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.

53739 lines
1.9MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. ==============================================================================
  25. This header contains the entire Juce source tree, and can be #included in
  26. all your source files.
  27. As well as including this in your files, you should also add juce_inline.cpp
  28. to your project (or juce_inline.mm on the Mac).
  29. ==============================================================================
  30. */
  31. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  32. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  33. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  34. /********* Start of inlined file: juce.h *********/
  35. #ifndef __JUCE_JUCEHEADER__
  36. #define __JUCE_JUCEHEADER__
  37. /*
  38. This is the main JUCE header file that applications need to include.
  39. */
  40. // (this includes things that need defining outside of the JUCE namespace)
  41. /********* Start of inlined file: juce_StandardHeader.h *********/
  42. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  43. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  44. /** Current Juce version number.
  45. See also SystemStats::getJUCEVersion() for a string version.
  46. */
  47. #define JUCE_MAJOR_VERSION 1
  48. #define JUCE_MINOR_VERSION 46
  49. /** Current Juce version number.
  50. Bits 16 to 32 = major version.
  51. Bits 8 to 16 = minor version.
  52. Bits 0 to 8 = point release (not currently used).
  53. See also SystemStats::getJUCEVersion() for a string version.
  54. */
  55. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8))
  56. /********* Start of inlined file: juce_Config.h *********/
  57. #ifndef __JUCE_CONFIG_JUCEHEADER__
  58. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  59. /*
  60. This file contains macros that enable/disable various JUCE features.
  61. */
  62. /** The name of the namespace that all Juce classes and functions will be
  63. put inside. If this is not defined, no namespace will be used.
  64. */
  65. #ifndef JUCE_NAMESPACE
  66. #define JUCE_NAMESPACE juce
  67. #endif
  68. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  69. but if you define this value, you can override this can force it to be true or
  70. false.
  71. */
  72. #ifndef JUCE_FORCE_DEBUG
  73. //#define JUCE_FORCE_DEBUG 1
  74. #endif
  75. /** If this flag is enabled, the the jassert and jassertfalse macros will
  76. always use Logger::writeToLog() to write a message when an assertion happens.
  77. Enabling it will also leave this turned on in release builds. When it's disabled,
  78. however, the jassert and jassertfalse macros will not be compiled in a
  79. release build.
  80. @see jassert, jassertfalse, Logger
  81. */
  82. #ifndef JUCE_LOG_ASSERTIONS
  83. // #define JUCE_LOG_ASSERTIONS 1
  84. #endif
  85. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  86. which the ASIOAudioIODevice class can't be built. See the comments in the
  87. ASIOAudioIODevice class's header file for more info about this.
  88. (This only affects a Win32 build)
  89. */
  90. #ifndef JUCE_ASIO
  91. #define JUCE_ASIO 1
  92. #endif
  93. /** Comment out this macro to disable building of ALSA device support on Linux.
  94. */
  95. #ifndef JUCE_ALSA
  96. #define JUCE_ALSA 1
  97. #endif
  98. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  99. have the SDK installed.
  100. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  101. classes will be unavailable.
  102. On Windows, if you enable this, you'll need to have the QuickTime SDK
  103. installed, and its header files will need to be on your include path.
  104. */
  105. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  106. #define JUCE_QUICKTIME 1
  107. #endif
  108. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  109. have the appropriate headers and libraries available. If it's not enabled, the
  110. OpenGLComponent class will be unavailable.
  111. */
  112. #ifndef JUCE_OPENGL
  113. #define JUCE_OPENGL 1
  114. #endif
  115. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  116. If you're not going to need either of these formats, turn off the flags to
  117. avoid bloating your codebase with them.
  118. */
  119. #ifndef JUCE_USE_FLAC
  120. #define JUCE_USE_FLAC 1
  121. #endif
  122. #ifndef JUCE_USE_OGGVORBIS
  123. #define JUCE_USE_OGGVORBIS 1
  124. #endif
  125. /** This flag lets you enable support for CD-burning. You might want to disable
  126. it to build without the MS SDK under windows.
  127. */
  128. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  129. #define JUCE_USE_CDBURNER 1
  130. #endif
  131. /** Enabling this macro means that all regions that get repainted will have a coloured
  132. line drawn around them.
  133. This is handy if you're trying to optimise drawing, because it lets you easily see
  134. when anything is being repainted unnecessarily.
  135. */
  136. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  137. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  138. #endif
  139. /** Enable this under Linux to use Xinerama for multi-monitor support.
  140. */
  141. #ifndef JUCE_USE_XINERAMA
  142. #define JUCE_USE_XINERAMA 1
  143. #endif
  144. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  145. */
  146. #ifndef JUCE_USE_XSHM
  147. #define JUCE_USE_XSHM 1
  148. #endif
  149. /** Enabling this builds support for VST audio plugins.
  150. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  151. */
  152. #ifndef JUCE_PLUGINHOST_VST
  153. // #define JUCE_PLUGINHOST_VST 1
  154. #endif
  155. /** Enabling this builds support for AudioUnit audio plugins.
  156. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  157. */
  158. #ifndef JUCE_PLUGINHOST_AU
  159. // #define JUCE_PLUGINHOST_AU 1
  160. #endif
  161. /** Enabling this will avoid including any UI code in the build. This is handy for
  162. writing command-line utilities, e.g. on linux boxes which don't have some
  163. of the UI libraries installed.
  164. */
  165. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  166. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  167. #endif
  168. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  169. */
  170. #ifndef JUCE_WEB_BROWSER
  171. #define JUCE_WEB_BROWSER 1
  172. #endif
  173. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  174. codebase - you might need to use this if you're linking to some of these libraries
  175. yourself.
  176. */
  177. #ifndef JUCE_INCLUDE_ZLIB_CODE
  178. #define JUCE_INCLUDE_ZLIB_CODE 1
  179. #endif
  180. #ifndef JUCE_INCLUDE_FLAC_CODE
  181. #define JUCE_INCLUDE_FLAC_CODE 1
  182. #endif
  183. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  184. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  185. #endif
  186. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  187. #define JUCE_INCLUDE_PNGLIB_CODE 1
  188. #endif
  189. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  190. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  191. #endif
  192. /** Enable this to add extra memory-leak info to the new and delete operators.
  193. (Currently, this only affects Windows builds in debug mode).
  194. */
  195. #ifndef JUCE_CHECK_MEMORY_LEAKS
  196. #define JUCE_CHECK_MEMORY_LEAKS 1
  197. #endif
  198. /** Enable this to turn on juce's internal catching of exceptions.
  199. Turning it off will avoid any exception catching. With it on, all exceptions
  200. are passed to the JUCEApplication::unhandledException() callback for logging.
  201. */
  202. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  204. #endif
  205. /** If this macro is set, the Juce String class will use unicode as its
  206. internal representation. If it isn't set, it'll use ANSI.
  207. */
  208. #ifndef JUCE_STRINGS_ARE_UNICODE
  209. #define JUCE_STRINGS_ARE_UNICODE 1
  210. #endif
  211. #endif
  212. /********* End of inlined file: juce_Config.h *********/
  213. #ifdef JUCE_NAMESPACE
  214. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  215. #define END_JUCE_NAMESPACE }
  216. #else
  217. #define BEGIN_JUCE_NAMESPACE
  218. #define END_JUCE_NAMESPACE
  219. #endif
  220. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  221. /********* Start of inlined file: juce_PlatformDefs.h *********/
  222. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  223. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  224. /* This file figures out which platform is being built, and defines some macros
  225. that the rest of the code can use for OS-specific compilation.
  226. Macros that will be set here are:
  227. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  228. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  229. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  230. - Either JUCE_INTEL or JUCE_PPC
  231. - Either JUCE_GCC or JUCE_MSVC
  232. On the Mac, it also defines MACOS_10_2_OR_EARLIER if the build is targeting OSX10.2,
  233. and MACOS_10_3_OR_EARLIER if it is targeting either 10.2 or 10.3
  234. It also includes a set of macros for debug console output and assertions.
  235. */
  236. #if (defined (_WIN32) || defined (_WIN64))
  237. #define JUCE_WIN32 1
  238. #else
  239. #if defined (LINUX) || defined (__linux__)
  240. #define JUCE_LINUX 1
  241. #else
  242. #define JUCE_MAC 1
  243. #endif
  244. #endif
  245. #if JUCE_WIN32
  246. #ifdef _MSC_VER
  247. #ifdef _WIN64
  248. #define JUCE_64BIT 1
  249. #else
  250. #define JUCE_32BIT 1
  251. #endif
  252. #endif
  253. #ifdef _DEBUG
  254. #define JUCE_DEBUG 1
  255. #endif
  256. /** If defined, this indicates that the processor is little-endian. */
  257. #define JUCE_LITTLE_ENDIAN 1
  258. #define JUCE_INTEL 1
  259. #endif
  260. #if JUCE_MAC
  261. #include <CoreFoundation/CoreFoundation.h>
  262. #ifndef NDEBUG
  263. #define JUCE_DEBUG 1
  264. #endif
  265. #ifdef __LITTLE_ENDIAN__
  266. #define JUCE_LITTLE_ENDIAN 1
  267. #else
  268. #define JUCE_BIG_ENDIAN 1
  269. #endif
  270. #if defined (__ppc__) || defined (__ppc64__)
  271. #define JUCE_PPC 1
  272. #else
  273. #define JUCE_INTEL 1
  274. #endif
  275. #ifdef __LP64__
  276. #define JUCE_64BIT 1
  277. #else
  278. #define JUCE_32BIT 1
  279. #endif
  280. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  281. #define MACOS_10_2_OR_EARLIER 1
  282. #endif
  283. #if (! defined (MAC_OS_X_VERSION_10_4)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  284. #define MACOS_10_3_OR_EARLIER 1
  285. #endif
  286. #if (! defined (MAC_OS_X_VERSION_10_5)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  287. #define MACOS_10_4_OR_EARLIER 1
  288. #endif
  289. #endif
  290. #if JUCE_LINUX
  291. #ifdef _DEBUG
  292. #define JUCE_DEBUG 1
  293. #endif
  294. // Allow override for big-endian Linux platforms
  295. #ifndef JUCE_BIG_ENDIAN
  296. #define JUCE_LITTLE_ENDIAN 1
  297. #endif
  298. #if defined (__LP64__) || defined (_LP64)
  299. #define JUCE_64BIT 1
  300. #else
  301. #define JUCE_32BIT 1
  302. #endif
  303. #define JUCE_INTEL 1
  304. #endif
  305. #ifdef JUCE_FORCE_DEBUG
  306. #undef JUCE_DEBUG
  307. #if JUCE_FORCE_DEBUG
  308. #define JUCE_DEBUG 1
  309. #endif
  310. #endif
  311. // Compiler type macros.
  312. #ifdef __GNUC__
  313. #define JUCE_GCC 1
  314. #elif defined (_MSC_VER)
  315. #define JUCE_MSVC 1
  316. #if _MSC_VER >= 1400
  317. #define JUCE_USE_INTRINSICS 1
  318. #endif
  319. #else
  320. #error unknown compiler
  321. #endif
  322. /** This macro defines the C calling convention used as the standard for Juce calls. */
  323. #if JUCE_MSVC
  324. #define JUCE_CALLTYPE __stdcall
  325. #else
  326. #define JUCE_CALLTYPE
  327. #endif
  328. // Debugging and assertion macros
  329. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  330. #if JUCE_LOG_ASSERTIONS
  331. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  332. #elif defined (JUCE_DEBUG)
  333. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  334. #else
  335. #define juce_LogCurrentAssertion
  336. #endif
  337. #ifdef JUCE_DEBUG
  338. // If debugging is enabled..
  339. /** Writes a string to the standard error stream.
  340. This is only compiled in a debug build.
  341. @see Logger::outputDebugString
  342. */
  343. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  344. /** Printf's a string to the standard error stream.
  345. This is only compiled in a debug build.
  346. @see Logger::outputDebugString
  347. */
  348. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  349. // Assertions..
  350. #if JUCE_WIN32 || DOXYGEN
  351. #if JUCE_USE_INTRINSICS
  352. #pragma intrinsic (__debugbreak)
  353. /** This will try to break the debugger if one is currently hosting this app.
  354. @see jassert()
  355. */
  356. #define juce_breakDebugger __debugbreak();
  357. #elif JUCE_GCC
  358. /** This will try to break the debugger if one is currently hosting this app.
  359. @see jassert()
  360. */
  361. #define juce_breakDebugger asm("int $3");
  362. #else
  363. /** This will try to break the debugger if one is currently hosting this app.
  364. @see jassert()
  365. */
  366. #define juce_breakDebugger { __asm int 3 }
  367. #endif
  368. #elif JUCE_MAC
  369. #define juce_breakDebugger Debugger();
  370. #elif JUCE_LINUX
  371. #define juce_breakDebugger kill (0, SIGTRAP);
  372. #endif
  373. /** This will always cause an assertion failure.
  374. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  375. in juce_Config.h).
  376. @see jassert()
  377. */
  378. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  379. /** Platform-independent assertion macro.
  380. This gets optimised out when not being built with debugging turned on.
  381. Be careful not to call any functions within its arguments that are vital to
  382. the behaviour of the program, because these won't get called in the release
  383. build.
  384. @see jassertfalse
  385. */
  386. #define jassert(expression) { if (! (expression)) jassertfalse }
  387. #else
  388. // If debugging is disabled, these dummy debug and assertion macros are used..
  389. #define DBG(dbgtext)
  390. #define DBG_PRINTF(dbgprintf)
  391. #define jassertfalse { juce_LogCurrentAssertion }
  392. #if JUCE_LOG_ASSERTIONS
  393. #define jassert(expression) { if (! (expression)) jassertfalse }
  394. #else
  395. #define jassert(a) { }
  396. #endif
  397. #endif
  398. #ifndef DOXYGEN
  399. template <bool b> struct JuceStaticAssert;
  400. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  401. #endif
  402. /** A compile-time assertion macro.
  403. If the expression parameter is false, the macro will cause a compile error.
  404. */
  405. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  406. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  407. #define JUCE_TRY try
  408. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  409. object so they can be logged by the application if it wants to.
  410. */
  411. #define JUCE_CATCH_EXCEPTION \
  412. catch (const std::exception& e) \
  413. { \
  414. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  415. } \
  416. catch (...) \
  417. { \
  418. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  419. }
  420. #define JUCE_CATCH_ALL catch (...) {}
  421. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  422. #else
  423. #define JUCE_TRY
  424. #define JUCE_CATCH_EXCEPTION
  425. #define JUCE_CATCH_ALL
  426. #define JUCE_CATCH_ALL_ASSERT
  427. #endif
  428. // Macros for inlining.
  429. #if JUCE_MSVC
  430. /** A platform-independent way of forcing an inline function.
  431. Use the syntax: @code
  432. forcedinline void myfunction (int x)
  433. @endcode
  434. */
  435. #ifdef JUCE_DEBUG
  436. #define forcedinline __forceinline
  437. #else
  438. #define forcedinline inline
  439. #endif
  440. /** A platform-independent way of stopping the compiler inlining a function.
  441. Use the syntax: @code
  442. juce_noinline void myfunction (int x)
  443. @endcode
  444. */
  445. #define juce_noinline
  446. #else
  447. /** A platform-independent way of forcing an inline function.
  448. Use the syntax: @code
  449. forcedinline void myfunction (int x)
  450. @endcode
  451. */
  452. #ifndef JUCE_DEBUG
  453. #define forcedinline inline __attribute__((always_inline))
  454. #else
  455. #define forcedinline inline
  456. #endif
  457. /** A platform-independent way of stopping the compiler inlining a function.
  458. Use the syntax: @code
  459. juce_noinline void myfunction (int x)
  460. @endcode
  461. */
  462. #define juce_noinline __attribute__((noinline))
  463. #endif
  464. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  465. /********* End of inlined file: juce_PlatformDefs.h *********/
  466. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  467. #if JUCE_MSVC
  468. #pragma warning (push)
  469. #pragma warning (disable: 4514 4245 4100)
  470. #endif
  471. #include <cstdlib>
  472. #include <cstdarg>
  473. #include <climits>
  474. #include <cmath>
  475. #include <cwchar>
  476. #include <stdexcept>
  477. #include <typeinfo>
  478. #include <cstring>
  479. #include <cstdio>
  480. #if JUCE_MAC || JUCE_LINUX
  481. #include <pthread.h>
  482. #endif
  483. #if JUCE_USE_INTRINSICS
  484. #include <intrin.h>
  485. #endif
  486. #if JUCE_MAC
  487. #if MACOS_10_3_OR_EARLIER
  488. #include <CoreServices/CoreServices.h>
  489. #else
  490. #include <libkern/OSAtomic.h>
  491. #endif
  492. #endif
  493. #if JUCE_LINUX
  494. #include <signal.h>
  495. #endif
  496. #if JUCE_MSVC && JUCE_DEBUG
  497. #include <crtdbg.h>
  498. #endif
  499. #if JUCE_MSVC
  500. #pragma warning (pop)
  501. #endif
  502. // DLL building settings on Win32
  503. #if JUCE_MSVC
  504. #ifdef JUCE_DLL_BUILD
  505. #define JUCE_API __declspec (dllexport)
  506. #pragma warning (disable: 4251)
  507. #elif defined (JUCE_DLL)
  508. #define JUCE_API __declspec (dllimport)
  509. #pragma warning (disable: 4251)
  510. #endif
  511. #endif
  512. #ifndef JUCE_API
  513. /** This macro is added to all juce public class declarations. */
  514. #define JUCE_API
  515. #endif
  516. /** This macro is added to all juce public function declarations. */
  517. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  518. // Now include some basics that are needed by most of the Juce classes...
  519. BEGIN_JUCE_NAMESPACE
  520. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  521. #if JUCE_LOG_ASSERTIONS
  522. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  523. #endif
  524. /********* Start of inlined file: juce_Memory.h *********/
  525. #ifndef __JUCE_MEMORY_JUCEHEADER__
  526. #define __JUCE_MEMORY_JUCEHEADER__
  527. /*
  528. This file defines the various juce_malloc(), juce_free() macros that should be used in
  529. preference to the standard calls.
  530. */
  531. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  532. #ifndef JUCE_DLL
  533. // Win32 debug non-DLL versions..
  534. /** This should be used instead of calling malloc directly. */
  535. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  536. /** This should be used instead of calling calloc directly. */
  537. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  538. /** This should be used instead of calling realloc directly. */
  539. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  540. /** This should be used instead of calling free directly. */
  541. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  542. #else
  543. // Win32 debug DLL versions..
  544. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  545. // way all juce calls in the DLL and in the host API will all use the same allocator.
  546. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  547. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  548. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  549. extern JUCE_API void juce_DebugFree (void* const block);
  550. /** This should be used instead of calling malloc directly. */
  551. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  552. /** This should be used instead of calling calloc directly. */
  553. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  554. /** This should be used instead of calling realloc directly. */
  555. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  556. /** This should be used instead of calling free directly. */
  557. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  558. #endif
  559. #if ! defined (_AFXDLL)
  560. /** This macro can be added to classes to add extra debugging information to the memory
  561. allocated for them, so you can see the type of objects involved when there's a dump
  562. of leaked objects at program shutdown. (Only works on win32 at the moment).
  563. */
  564. #define juce_UseDebuggingNewOperator \
  565. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  566. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  567. static void operator delete (void* p) { juce_free (p); }
  568. #endif
  569. #elif defined (JUCE_DLL)
  570. // Win32 DLL (release) versions..
  571. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  572. // way all juce calls in the DLL and in the host API will all use the same allocator.
  573. extern JUCE_API void* juce_Malloc (const int size);
  574. extern JUCE_API void* juce_Calloc (const int size);
  575. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  576. extern JUCE_API void juce_Free (void* const block);
  577. /** This should be used instead of calling malloc directly. */
  578. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  579. /** This should be used instead of calling calloc directly. */
  580. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  581. /** This should be used instead of calling realloc directly. */
  582. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  583. /** This should be used instead of calling free directly. */
  584. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  585. #define juce_UseDebuggingNewOperator \
  586. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  587. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  588. static void operator delete (void* p) { juce_free (p); }
  589. #else
  590. // Mac, Linux and Win32 (release) versions..
  591. /** This should be used instead of calling malloc directly. */
  592. #define juce_malloc(numBytes) malloc (numBytes)
  593. /** This should be used instead of calling calloc directly. */
  594. #define juce_calloc(numBytes) calloc (1, numBytes)
  595. /** This should be used instead of calling realloc directly. */
  596. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  597. /** This should be used instead of calling free directly. */
  598. #define juce_free(location) free (location)
  599. #endif
  600. /** This macro can be added to classes to add extra debugging information to the memory
  601. allocated for them, so you can see the type of objects involved when there's a dump
  602. of leaked objects at program shutdown. (Only works on win32 at the moment).
  603. Note that if you create a class that inherits from a class that uses this macro,
  604. your class must also use the macro, otherwise you'll probably get compile errors
  605. because of ambiguous new operators.
  606. Most of the JUCE classes use it, so see these for examples of where it should go.
  607. */
  608. #ifndef juce_UseDebuggingNewOperator
  609. #define juce_UseDebuggingNewOperator
  610. #endif
  611. #if JUCE_MSVC
  612. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  613. E.g.
  614. @code
  615. juce_ThreadLocal int myVariable;
  616. @endcode
  617. */
  618. #define juce_ThreadLocal __declspec(thread)
  619. #else
  620. #define juce_ThreadLocal __thread
  621. #endif
  622. /** Clears a block of memory. */
  623. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  624. /** Clears a reference to a local structure. */
  625. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  626. /** A handy macro that calls delete on a pointer if it's non-zero, and
  627. then sets the pointer to null.
  628. */
  629. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  630. #endif // __JUCE_MEMORY_JUCEHEADER__
  631. /********* End of inlined file: juce_Memory.h *********/
  632. /********* Start of inlined file: juce_MathsFunctions.h *********/
  633. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  634. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  635. /*
  636. This file sets up some handy mathematical typdefs and functions.
  637. */
  638. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  639. /** A platform-independent 8-bit signed integer type. */
  640. typedef signed char int8;
  641. /** A platform-independent 8-bit unsigned integer type. */
  642. typedef unsigned char uint8;
  643. /** A platform-independent 16-bit signed integer type. */
  644. typedef signed short int16;
  645. /** A platform-independent 16-bit unsigned integer type. */
  646. typedef unsigned short uint16;
  647. /** A platform-independent 32-bit signed integer type. */
  648. typedef signed int int32;
  649. /** A platform-independent 32-bit unsigned integer type. */
  650. typedef unsigned int uint32;
  651. #if JUCE_MSVC
  652. /** A platform-independent 64-bit integer type. */
  653. typedef __int64 int64;
  654. /** A platform-independent 64-bit unsigned integer type. */
  655. typedef unsigned __int64 uint64;
  656. /** A platform-independent macro for writing 64-bit literals, needed because
  657. different compilers have different syntaxes for this.
  658. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  659. GCC, or 0x1000000000 for MSVC.
  660. */
  661. #define literal64bit(longLiteral) ((__int64) longLiteral)
  662. #else
  663. /** A platform-independent 64-bit integer type. */
  664. typedef long long int64;
  665. /** A platform-independent 64-bit unsigned integer type. */
  666. typedef unsigned long long uint64;
  667. /** A platform-independent macro for writing 64-bit literals, needed because
  668. different compilers have different syntaxes for this.
  669. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  670. GCC, or 0x1000000000 for MSVC.
  671. */
  672. #define literal64bit(longLiteral) (longLiteral##LL)
  673. #endif
  674. #if JUCE_64BIT
  675. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  676. typedef int64 pointer_sized_int;
  677. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  678. typedef uint64 pointer_sized_uint;
  679. #elif _MSC_VER >= 1300
  680. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  681. typedef _W64 int pointer_sized_int;
  682. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  683. typedef _W64 unsigned int pointer_sized_uint;
  684. #else
  685. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  686. typedef int pointer_sized_int;
  687. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  688. typedef unsigned int pointer_sized_uint;
  689. #endif
  690. /** A platform-independent unicode character type. */
  691. typedef wchar_t juce_wchar;
  692. // Some indispensible min/max functions
  693. /** Returns the larger of two values. */
  694. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  695. /** Returns the larger of two values. */
  696. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  697. /** Returns the larger of two values. */
  698. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  699. /** Returns the larger of two values. */
  700. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  701. /** Returns the larger of three values. */
  702. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  703. /** Returns the larger of three values. */
  704. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  705. /** Returns the larger of three values. */
  706. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  707. /** Returns the larger of three values. */
  708. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  709. /** Returns the larger of four values. */
  710. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  711. /** Returns the larger of four values. */
  712. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  713. /** Returns the larger of four values. */
  714. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  715. /** Returns the larger of four values. */
  716. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  717. /** Returns the smaller of two values. */
  718. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  719. /** Returns the smaller of two values. */
  720. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  721. /** Returns the smaller of two values. */
  722. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  723. /** Returns the smaller of two values. */
  724. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  725. /** Returns the smaller of three values. */
  726. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  727. /** Returns the smaller of three values. */
  728. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  729. /** Returns the smaller of three values. */
  730. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  731. /** Returns the smaller of three values. */
  732. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  733. /** Returns the smaller of four values. */
  734. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  735. /** Returns the smaller of four values. */
  736. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  737. /** Returns the smaller of four values. */
  738. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  739. /** Returns the smaller of four values. */
  740. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  741. /** Constrains a value to keep it within a given range.
  742. This will check that the specified value lies between the lower and upper bounds
  743. specified, and if not, will return the nearest value that would be in-range. Effectively,
  744. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  745. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  746. the results will be unpredictable.
  747. @param lowerLimit the minimum value to return
  748. @param upperLimit the maximum value to return
  749. @param valueToConstrain the value to try to return
  750. @returns the closest value to valueToConstrain which lies between lowerLimit
  751. and upperLimit (inclusive)
  752. @see jlimit0To, jmin, jmax
  753. */
  754. template <class Type>
  755. inline Type jlimit (const Type lowerLimit,
  756. const Type upperLimit,
  757. const Type valueToConstrain) throw()
  758. {
  759. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  760. return (valueToConstrain < lowerLimit) ? lowerLimit
  761. : ((valueToConstrain > upperLimit) ? upperLimit
  762. : valueToConstrain);
  763. }
  764. /** Handy function to swap two values over.
  765. */
  766. template <class Type>
  767. inline void swapVariables (Type& variable1, Type& variable2) throw()
  768. {
  769. const Type tempVal = variable1;
  770. variable1 = variable2;
  771. variable2 = tempVal;
  772. }
  773. /** Handy macro for getting the number of elements in a simple const C array.
  774. E.g.
  775. @code
  776. static int myArray[] = { 1, 2, 3 };
  777. int numElements = numElementsInArray (myArray) // returns 3
  778. @endcode
  779. */
  780. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  781. // Some useful maths functions that aren't always present with all compilers and build settings.
  782. #if JUCE_WIN32 || defined (DOXYGEN)
  783. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  784. versions of these functions of various platforms and compilers. */
  785. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  786. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  787. versions of these functions of various platforms and compilers. */
  788. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  789. #elif MACOS_10_2_OR_EARLIER
  790. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  791. versions of these functions of various platforms and compilers. */
  792. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  793. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  794. versions of these functions of various platforms and compilers. */
  795. forcedinline float juce_hypotf (float a, float b) { return (float) hypot (a, b); }
  796. forcedinline float sinf (const float a) { return (float) sin (a); }
  797. forcedinline float cosf (const float a) { return (float) cos (a); }
  798. forcedinline float tanf (const float a) { return (float) tan (a); }
  799. forcedinline float atan2f (const float a, const float b) { return (float) atan2 (a, b); }
  800. forcedinline float sqrtf (const float a) { return (float) sqrt (a); }
  801. forcedinline float logf (const float a) { return (float) log (a); }
  802. forcedinline float powf (const float a, const float b) { return (float) pow (a, b); }
  803. forcedinline float expf (const float a) { return (float) exp (a); }
  804. #else
  805. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  806. versions of these functions of various platforms and compilers. */
  807. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  808. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  809. versions of these functions of various platforms and compilers. */
  810. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  811. #endif
  812. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  813. /** A predefined value for Pi, at double-precision.
  814. @see float_Pi
  815. */
  816. const double double_Pi = 3.1415926535897932384626433832795;
  817. /** A predefined value for Pi, at sngle-precision.
  818. @see double_Pi
  819. */
  820. const float float_Pi = 3.14159265358979323846f;
  821. /** The isfinite() method seems to vary greatly between platforms, so this is a
  822. platform-independent macro for it.
  823. */
  824. #if JUCE_LINUX
  825. #define juce_isfinite(v) std::isfinite(v)
  826. #elif JUCE_MAC
  827. #if MACOS_10_2_OR_EARLIER
  828. #define juce_isfinite(v) __isfinite(v)
  829. #elif MACOS_10_3_OR_EARLIER
  830. #ifdef isfinite
  831. #define juce_isfinite(v) isfinite(v)
  832. #else
  833. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  834. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  835. #endif
  836. #else
  837. #define juce_isfinite(v) std::isfinite(v)
  838. #endif
  839. #elif JUCE_WIN32 && ! defined (isfinite)
  840. #define juce_isfinite(v) _finite(v)
  841. #else
  842. #define juce_isfinite(v) isfinite(v)
  843. #endif
  844. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  845. /********* End of inlined file: juce_MathsFunctions.h *********/
  846. /********* Start of inlined file: juce_DataConversions.h *********/
  847. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  848. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  849. #if JUCE_USE_INTRINSICS
  850. #pragma intrinsic (_byteswap_ulong)
  851. #endif
  852. // Endianness conversions..
  853. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  854. forcedinline uint32 swapByteOrder (uint32 n) throw()
  855. {
  856. #if JUCE_MAC
  857. // Mac version
  858. return CFSwapInt32 (n);
  859. #elif JUCE_GCC
  860. // Inpenetrable GCC version..
  861. asm("bswap %%eax" : "=a"(n) : "a"(n));
  862. return n;
  863. #elif JUCE_USE_INTRINSICS
  864. // Win32 intrinsics version..
  865. return _byteswap_ulong (n);
  866. #else
  867. // Win32 version..
  868. __asm {
  869. mov eax, n
  870. bswap eax
  871. mov n, eax
  872. }
  873. return n;
  874. #endif
  875. }
  876. /** Swaps the byte-order of a 16-bit short. */
  877. inline uint16 swapByteOrder (const uint16 n) throw()
  878. {
  879. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  880. // Win32 intrinsics version..
  881. return (uint16) _byteswap_ushort (n);
  882. #else
  883. return (uint16) ((n << 8) | (n >> 8));
  884. #endif
  885. }
  886. inline uint64 swapByteOrder (const uint64 value) throw()
  887. {
  888. #if JUCE_MAC
  889. return CFSwapInt64 (value);
  890. #elif JUCE_USE_INTRINSICS
  891. return _byteswap_uint64 (value);
  892. #else
  893. return (((int64) swapByteOrder ((uint32) value)) << 32)
  894. | swapByteOrder ((uint32) (value >> 32));
  895. #endif
  896. }
  897. #if JUCE_LITTLE_ENDIAN
  898. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  899. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  900. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  901. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  902. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  903. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  904. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  905. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  906. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  907. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  908. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  909. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  910. /** Turns 4 bytes into a little-endian integer. */
  911. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  912. /** Turns 2 bytes into a little-endian integer. */
  913. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  914. /** Turns 4 bytes into a big-endian integer. */
  915. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  916. /** Turns 2 bytes into a big-endian integer. */
  917. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  918. #else
  919. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  920. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  921. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  922. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  923. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  924. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  925. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  926. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  927. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  928. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  929. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  930. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  931. /** Turns 4 bytes into a little-endian integer. */
  932. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  933. /** Turns 2 bytes into a little-endian integer. */
  934. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  935. /** Turns 4 bytes into a big-endian integer. */
  936. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  937. /** Turns 2 bytes into a big-endian integer. */
  938. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  939. #endif
  940. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  941. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  942. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  943. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  944. /** Copies a 24-bit number to 3 little-endian bytes. */
  945. inline void littleEndian24BitToChars (const int value, char* const destBytes) throw() { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  946. /** Copies a 24-bit number to 3 big-endian bytes. */
  947. inline void bigEndian24BitToChars (const int value, char* const destBytes) throw() { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  948. /** Fast floating-point-to-integer conversion.
  949. This is faster than using the normal c++ cast to convert a double to an int, and
  950. it will round the value to the nearest integer, rather than rounding it down
  951. like the normal cast does.
  952. Note that this routine gets its speed at the expense of some accuracy, and when
  953. rounding values whose floating point component is exactly 0.5, odd numbers and
  954. even numbers will be rounded up or down differently. For a more accurate conversion,
  955. see roundDoubleToIntAccurate().
  956. */
  957. inline int roundDoubleToInt (const double value) throw()
  958. {
  959. union { int asInt[2]; double asDouble; } n;
  960. n.asDouble = value + 6755399441055744.0;
  961. #if JUCE_BIG_ENDIAN
  962. return n.asInt [1];
  963. #else
  964. return n.asInt [0];
  965. #endif
  966. }
  967. /** Fast floating-point-to-integer conversion.
  968. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  969. fine for values above zero, but negative numbers are rounded the wrong way.
  970. */
  971. inline int roundDoubleToIntAccurate (const double value) throw()
  972. {
  973. return roundDoubleToInt (value + 1.5e-8);
  974. }
  975. /** Fast floating-point-to-integer conversion.
  976. This is faster than using the normal c++ cast to convert a float to an int, and
  977. it will round the value to the nearest integer, rather than rounding it down
  978. like the normal cast does.
  979. Note that this routine gets its speed at the expense of some accuracy, and when
  980. rounding values whose floating point component is exactly 0.5, odd numbers and
  981. even numbers will be rounded up or down differently.
  982. */
  983. inline int roundFloatToInt (const float value) throw()
  984. {
  985. union { int asInt[2]; double asDouble; } n;
  986. n.asDouble = value + 6755399441055744.0;
  987. #if JUCE_BIG_ENDIAN
  988. return n.asInt [1];
  989. #else
  990. return n.asInt [0];
  991. #endif
  992. }
  993. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  994. /********* End of inlined file: juce_DataConversions.h *********/
  995. /********* Start of inlined file: juce_Logger.h *********/
  996. #ifndef __JUCE_LOGGER_JUCEHEADER__
  997. #define __JUCE_LOGGER_JUCEHEADER__
  998. /********* Start of inlined file: juce_String.h *********/
  999. #ifndef __JUCE_STRING_JUCEHEADER__
  1000. #define __JUCE_STRING_JUCEHEADER__
  1001. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1002. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1003. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1004. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1005. (in the default system encoding) as its internal representation.
  1006. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1007. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1008. literals in the T("abcd") macro, so that it all works nicely either way round.
  1009. */
  1010. #if JUCE_STRINGS_ARE_UNICODE
  1011. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1012. typedef juce_wchar tchar;
  1013. #define juce_tcharToWideChar(c) (c)
  1014. #else
  1015. #define JUCE_T(stringLiteral) (stringLiteral)
  1016. typedef char tchar;
  1017. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1018. #endif
  1019. #if ! JUCE_DONT_DEFINE_MACROS
  1020. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1021. or unicode.
  1022. If you write your string literals in the form T("xyz"), this will either be compiled
  1023. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1024. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1025. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1026. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1027. the juce/src directory) to avoid defining this macro. See the comments in
  1028. juce_withoutMacros.h for more info.
  1029. */
  1030. #define T(stringLiteral) JUCE_T(stringLiteral)
  1031. #endif
  1032. /**
  1033. A set of methods for manipulating characters and character strings, with
  1034. duplicate methods to handle 8-bit and unicode characters.
  1035. These are defined as wrappers around the basic C string handlers, to provide
  1036. a clean, cross-platform layer, (because various platforms differ in the
  1037. range of C library calls that they provide).
  1038. @see String
  1039. */
  1040. class JUCE_API CharacterFunctions
  1041. {
  1042. public:
  1043. static int length (const char* const s) throw();
  1044. static int length (const juce_wchar* const s) throw();
  1045. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1046. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1047. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1048. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1049. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1050. static void append (char* dest, const char* src) throw();
  1051. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1052. static int compare (const char* const s1, const char* const s2) throw();
  1053. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1054. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1055. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1056. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1057. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1058. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1059. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1060. static const char* find (const char* const haystack, const char* const needle) throw();
  1061. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1062. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1063. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1064. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1065. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1066. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1067. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1068. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1069. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1070. static int getIntValue (const char* const s) throw();
  1071. static int getIntValue (const juce_wchar* s) throw();
  1072. static int64 getInt64Value (const char* s) throw();
  1073. static int64 getInt64Value (const juce_wchar* s) throw();
  1074. static double getDoubleValue (const char* const s) throw();
  1075. static double getDoubleValue (const juce_wchar* const s) throw();
  1076. static char toUpperCase (const char character) throw();
  1077. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1078. static void toUpperCase (char* s) throw();
  1079. static void toUpperCase (juce_wchar* s) throw();
  1080. static bool isUpperCase (const char character) throw();
  1081. static bool isUpperCase (const juce_wchar character) throw();
  1082. static char toLowerCase (const char character) throw();
  1083. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1084. static void toLowerCase (char* s) throw();
  1085. static void toLowerCase (juce_wchar* s) throw();
  1086. static bool isLowerCase (const char character) throw();
  1087. static bool isLowerCase (const juce_wchar character) throw();
  1088. static bool isWhitespace (const char character) throw();
  1089. static bool isWhitespace (const juce_wchar character) throw();
  1090. static bool isDigit (const char character) throw();
  1091. static bool isDigit (const juce_wchar character) throw();
  1092. static bool isLetter (const char character) throw();
  1093. static bool isLetter (const juce_wchar character) throw();
  1094. static bool isLetterOrDigit (const char character) throw();
  1095. static bool isLetterOrDigit (const juce_wchar character) throw();
  1096. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1097. hex digit.
  1098. */
  1099. static int getHexDigitValue (const tchar digit) throw();
  1100. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1101. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1102. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1103. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1104. };
  1105. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1106. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1107. /**
  1108. The JUCE String class!
  1109. Using a reference-counted internal representation, these strings are fast
  1110. and efficient, and there are methods to do just about any operation you'll ever
  1111. dream of.
  1112. @see StringArray, StringPairArray
  1113. */
  1114. class JUCE_API String
  1115. {
  1116. public:
  1117. /** Creates an empty string.
  1118. @see empty
  1119. */
  1120. String() throw();
  1121. /** Creates a copy of another string. */
  1122. String (const String& other) throw();
  1123. /** Creates a string from a zero-terminated text string.
  1124. The string is assumed to be stored in the default system encoding.
  1125. */
  1126. String (const char* const text) throw();
  1127. /** Creates a string from an string of characters.
  1128. This will use up the the first maxChars characters of the string (or
  1129. less if the string is actually shorter)
  1130. */
  1131. String (const char* const text,
  1132. const int maxChars) throw();
  1133. /** Creates a string from a zero-terminated unicode text string. */
  1134. String (const juce_wchar* const unicodeText) throw();
  1135. /** Creates a string from a unicode text string.
  1136. This will use up the the first maxChars characters of the string (or
  1137. less if the string is actually shorter)
  1138. */
  1139. String (const juce_wchar* const unicodeText,
  1140. const int maxChars) throw();
  1141. /** Creates a string from a single character. */
  1142. static const String charToString (const tchar character) throw();
  1143. /** Destructor. */
  1144. ~String() throw();
  1145. /** This is an empty string that can be used whenever one is needed.
  1146. It's better to use this than String() because it explains what's going on
  1147. and is more efficient.
  1148. */
  1149. static const String empty;
  1150. /** Generates a probably-unique 32-bit hashcode from this string. */
  1151. int hashCode() const throw();
  1152. /** Generates a probably-unique 64-bit hashcode from this string. */
  1153. int64 hashCode64() const throw();
  1154. /** Returns the number of characters in the string. */
  1155. int length() const throw();
  1156. // Assignment and concatenation operators..
  1157. /** Replaces this string's contents with another string. */
  1158. const String& operator= (const tchar* const other) throw();
  1159. /** Replaces this string's contents with another string. */
  1160. const String& operator= (const String& other) throw();
  1161. /** Appends another string at the end of this one. */
  1162. const String& operator+= (const tchar* const textToAppend) throw();
  1163. /** Appends another string at the end of this one. */
  1164. const String& operator+= (const String& stringToAppend) throw();
  1165. /** Appends a character at the end of this string. */
  1166. const String& operator+= (const char characterToAppend) throw();
  1167. /** Appends a character at the end of this string. */
  1168. const String& operator+= (const juce_wchar characterToAppend) throw();
  1169. /** Appends a string at the end of this one.
  1170. @param textToAppend the string to add
  1171. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1172. */
  1173. void append (const tchar* const textToAppend,
  1174. const int maxCharsToTake) throw();
  1175. /** Appends a string at the end of this one.
  1176. @returns the concatenated string
  1177. */
  1178. const String operator+ (const String& stringToAppend) const throw();
  1179. /** Appends a string at the end of this one.
  1180. @returns the concatenated string
  1181. */
  1182. const String operator+ (const tchar* const textToAppend) const throw();
  1183. /** Appends a character at the end of this one.
  1184. @returns the concatenated string
  1185. */
  1186. const String operator+ (const tchar characterToAppend) const throw();
  1187. /** Appends a character at the end of this string. */
  1188. String& operator<< (const char n) throw();
  1189. /** Appends a character at the end of this string. */
  1190. String& operator<< (const juce_wchar n) throw();
  1191. /** Appends another string at the end of this one. */
  1192. String& operator<< (const char* const text) throw();
  1193. /** Appends another string at the end of this one. */
  1194. String& operator<< (const juce_wchar* const text) throw();
  1195. /** Appends another string at the end of this one. */
  1196. String& operator<< (const String& text) throw();
  1197. /** Appends a decimal number at the end of this string. */
  1198. String& operator<< (const short number) throw();
  1199. /** Appends a decimal number at the end of this string. */
  1200. String& operator<< (const int number) throw();
  1201. /** Appends a decimal number at the end of this string. */
  1202. String& operator<< (const unsigned int number) throw();
  1203. /** Appends a decimal number at the end of this string. */
  1204. String& operator<< (const float number) throw();
  1205. /** Appends a decimal number at the end of this string. */
  1206. String& operator<< (const double number) throw();
  1207. // Comparison methods..
  1208. /** Returns true if the string contains no characters.
  1209. Note that there's also an isNotEmpty() method to help write readable code.
  1210. */
  1211. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1212. /** Returns true if the string contains at least one character.
  1213. Note that there's also an isEmpty() method to help write readable code.
  1214. */
  1215. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1216. /** Case-sensitive comparison with another string. */
  1217. bool operator== (const String& other) const throw();
  1218. /** Case-sensitive comparison with another string. */
  1219. bool operator== (const tchar* const other) const throw();
  1220. /** Case-sensitive comparison with another string. */
  1221. bool operator!= (const String& other) const throw();
  1222. /** Case-sensitive comparison with another string. */
  1223. bool operator!= (const tchar* const other) const throw();
  1224. /** Case-insensitive comparison with another string. */
  1225. bool equalsIgnoreCase (const String& other) const throw();
  1226. /** Case-insensitive comparison with another string. */
  1227. bool equalsIgnoreCase (const tchar* const other) const throw();
  1228. /** Case-sensitive comparison with another string. */
  1229. bool operator> (const String& other) const throw();
  1230. /** Case-sensitive comparison with another string. */
  1231. bool operator< (const tchar* const other) const throw();
  1232. /** Case-sensitive comparison with another string. */
  1233. bool operator>= (const String& other) const throw();
  1234. /** Case-sensitive comparison with another string. */
  1235. bool operator<= (const tchar* const other) const throw();
  1236. /** Case-sensitive comparison with another string.
  1237. @returns 0 if the two strings are identical; negative if this string
  1238. comes before the other one alphabetically, or positive if it
  1239. comes after it.
  1240. */
  1241. int compare (const tchar* const other) const throw();
  1242. /** Case-insensitive comparison with another string.
  1243. @returns 0 if the two strings are identical; negative if this string
  1244. comes before the other one alphabetically, or positive if it
  1245. comes after it.
  1246. */
  1247. int compareIgnoreCase (const tchar* const other) const throw();
  1248. /** Lexicographic comparison with another string.
  1249. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1250. characters, making it good for sorting human-readable strings.
  1251. @returns 0 if the two strings are identical; negative if this string
  1252. comes before the other one alphabetically, or positive if it
  1253. comes after it.
  1254. */
  1255. int compareLexicographically (const tchar* const other) const throw();
  1256. /** Tests whether the string begins with another string.
  1257. Uses a case-sensitive comparison.
  1258. */
  1259. bool startsWith (const tchar* const text) const throw();
  1260. /** Tests whether the string begins with a particular character.
  1261. Uses a case-sensitive comparison.
  1262. */
  1263. bool startsWithChar (const tchar character) const throw();
  1264. /** Tests whether the string begins with another string.
  1265. Uses a case-insensitive comparison.
  1266. */
  1267. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1268. /** Tests whether the string ends with another string.
  1269. Uses a case-sensitive comparison.
  1270. */
  1271. bool endsWith (const tchar* const text) const throw();
  1272. /** Tests whether the string ends with a particular character.
  1273. Uses a case-sensitive comparison.
  1274. */
  1275. bool endsWithChar (const tchar character) const throw();
  1276. /** Tests whether the string ends with another string.
  1277. Uses a case-insensitive comparison.
  1278. */
  1279. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1280. /** Tests whether the string contains another substring.
  1281. Uses a case-sensitive comparison.
  1282. */
  1283. bool contains (const tchar* const text) const throw();
  1284. /** Tests whether the string contains a particular character.
  1285. Uses a case-sensitive comparison.
  1286. */
  1287. bool containsChar (const tchar character) const throw();
  1288. /** Tests whether the string contains another substring.
  1289. Uses a case-insensitive comparison.
  1290. */
  1291. bool containsIgnoreCase (const tchar* const text) const throw();
  1292. /** Tests whether the string contains another substring as a distict word.
  1293. @returns true if the string contains this word, surrounded by
  1294. non-alphanumeric characters
  1295. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1296. */
  1297. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1298. /** Tests whether the string contains another substring as a distict word.
  1299. @returns true if the string contains this word, surrounded by
  1300. non-alphanumeric characters
  1301. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1302. */
  1303. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1304. /** Finds an instance of another substring if it exists as a distict word.
  1305. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1306. then this will return the index of the start of the substring. If it isn't
  1307. found, then it will return -1
  1308. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1309. */
  1310. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1311. /** Finds an instance of another substring if it exists as a distict word.
  1312. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1313. then this will return the index of the start of the substring. If it isn't
  1314. found, then it will return -1
  1315. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1316. */
  1317. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1318. /** Looks for any of a set of characters in the string.
  1319. Uses a case-sensitive comparison.
  1320. @returns true if the string contains any of the characters from
  1321. the string that is passed in.
  1322. */
  1323. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1324. /** Looks for a set of characters in the string.
  1325. Uses a case-sensitive comparison.
  1326. @returns true if the all the characters in the string are also found in the
  1327. string that is passed in.
  1328. */
  1329. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1330. /** Returns true if the string matches this simple wildcard expression.
  1331. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1332. This isn't a full-blown regex though! The only wildcard characters supported
  1333. are "*" and "?". It's mainly intended for filename pattern matching.
  1334. */
  1335. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1336. // Substring location methods..
  1337. /** Searches for a character inside this string.
  1338. Uses a case-sensitive comparison.
  1339. @returns the index of the first occurrence of the character in this
  1340. string, or -1 if it's not found.
  1341. */
  1342. int indexOfChar (const tchar characterToLookFor) const throw();
  1343. /** Searches for a character inside this string.
  1344. Uses a case-sensitive comparison.
  1345. @param startIndex the index from which the search should proceed
  1346. @param characterToLookFor the character to look for
  1347. @returns the index of the first occurrence of the character in this
  1348. string, or -1 if it's not found.
  1349. */
  1350. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1351. /** Returns the index of the first character that matches one of the characters
  1352. passed-in to this method.
  1353. This scans the string, beginning from the startIndex supplied, and if it finds
  1354. a character that appears in the string charactersToLookFor, it returns its index.
  1355. If none of these characters are found, it returns -1.
  1356. If ignoreCase is true, the comparison will be case-insensitive.
  1357. @see indexOfChar, lastIndexOfAnyOf
  1358. */
  1359. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1360. const int startIndex = 0,
  1361. const bool ignoreCase = false) const throw();
  1362. /** Searches for a substring within this string.
  1363. Uses a case-sensitive comparison.
  1364. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1365. */
  1366. int indexOf (const tchar* const text) const throw();
  1367. /** Searches for a substring within this string.
  1368. Uses a case-sensitive comparison.
  1369. @param startIndex the index from which the search should proceed
  1370. @param textToLookFor the string to search for
  1371. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1372. */
  1373. int indexOf (const int startIndex,
  1374. const tchar* const textToLookFor) const throw();
  1375. /** Searches for a substring within this string.
  1376. Uses a case-insensitive comparison.
  1377. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1378. */
  1379. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1380. /** Searches for a substring within this string.
  1381. Uses a case-insensitive comparison.
  1382. @param startIndex the index from which the search should proceed
  1383. @param textToLookFor the string to search for
  1384. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1385. */
  1386. int indexOfIgnoreCase (const int startIndex,
  1387. const tchar* const textToLookFor) const throw();
  1388. /** Searches for a character inside this string (working backwards from the end of the string).
  1389. Uses a case-sensitive comparison.
  1390. @returns the index of the last occurrence of the character in this
  1391. string, or -1 if it's not found.
  1392. */
  1393. int lastIndexOfChar (const tchar character) const throw();
  1394. /** Searches for a substring inside this string (working backwards from the end of the string).
  1395. Uses a case-sensitive comparison.
  1396. @returns the index of the start of the last occurrence of the
  1397. substring within this string, or -1 if it's not found.
  1398. */
  1399. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1400. /** Searches for a substring inside this string (working backwards from the end of the string).
  1401. Uses a case-insensitive comparison.
  1402. @returns the index of the start of the last occurrence of the
  1403. substring within this string, or -1 if it's not found.
  1404. */
  1405. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1406. /** Returns the index of the last character in this string that matches one of the
  1407. characters passed-in to this method.
  1408. This scans the string backwards, starting from its end, and if it finds
  1409. a character that appears in the string charactersToLookFor, it returns its index.
  1410. If none of these characters are found, it returns -1.
  1411. If ignoreCase is true, the comparison will be case-insensitive.
  1412. @see lastIndexOf, indexOfAnyOf
  1413. */
  1414. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1415. const bool ignoreCase = false) const throw();
  1416. // Substring extraction and manipulation methods..
  1417. /** Returns the character at this index in the string.
  1418. No checks are made to see if the index is within a valid range, so be careful!
  1419. */
  1420. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1421. /** Returns a character from the string such that it can also be altered.
  1422. This can be used as a way of easily changing characters in the string.
  1423. Note that the index passed-in is not checked to see whether it's in-range, so
  1424. be careful when using this.
  1425. */
  1426. tchar& operator[] (const int index) throw();
  1427. /** Returns the final character of the string.
  1428. If the string is empty this will return 0.
  1429. */
  1430. tchar getLastCharacter() const throw();
  1431. /** Returns a subsection of the string.
  1432. If the range specified is beyond the limits of the string, as much as
  1433. possible is returned.
  1434. @param startIndex the index of the start of the substring needed
  1435. @param endIndex all characters from startIndex up to (but not including)
  1436. this index are returned
  1437. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1438. */
  1439. const String substring (int startIndex,
  1440. int endIndex) const throw();
  1441. /** Returns a section of the string, starting from a given position.
  1442. @param startIndex the first character to include. If this is beyond the end
  1443. of the string, an empty string is returned. If it is zero or
  1444. less, the whole string is returned.
  1445. @returns the substring from startIndex up to the end of the string
  1446. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1447. */
  1448. const String substring (const int startIndex) const throw();
  1449. /** Returns a version of this string with a number of characters removed
  1450. from the end.
  1451. @param numberToDrop the number of characters to drop from the end of the
  1452. string. If this is greater than the length of the string,
  1453. an empty string will be returned. If zero or less, the
  1454. original string will be returned.
  1455. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1456. */
  1457. const String dropLastCharacters (const int numberToDrop) const throw();
  1458. /** Returns a section of the string starting from a given substring.
  1459. This will search for the first occurrence of the given substring, and
  1460. return the section of the string starting from the point where this is
  1461. found (optionally not including the substring itself).
  1462. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1463. fromFirstOccurrenceOf ("34", false) would return "56".
  1464. If the substring isn't found, the method will return an empty string.
  1465. If ignoreCase is true, the comparison will be case-insensitive.
  1466. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1467. */
  1468. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1469. const bool includeSubStringInResult,
  1470. const bool ignoreCase) const throw();
  1471. /** Returns a section of the string starting from the last occurrence of a given substring.
  1472. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1473. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1474. return the whole of the original string.
  1475. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1476. */
  1477. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1478. const bool includeSubStringInResult,
  1479. const bool ignoreCase) const throw();
  1480. /** Returns the start of this string, up to the first occurrence of a substring.
  1481. This will search for the first occurrence of a given substring, and then
  1482. return a copy of the string, up to the position of this substring,
  1483. optionally including or excluding the substring itself in the result.
  1484. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1485. upTo ("34", true) would return "1234".
  1486. If the substring isn't found, this will return the whole of the original string.
  1487. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1488. */
  1489. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1490. const bool includeSubStringInResult,
  1491. const bool ignoreCase) const throw();
  1492. /** Returns the start of this string, up to the last occurrence of a substring.
  1493. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1494. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1495. */
  1496. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1497. const bool includeSubStringInResult,
  1498. const bool ignoreCase) const throw();
  1499. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1500. const String trim() const throw();
  1501. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1502. const String trimStart() const throw();
  1503. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1504. const String trimEnd() const throw();
  1505. /** Returns an upper-case version of this string. */
  1506. const String toUpperCase() const throw();
  1507. /** Returns an lower-case version of this string. */
  1508. const String toLowerCase() const throw();
  1509. /** Replaces a sub-section of the string with another string.
  1510. This will return a copy of this string, with a set of characters
  1511. from startIndex to startIndex + numCharsToReplace removed, and with
  1512. a new string inserted in their place.
  1513. Note that this is a const method, and won't alter the string itself.
  1514. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1515. it will be constrained to a valid range.
  1516. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1517. characters will be taken out.
  1518. @param stringToInsert the new string to insert at startIndex after the characters have been
  1519. removed.
  1520. */
  1521. const String replaceSection (int startIndex,
  1522. int numCharactersToReplace,
  1523. const tchar* const stringToInsert) const throw();
  1524. /** Replaces all occurrences of a substring with another string.
  1525. Returns a copy of this string, with any occurrences of stringToReplace
  1526. swapped for stringToInsertInstead.
  1527. Note that this is a const method, and won't alter the string itself.
  1528. */
  1529. const String replace (const tchar* const stringToReplace,
  1530. const tchar* const stringToInsertInstead,
  1531. const bool ignoreCase = false) const throw();
  1532. /** Returns a string with all occurrences of a character replaced with a different one. */
  1533. const String replaceCharacter (const tchar characterToReplace,
  1534. const tchar characterToInsertInstead) const throw();
  1535. /** Replaces a set of characters with another set.
  1536. Returns a string in which each character from charactersToReplace has been replaced
  1537. by the character at the equivalent position in newCharacters (so the two strings
  1538. passed in must be the same length).
  1539. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1540. Note that this is a const method, and won't affect the string itself.
  1541. */
  1542. const String replaceCharacters (const String& charactersToReplace,
  1543. const tchar* const charactersToInsertInstead) const throw();
  1544. /** Returns a version of this string that only retains a fixed set of characters.
  1545. This will return a copy of this string, omitting any characters which are not
  1546. found in the string passed-in.
  1547. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1548. Note that this is a const method, and won't alter the string itself.
  1549. */
  1550. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1551. /** Returns a version of this string with a set of characters removed.
  1552. This will return a copy of this string, omitting any characters which are
  1553. found in the string passed-in.
  1554. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1555. Note that this is a const method, and won't alter the string itself.
  1556. */
  1557. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1558. /** Returns a section from the start of the string that only contains a certain set of characters.
  1559. This returns the leftmost section of the string, up to (and not including) the
  1560. first character that doesn't appear in the string passed in.
  1561. */
  1562. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1563. /** Returns a section from the start of the string that only contains a certain set of characters.
  1564. This returns the leftmost section of the string, up to (and not including) the
  1565. first character that occurs in the string passed in.
  1566. */
  1567. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1568. /** Checks whether the string might be in quotation marks.
  1569. @returns true if the string begins with a quote character (either a double or single quote).
  1570. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1571. @see unquoted, quoted
  1572. */
  1573. bool isQuotedString() const throw();
  1574. /** Removes quotation marks from around the string, (if there are any).
  1575. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1576. at the ends of the string are not affected. If there aren't any quotes, the original string
  1577. is returned.
  1578. Note that this is a const method, and won't alter the string itself.
  1579. @see isQuotedString, quoted
  1580. */
  1581. const String unquoted() const throw();
  1582. /** Adds quotation marks around a string.
  1583. This will return a copy of the string with a quote at the start and end, (but won't
  1584. add the quote if there's already one there, so it's safe to call this on strings that
  1585. may already have quotes around them).
  1586. Note that this is a const method, and won't alter the string itself.
  1587. @param quoteCharacter the character to add at the start and end
  1588. @see isQuotedString, unquoted
  1589. */
  1590. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1591. /** Writes text into this string, using printf style-arguments.
  1592. This will replace the contents of the string with the output of this
  1593. formatted printf.
  1594. Note that using the %s token with a juce string is probably a bad idea, as
  1595. this may expect differect encodings on different platforms.
  1596. @see formatted
  1597. */
  1598. void printf (const tchar* const format, ...) throw();
  1599. /** Returns a string, created using arguments in the style of printf.
  1600. This will return a string which is the result of a sprintf using the
  1601. arguments passed-in.
  1602. Note that using the %s token with a juce string is probably a bad idea, as
  1603. this may expect differect encodings on different platforms.
  1604. @see printf, vprintf
  1605. */
  1606. static const String formatted (const tchar* const format, ...) throw();
  1607. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1608. This will replace the contents of the string with the output of this
  1609. formatted printf. Used by other methods, this is public in case it's
  1610. useful for other purposes where you want to pass a va_list through directly.
  1611. Note that using the %s token with a juce string is probably a bad idea, as
  1612. this may expect differect encodings on different platforms.
  1613. @see printf, formatted
  1614. */
  1615. void vprintf (const tchar* const format, va_list& args) throw();
  1616. /** Creates a string which is a version of a string repeated and joined together.
  1617. @param stringToRepeat the string to repeat
  1618. @param numberOfTimesToRepeat how many times to repeat it
  1619. */
  1620. static const String repeatedString (const tchar* const stringToRepeat,
  1621. int numberOfTimesToRepeat) throw();
  1622. /** Creates a string from data in an unknown format.
  1623. This looks at some binary data and tries to guess whether it's Unicode
  1624. or 8-bit characters, then returns a string that represents it correctly.
  1625. Should be able to handle Unicode endianness correctly, by looking at
  1626. the first two bytes.
  1627. */
  1628. static const String createStringFromData (const void* const data,
  1629. const int size) throw();
  1630. // Numeric conversions..
  1631. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1632. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1633. */
  1634. explicit String (const int decimalInteger) throw();
  1635. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1636. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1637. */
  1638. explicit String (const unsigned int decimalInteger) throw();
  1639. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1640. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1641. */
  1642. explicit String (const short decimalInteger) throw();
  1643. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1644. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1645. */
  1646. explicit String (const unsigned short decimalInteger) throw();
  1647. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1648. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1649. */
  1650. explicit String (const int64 largeIntegerValue) throw();
  1651. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1652. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1653. */
  1654. explicit String (const uint64 largeIntegerValue) throw();
  1655. /** Creates a string representing this floating-point number.
  1656. @param floatValue the value to convert to a string
  1657. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1658. decimal places, and will not use exponent notation. If 0 or
  1659. less, it will use exponent notation if necessary.
  1660. @see getDoubleValue, getIntValue
  1661. */
  1662. explicit String (const float floatValue,
  1663. const int numberOfDecimalPlaces = 0) throw();
  1664. /** Creates a string representing this floating-point number.
  1665. @param doubleValue the value to convert to a string
  1666. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1667. decimal places, and will not use exponent notation. If 0 or
  1668. less, it will use exponent notation if necessary.
  1669. @see getFloatValue, getIntValue
  1670. */
  1671. explicit String (const double doubleValue,
  1672. const int numberOfDecimalPlaces = 0) throw();
  1673. /** Parses this string to find its numerical value (up to 32 bits in size).
  1674. @returns the value of the string as a 32 bit signed base-10 integer.
  1675. @see getTrailingIntValue, getHexValue32, getHexValue64
  1676. */
  1677. int getIntValue() const throw();
  1678. /** Parses this string to find its numerical value (up to 64 bits in size).
  1679. @returns the value of the string as a 64 bit signed base-10 integer.
  1680. */
  1681. int64 getLargeIntValue() const throw();
  1682. /** Parses a decimal number from the end of the string.
  1683. This will look for a value at the end of the string.
  1684. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1685. Negative numbers are not handled, so "xyz-5" returns 5.
  1686. @see getIntValue
  1687. */
  1688. int getTrailingIntValue() const throw();
  1689. /** Parses this string as a floating point number.
  1690. @returns the value of the string as a 32-bit floating point value.
  1691. @see getDoubleValue
  1692. */
  1693. float getFloatValue() const throw();
  1694. /** Parses this string as a floating point number.
  1695. @returns the value of the string as a 64-bit floating point value.
  1696. @see getFloatValue
  1697. */
  1698. double getDoubleValue() const throw();
  1699. /** Parses the string as a hexadecimal number.
  1700. Non-hexadecimal characters in the string are ignored.
  1701. If the string contains too many characters, then the lowest significant
  1702. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1703. @returns a 32-bit number which is the value of the string in hex.
  1704. */
  1705. int getHexValue32() const throw();
  1706. /** Parses the string as a hexadecimal number.
  1707. Non-hexadecimal characters in the string are ignored.
  1708. If the string contains too many characters, then the lowest significant
  1709. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1710. @returns a 64-bit number which is the value of the string in hex.
  1711. */
  1712. int64 getHexValue64() const throw();
  1713. /** Creates a string representing this 32-bit value in hexadecimal. */
  1714. static const String toHexString (const int number) throw();
  1715. /** Creates a string representing this 64-bit value in hexadecimal. */
  1716. static const String toHexString (const int64 number) throw();
  1717. /** Creates a string representing this 16-bit value in hexadecimal. */
  1718. static const String toHexString (const short number) throw();
  1719. /** Creates a string containing a hex dump of a block of binary data.
  1720. @param data the binary data to use as input
  1721. @param size how many bytes of data to use
  1722. @param groupSize how many bytes are grouped together before inserting a
  1723. space into the output. e.g. group size 0 has no spaces,
  1724. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1725. like "bea1 c2ff".
  1726. */
  1727. static const String toHexString (const unsigned char* data,
  1728. const int size,
  1729. const int groupSize = 1) throw();
  1730. // Casting to character arrays..
  1731. #if JUCE_STRINGS_ARE_UNICODE
  1732. /** Returns a version of this string using the default 8-bit system encoding.
  1733. Because it returns a reference to the string's internal data, the pointer
  1734. that is returned must not be stored anywhere, as it can be deleted whenever the
  1735. string changes.
  1736. */
  1737. operator const char*() const throw();
  1738. /** Returns a unicode version of this string.
  1739. Because it returns a reference to the string's internal data, the pointer
  1740. that is returned must not be stored anywhere, as it can be deleted whenever the
  1741. string changes.
  1742. */
  1743. inline operator const juce_wchar*() const throw() { return text->text; }
  1744. #else
  1745. /** Returns a version of this string using the default 8-bit system encoding.
  1746. Because it returns a reference to the string's internal data, the pointer
  1747. that is returned must not be stored anywhere, as it can be deleted whenever the
  1748. string changes.
  1749. */
  1750. inline operator const char*() const throw() { return text->text; }
  1751. /** Returns a unicode version of this string.
  1752. Because it returns a reference to the string's internal data, the pointer
  1753. that is returned must not be stored anywhere, as it can be deleted whenever the
  1754. string changes.
  1755. */
  1756. operator const juce_wchar*() const throw();
  1757. #endif
  1758. /** Copies the string to a buffer.
  1759. @param destBuffer the place to copy it to
  1760. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1761. not including the tailing zero, so this shouldn't be
  1762. larger than the size of your destination buffer - 1
  1763. */
  1764. void copyToBuffer (char* const destBuffer,
  1765. const int maxCharsToCopy) const throw();
  1766. /** Copies the string to a unicode buffer.
  1767. @param destBuffer the place to copy it to
  1768. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1769. not including the tailing zero, so this shouldn't be
  1770. larger than the size of your destination buffer - 1
  1771. */
  1772. void copyToBuffer (juce_wchar* const destBuffer,
  1773. const int maxCharsToCopy) const throw();
  1774. /** Copies the string to a buffer as UTF-8 characters.
  1775. Returns the number of bytes copied to the buffer, including the terminating null
  1776. character.
  1777. @param destBuffer the place to copy it to; if this is a null pointer,
  1778. the method just returns the number of bytes required
  1779. (including the terminating null character).
  1780. */
  1781. int copyToUTF8 (uint8* const destBuffer) const throw();
  1782. /** Returns a pointer to a UTF-8 version of this string.
  1783. Because it returns a reference to the string's internal data, the pointer
  1784. that is returned must not be stored anywhere, as it can be deleted whenever the
  1785. string changes.
  1786. */
  1787. const char* toUTF8() const throw();
  1788. /** Creates a String from a UTF-8 encoded buffer.
  1789. If the size is < 0, it'll keep reading until it hits a zero.
  1790. */
  1791. static const String fromUTF8 (const uint8* const utf8buffer,
  1792. int bufferSizeBytes = -1) throw();
  1793. /** Increases the string's internally allocated storage.
  1794. Although the string's contents won't be affected by this call, it will
  1795. increase the amount of memory allocated internally for the string to grow into.
  1796. If you're about to make a large number of calls to methods such
  1797. as += or <<, it's more efficient to preallocate enough extra space
  1798. beforehand, so that these methods won't have to keep resizing the string
  1799. to append the extra characters.
  1800. @param numCharsNeeded the number of characters to allocate storage for. If this
  1801. value is less than the currently allocated size, it will
  1802. have no effect.
  1803. */
  1804. void preallocateStorage (const int numCharsNeeded) throw();
  1805. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1806. private:
  1807. struct InternalRefCountedStringHolder
  1808. {
  1809. int refCount;
  1810. int allocatedNumChars;
  1811. #if JUCE_STRINGS_ARE_UNICODE
  1812. wchar_t text[1];
  1813. #else
  1814. char text[1];
  1815. #endif
  1816. };
  1817. InternalRefCountedStringHolder* text;
  1818. static InternalRefCountedStringHolder emptyString;
  1819. // internal constructor that preallocates a certain amount of memory
  1820. String (const int numChars, const int dummyVariable) throw();
  1821. void deleteInternal() throw();
  1822. void createInternal (const int numChars) throw();
  1823. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1824. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1825. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1826. void dupeInternalIfMultiplyReferenced() throw();
  1827. };
  1828. /** Global operator to allow a String to be appended to a string literal.
  1829. This allows the use of expressions such as "abc" + String (x)
  1830. @see String
  1831. */
  1832. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1833. const String& string2) throw();
  1834. /** Global operator to allow a String to be appended to a string literal.
  1835. This allows the use of expressions such as "abc" + String (x)
  1836. @see String
  1837. */
  1838. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1839. const String& string2) throw();
  1840. #endif // __JUCE_STRING_JUCEHEADER__
  1841. /********* End of inlined file: juce_String.h *********/
  1842. /**
  1843. Acts as an application-wide logging class.
  1844. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1845. method and this will then be used by all calls to writeToLog.
  1846. The logger class also contains methods for writing messages to the debugger's
  1847. output stream.
  1848. @see FileLogger
  1849. */
  1850. class JUCE_API Logger
  1851. {
  1852. public:
  1853. /** Destructor. */
  1854. virtual ~Logger();
  1855. /** Sets the current logging class to use.
  1856. Note that the object passed in won't be deleted when no longer needed.
  1857. A null pointer can be passed-in to disable any logging.
  1858. If deleteOldLogger is set to true, the existing logger will be
  1859. deleted (if there is one).
  1860. */
  1861. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1862. const bool deleteOldLogger = false);
  1863. /** Writes a string to the current logger.
  1864. This will pass the string to the logger's logMessage() method if a logger
  1865. has been set.
  1866. @see logMessage
  1867. */
  1868. static void JUCE_CALLTYPE writeToLog (const String& message);
  1869. /** Writes a message to the standard error stream.
  1870. This can be called directly, or by using the DBG() macro in
  1871. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1872. */
  1873. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1874. /** Writes a message to the standard error stream.
  1875. This can be called directly, or by using the DBG_PRINTF() macro in
  1876. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1877. */
  1878. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1879. protected:
  1880. Logger();
  1881. /** This is overloaded by subclasses to implement custom logging behaviour.
  1882. @see setCurrentLogger
  1883. */
  1884. virtual void logMessage (const String& message) = 0;
  1885. };
  1886. #endif // __JUCE_LOGGER_JUCEHEADER__
  1887. /********* End of inlined file: juce_Logger.h *********/
  1888. END_JUCE_NAMESPACE
  1889. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1890. /********* End of inlined file: juce_StandardHeader.h *********/
  1891. BEGIN_JUCE_NAMESPACE
  1892. #if JUCE_MSVC
  1893. // this is set explicitly in case the app is using a different packing size.
  1894. #pragma pack (push, 8)
  1895. #pragma warning (push)
  1896. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1897. #endif
  1898. #if JUCE_MAC
  1899. #pragma align=natural
  1900. #endif
  1901. #define JUCE_PUBLIC_INCLUDES
  1902. // this is where all the class header files get brought in..
  1903. /********* Start of inlined file: juce_core_includes.h *********/
  1904. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1905. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1906. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1907. /********* Start of inlined file: juce_Atomic.h *********/
  1908. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1909. #define __JUCE_ATOMIC_JUCEHEADER__
  1910. // Atomic increment/decrement operations..
  1911. #if JUCE_MAC && ! DOXYGEN
  1912. #if ! MACOS_10_3_OR_EARLIER
  1913. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1914. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1915. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1916. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1917. #else
  1918. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  1919. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  1920. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1921. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1922. #endif
  1923. #elif JUCE_GCC
  1924. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1925. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1926. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1927. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1928. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1929. #else
  1930. /** Increments an integer in a thread-safe way. */
  1931. forcedinline void atomicIncrement (int& variable) throw()
  1932. {
  1933. __asm__ __volatile__ (
  1934. #if JUCE_64BIT
  1935. "lock incl (%%rax)"
  1936. :
  1937. : "a" (&variable)
  1938. : "cc", "memory");
  1939. #else
  1940. "lock incl %0"
  1941. : "=m" (variable)
  1942. : "m" (variable));
  1943. #endif
  1944. }
  1945. /** Increments an integer in a thread-safe way and returns the incremented value. */
  1946. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  1947. {
  1948. int result;
  1949. __asm__ __volatile__ (
  1950. #if JUCE_64BIT
  1951. "lock xaddl %%ebx, (%%rax) \n\
  1952. incl %%ebx"
  1953. : "=b" (result)
  1954. : "a" (&variable), "b" (1)
  1955. : "cc", "memory");
  1956. #else
  1957. "lock xaddl %%eax, (%%ecx) \n\
  1958. incl %%eax"
  1959. : "=a" (result)
  1960. : "c" (&variable), "a" (1)
  1961. : "memory");
  1962. #endif
  1963. return result;
  1964. }
  1965. /** Decrememts an integer in a thread-safe way. */
  1966. forcedinline void atomicDecrement (int& variable) throw()
  1967. {
  1968. __asm__ __volatile__ (
  1969. #if JUCE_64BIT
  1970. "lock decl (%%rax)"
  1971. :
  1972. : "a" (&variable)
  1973. : "cc", "memory");
  1974. #else
  1975. "lock decl %0"
  1976. : "=m" (variable)
  1977. : "m" (variable));
  1978. #endif
  1979. }
  1980. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  1981. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  1982. {
  1983. int result;
  1984. __asm__ __volatile__ (
  1985. #if JUCE_64BIT
  1986. "lock xaddl %%ebx, (%%rax) \n\
  1987. decl %%ebx"
  1988. : "=b" (result)
  1989. : "a" (&variable), "b" (-1)
  1990. : "cc", "memory");
  1991. #else
  1992. "lock xaddl %%eax, (%%ecx) \n\
  1993. decl %%eax"
  1994. : "=a" (result)
  1995. : "c" (&variable), "a" (-1)
  1996. : "memory");
  1997. #endif
  1998. return result;
  1999. }
  2000. #endif
  2001. #elif JUCE_USE_INTRINSICS
  2002. #pragma intrinsic (_InterlockedIncrement)
  2003. #pragma intrinsic (_InterlockedDecrement)
  2004. /** Increments an integer in a thread-safe way. */
  2005. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2006. {
  2007. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2008. }
  2009. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2010. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2011. {
  2012. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2013. }
  2014. /** Decrememts an integer in a thread-safe way. */
  2015. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2016. {
  2017. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2018. }
  2019. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2020. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2021. {
  2022. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2023. }
  2024. #else
  2025. /** Increments an integer in a thread-safe way. */
  2026. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2027. {
  2028. __asm {
  2029. mov ecx, dword ptr [variable]
  2030. lock inc dword ptr [ecx]
  2031. }
  2032. }
  2033. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2034. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2035. {
  2036. int result;
  2037. __asm {
  2038. mov ecx, dword ptr [variable]
  2039. mov eax, 1
  2040. lock xadd dword ptr [ecx], eax
  2041. inc eax
  2042. mov result, eax
  2043. }
  2044. return result;
  2045. }
  2046. /** Decrememts an integer in a thread-safe way. */
  2047. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2048. {
  2049. __asm {
  2050. mov ecx, dword ptr [variable]
  2051. lock dec dword ptr [ecx]
  2052. }
  2053. }
  2054. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2055. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2056. {
  2057. int result;
  2058. __asm {
  2059. mov ecx, dword ptr [variable]
  2060. mov eax, -1
  2061. lock xadd dword ptr [ecx], eax
  2062. dec eax
  2063. mov result, eax
  2064. }
  2065. return result;
  2066. }
  2067. #endif
  2068. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2069. /********* End of inlined file: juce_Atomic.h *********/
  2070. #endif
  2071. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2072. #endif
  2073. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2074. /********* Start of inlined file: juce_FileLogger.h *********/
  2075. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2076. #define __JUCE_FILELOGGER_JUCEHEADER__
  2077. /********* Start of inlined file: juce_File.h *********/
  2078. #ifndef __JUCE_FILE_JUCEHEADER__
  2079. #define __JUCE_FILE_JUCEHEADER__
  2080. /********* Start of inlined file: juce_OwnedArray.h *********/
  2081. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2082. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2083. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2084. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2085. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2086. /** The default size of chunk in which arrays increase their storage.
  2087. Used by ArrayAllocationBase and its subclasses.
  2088. */
  2089. const int juceDefaultArrayGranularity = 8;
  2090. /**
  2091. Implements some basic array storage allocation functions.
  2092. This class isn't really for public use - it's used by the other
  2093. array classes, but might come in handy for some purposes.
  2094. @see Array, OwnedArray, ReferenceCountedArray
  2095. */
  2096. template <class ElementType>
  2097. class ArrayAllocationBase
  2098. {
  2099. protected:
  2100. /** Creates an empty array.
  2101. @param granularity_ this is the size of increment by which the internal storage
  2102. will be increased.
  2103. */
  2104. ArrayAllocationBase (const int granularity_) throw()
  2105. : elements (0),
  2106. numAllocated (0),
  2107. granularity (granularity_)
  2108. {
  2109. }
  2110. /** Destructor. */
  2111. ~ArrayAllocationBase() throw()
  2112. {
  2113. delete[] elements;
  2114. }
  2115. /** Changes the amount of storage allocated.
  2116. This will retain any data currently held in the array, and either add or
  2117. remove extra space at the end.
  2118. @param numElements the number of elements that are needed
  2119. */
  2120. void setAllocatedSize (const int numElements) throw()
  2121. {
  2122. if (numAllocated != numElements)
  2123. {
  2124. if (numElements > 0)
  2125. {
  2126. ElementType* const newElements = new ElementType [numElements];
  2127. const int itemsToRetain = jmin (numElements, numAllocated);
  2128. for (int i = 0; i < itemsToRetain; ++i)
  2129. newElements[i] = elements[i];
  2130. delete[] elements;
  2131. elements = newElements;
  2132. }
  2133. else if (elements != 0)
  2134. {
  2135. delete[] elements;
  2136. elements = 0;
  2137. }
  2138. numAllocated = numElements;
  2139. }
  2140. }
  2141. /** Increases the amount of storage allocated if it is less than a given amount.
  2142. This will retain any data currently held in the array, but will add
  2143. extra space at the end to make sure there it's at least as big as the size
  2144. passed in. If it's already bigger, no action is taken.
  2145. @param minNumElements the minimum number of elements that are needed
  2146. */
  2147. void ensureAllocatedSize (int minNumElements) throw()
  2148. {
  2149. if (minNumElements > numAllocated)
  2150. {
  2151. // for arrays with small granularity that get big, start
  2152. // increasing the size in bigger jumps
  2153. if (minNumElements > (granularity << 6))
  2154. {
  2155. minNumElements += (minNumElements / granularity);
  2156. if (minNumElements > (granularity << 8))
  2157. minNumElements += granularity << 6;
  2158. else
  2159. minNumElements += granularity << 5;
  2160. }
  2161. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2162. }
  2163. }
  2164. ElementType* elements;
  2165. int numAllocated, granularity;
  2166. private:
  2167. ArrayAllocationBase (const ArrayAllocationBase&);
  2168. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2169. };
  2170. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2171. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2172. /********* Start of inlined file: juce_ElementComparator.h *********/
  2173. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2174. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2175. /**
  2176. Sorts a range of elements in an array.
  2177. The comparator object that is passed-in must define a public method with the following
  2178. signature:
  2179. @code
  2180. int compareElements (ElementType first, ElementType second);
  2181. @endcode
  2182. ..and this method must return:
  2183. - a value of < 0 if the first comes before the second
  2184. - a value of 0 if the two objects are equivalent
  2185. - a value of > 0 if the second comes before the first
  2186. To improve performance, the compareElements() method can be declared as static or const.
  2187. @param comparator an object which defines a compareElements() method
  2188. @param array the array to sort
  2189. @param firstElement the index of the first element of the range to be sorted
  2190. @param lastElement the index of the last element in the range that needs
  2191. sorting (this is inclusive)
  2192. @param retainOrderOfEquivalentItems if true, the order of items that the
  2193. comparator deems the same will be maintained - this will be
  2194. a slower algorithm than if they are allowed to be moved around.
  2195. @see sortArrayRetainingOrder
  2196. */
  2197. template <class ElementType, class ElementComparator>
  2198. static void sortArray (ElementComparator& comparator,
  2199. ElementType* const array,
  2200. int firstElement,
  2201. int lastElement,
  2202. const bool retainOrderOfEquivalentItems)
  2203. {
  2204. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2205. // avoids getting warning messages about the parameter being unused
  2206. if (lastElement > firstElement)
  2207. {
  2208. if (retainOrderOfEquivalentItems)
  2209. {
  2210. for (int i = firstElement; i < lastElement; ++i)
  2211. {
  2212. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2213. {
  2214. const ElementType temp = array [i];
  2215. array [i] = array[i + 1];
  2216. array [i + 1] = temp;
  2217. if (i > firstElement)
  2218. i -= 2;
  2219. }
  2220. }
  2221. }
  2222. else
  2223. {
  2224. int fromStack[30], toStack[30];
  2225. int stackIndex = 0;
  2226. for (;;)
  2227. {
  2228. const int size = (lastElement - firstElement) + 1;
  2229. if (size <= 8)
  2230. {
  2231. int j = lastElement;
  2232. int maxIndex;
  2233. while (j > firstElement)
  2234. {
  2235. maxIndex = firstElement;
  2236. for (int k = firstElement + 1; k <= j; ++k)
  2237. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2238. maxIndex = k;
  2239. const ElementType temp = array [maxIndex];
  2240. array [maxIndex] = array[j];
  2241. array [j] = temp;
  2242. --j;
  2243. }
  2244. }
  2245. else
  2246. {
  2247. const int mid = firstElement + (size >> 1);
  2248. ElementType temp = array [mid];
  2249. array [mid] = array [firstElement];
  2250. array [firstElement] = temp;
  2251. int i = firstElement;
  2252. int j = lastElement + 1;
  2253. for (;;)
  2254. {
  2255. while (++i <= lastElement
  2256. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2257. {}
  2258. while (--j > firstElement
  2259. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2260. {}
  2261. if (j < i)
  2262. break;
  2263. temp = array[i];
  2264. array[i] = array[j];
  2265. array[j] = temp;
  2266. }
  2267. temp = array [firstElement];
  2268. array [firstElement] = array[j];
  2269. array [j] = temp;
  2270. if (j - 1 - firstElement >= lastElement - i)
  2271. {
  2272. if (firstElement + 1 < j)
  2273. {
  2274. fromStack [stackIndex] = firstElement;
  2275. toStack [stackIndex] = j - 1;
  2276. ++stackIndex;
  2277. }
  2278. if (i < lastElement)
  2279. {
  2280. firstElement = i;
  2281. continue;
  2282. }
  2283. }
  2284. else
  2285. {
  2286. if (i < lastElement)
  2287. {
  2288. fromStack [stackIndex] = i;
  2289. toStack [stackIndex] = lastElement;
  2290. ++stackIndex;
  2291. }
  2292. if (firstElement + 1 < j)
  2293. {
  2294. lastElement = j - 1;
  2295. continue;
  2296. }
  2297. }
  2298. }
  2299. if (--stackIndex < 0)
  2300. break;
  2301. jassert (stackIndex < numElementsInArray (fromStack));
  2302. firstElement = fromStack [stackIndex];
  2303. lastElement = toStack [stackIndex];
  2304. }
  2305. }
  2306. }
  2307. }
  2308. /**
  2309. Searches a sorted array of elements, looking for the index at which a specified value
  2310. should be inserted for it to be in the correct order.
  2311. The comparator object that is passed-in must define a public method with the following
  2312. signature:
  2313. @code
  2314. int compareElements (ElementType first, ElementType second);
  2315. @endcode
  2316. ..and this method must return:
  2317. - a value of < 0 if the first comes before the second
  2318. - a value of 0 if the two objects are equivalent
  2319. - a value of > 0 if the second comes before the first
  2320. To improve performance, the compareElements() method can be declared as static or const.
  2321. @param comparator an object which defines a compareElements() method
  2322. @param array the array to search
  2323. @param newElement the value that is going to be inserted
  2324. @param firstElement the index of the first element to search
  2325. @param lastElement the index of the last element in the range (this is non-inclusive)
  2326. */
  2327. template <class ElementType, class ElementComparator>
  2328. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2329. ElementType* const array,
  2330. const ElementType newElement,
  2331. int firstElement,
  2332. int lastElement)
  2333. {
  2334. jassert (firstElement <= lastElement);
  2335. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2336. // avoids getting warning messages about the parameter being unused
  2337. while (firstElement < lastElement)
  2338. {
  2339. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2340. {
  2341. ++firstElement;
  2342. break;
  2343. }
  2344. else
  2345. {
  2346. const int halfway = (firstElement + lastElement) >> 1;
  2347. if (halfway == firstElement)
  2348. {
  2349. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2350. ++firstElement;
  2351. break;
  2352. }
  2353. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2354. {
  2355. firstElement = halfway;
  2356. }
  2357. else
  2358. {
  2359. lastElement = halfway;
  2360. }
  2361. }
  2362. }
  2363. return firstElement;
  2364. }
  2365. /**
  2366. A simple ElementComparator class that can be used to sort an array of
  2367. integer primitive objects.
  2368. Example: @code
  2369. Array <int> myArray;
  2370. IntegerElementComparator<int> sorter;
  2371. myArray.sort (sorter);
  2372. @endcode
  2373. For floating point values, see the FloatElementComparator class instead.
  2374. @see FloatElementComparator, ElementComparator
  2375. */
  2376. template <class ElementType>
  2377. class IntegerElementComparator
  2378. {
  2379. public:
  2380. static int compareElements (const ElementType first,
  2381. const ElementType second) throw()
  2382. {
  2383. return first - second;
  2384. }
  2385. };
  2386. /**
  2387. A simple ElementComparator class that can be used to sort an array of numeric
  2388. double or floating point primitive objects.
  2389. Example: @code
  2390. Array <double> myArray;
  2391. FloatElementComparator<double> sorter;
  2392. myArray.sort (sorter);
  2393. @endcode
  2394. For integer values, see the IntegerElementComparator class instead.
  2395. @see IntegerElementComparator, ElementComparator
  2396. */
  2397. template <class ElementType>
  2398. class FloatElementComparator
  2399. {
  2400. public:
  2401. static int compareElements (const ElementType first,
  2402. const ElementType second) throw()
  2403. {
  2404. return (first < second) ? -1
  2405. : ((first == second) ? 0
  2406. : 1);
  2407. }
  2408. };
  2409. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2410. /********* End of inlined file: juce_ElementComparator.h *********/
  2411. /********* Start of inlined file: juce_CriticalSection.h *********/
  2412. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2413. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2414. /**
  2415. Prevents multiple threads from accessing shared objects at the same time.
  2416. @see ScopedLock, Thread, InterProcessLock
  2417. */
  2418. class JUCE_API CriticalSection
  2419. {
  2420. public:
  2421. /**
  2422. Creates a CriticalSection object
  2423. */
  2424. CriticalSection() throw();
  2425. /** Destroys a CriticalSection object.
  2426. If the critical section is deleted whilst locked, its subsequent behaviour
  2427. is unpredictable.
  2428. */
  2429. ~CriticalSection() throw();
  2430. /** Locks this critical section.
  2431. If the lock is currently held by another thread, this will wait until it
  2432. becomes free.
  2433. If the lock is already held by the caller thread, the method returns immediately.
  2434. @see exit, ScopedLock
  2435. */
  2436. void enter() const throw();
  2437. /** Attempts to lock this critical section without blocking.
  2438. This method behaves identically to CriticalSection::enter, except that the caller thread
  2439. does not wait if the lock is currently held by another thread but returns false immediately.
  2440. @returns false if the lock is currently held by another thread, true otherwise.
  2441. @see enter
  2442. */
  2443. bool tryEnter() const throw();
  2444. /** Releases the lock.
  2445. If the caller thread hasn't got the lock, this can have unpredictable results.
  2446. If the enter() method has been called multiple times by the thread, each
  2447. call must be matched by a call to exit() before other threads will be allowed
  2448. to take over the lock.
  2449. @see enter, ScopedLock
  2450. */
  2451. void exit() const throw();
  2452. juce_UseDebuggingNewOperator
  2453. private:
  2454. #if JUCE_WIN32
  2455. #if JUCE_64BIT
  2456. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2457. // block of memory here that's big enough to be used internally as a windows critical
  2458. // section object.
  2459. uint8 internal [44];
  2460. #else
  2461. uint8 internal [24];
  2462. #endif
  2463. #else
  2464. mutable pthread_mutex_t internal;
  2465. #endif
  2466. CriticalSection (const CriticalSection&);
  2467. const CriticalSection& operator= (const CriticalSection&);
  2468. };
  2469. /**
  2470. A class that can be used in place of a real CriticalSection object.
  2471. This is currently used by some templated array classes, and should get
  2472. optimised out by the compiler.
  2473. @see Array, OwnedArray, ReferenceCountedArray
  2474. */
  2475. class JUCE_API DummyCriticalSection
  2476. {
  2477. public:
  2478. forcedinline DummyCriticalSection() throw() {}
  2479. forcedinline ~DummyCriticalSection() throw() {}
  2480. forcedinline void enter() const throw() {}
  2481. forcedinline void exit() const throw() {}
  2482. };
  2483. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2484. /********* End of inlined file: juce_CriticalSection.h *********/
  2485. /** An array designed for holding objects.
  2486. This holds a list of pointers to objects, and will automatically
  2487. delete the objects when they are removed from the array, or when the
  2488. array is itself deleted.
  2489. Declare it in the form: OwnedArray<MyObjectClass>
  2490. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2491. After adding objects, they are 'owned' by the array and will be deleted when
  2492. removed or replaced.
  2493. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2494. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2495. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2496. */
  2497. template <class ObjectClass,
  2498. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2499. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2500. {
  2501. public:
  2502. /** Creates an empty array.
  2503. @param granularity this is the size of increment by which the internal storage
  2504. used by the array will grow. Only change it from the default if you know the
  2505. array is going to be very big and needs to be able to grow efficiently.
  2506. @see ArrayAllocationBase
  2507. */
  2508. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2509. : ArrayAllocationBase <ObjectClass*> (granularity),
  2510. numUsed (0)
  2511. {
  2512. }
  2513. /** Deletes the array and also deletes any objects inside it.
  2514. To get rid of the array without deleting its objects, use its
  2515. clear (false) method before deleting it.
  2516. */
  2517. ~OwnedArray()
  2518. {
  2519. clear (true);
  2520. }
  2521. /** Clears the array, optionally deleting the objects inside it first. */
  2522. void clear (const bool deleteObjects = true)
  2523. {
  2524. lock.enter();
  2525. if (deleteObjects)
  2526. {
  2527. while (numUsed > 0)
  2528. delete this->elements [--numUsed];
  2529. }
  2530. this->setAllocatedSize (0);
  2531. numUsed = 0;
  2532. lock.exit();
  2533. }
  2534. /** Returns the number of items currently in the array.
  2535. @see operator[]
  2536. */
  2537. inline int size() const throw()
  2538. {
  2539. return numUsed;
  2540. }
  2541. /** Returns a pointer to the object at this index in the array.
  2542. If the index is out-of-range, this will return a null pointer, (and
  2543. it could be null anyway, because it's ok for the array to hold null
  2544. pointers as well as objects).
  2545. @see getUnchecked
  2546. */
  2547. inline ObjectClass* operator[] (const int index) const throw()
  2548. {
  2549. lock.enter();
  2550. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2551. ? this->elements [index]
  2552. : (ObjectClass*) 0;
  2553. lock.exit();
  2554. return result;
  2555. }
  2556. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2557. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2558. it can be used when you're sure the index if always going to be legal.
  2559. */
  2560. inline ObjectClass* getUnchecked (const int index) const throw()
  2561. {
  2562. lock.enter();
  2563. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2564. ObjectClass* const result = this->elements [index];
  2565. lock.exit();
  2566. return result;
  2567. }
  2568. /** Returns a pointer to the first object in the array.
  2569. This will return a null pointer if the array's empty.
  2570. @see getLast
  2571. */
  2572. inline ObjectClass* getFirst() const throw()
  2573. {
  2574. lock.enter();
  2575. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2576. : (ObjectClass*) 0;
  2577. lock.exit();
  2578. return result;
  2579. }
  2580. /** Returns a pointer to the last object in the array.
  2581. This will return a null pointer if the array's empty.
  2582. @see getFirst
  2583. */
  2584. inline ObjectClass* getLast() const throw()
  2585. {
  2586. lock.enter();
  2587. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2588. : (ObjectClass*) 0;
  2589. lock.exit();
  2590. return result;
  2591. }
  2592. /** Finds the index of an object which might be in the array.
  2593. @param objectToLookFor the object to look for
  2594. @returns the index at which the object was found, or -1 if it's not found
  2595. */
  2596. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2597. {
  2598. int result = -1;
  2599. lock.enter();
  2600. ObjectClass* const* e = this->elements;
  2601. for (int i = numUsed; --i >= 0;)
  2602. {
  2603. if (objectToLookFor == *e)
  2604. {
  2605. result = (int) (e - this->elements);
  2606. break;
  2607. }
  2608. ++e;
  2609. }
  2610. lock.exit();
  2611. return result;
  2612. }
  2613. /** Returns true if the array contains a specified object.
  2614. @param objectToLookFor the object to look for
  2615. @returns true if the object is in the array
  2616. */
  2617. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2618. {
  2619. lock.enter();
  2620. ObjectClass* const* e = this->elements;
  2621. int i = numUsed;
  2622. while (i >= 4)
  2623. {
  2624. if (objectToLookFor == *e
  2625. || objectToLookFor == *++e
  2626. || objectToLookFor == *++e
  2627. || objectToLookFor == *++e)
  2628. {
  2629. lock.exit();
  2630. return true;
  2631. }
  2632. i -= 4;
  2633. ++e;
  2634. }
  2635. while (i > 0)
  2636. {
  2637. if (objectToLookFor == *e)
  2638. {
  2639. lock.exit();
  2640. return true;
  2641. }
  2642. --i;
  2643. ++e;
  2644. }
  2645. lock.exit();
  2646. return false;
  2647. }
  2648. /** Appends a new object to the end of the array.
  2649. Note that the this object will be deleted by the OwnedArray when it
  2650. is removed, so be careful not to delete it somewhere else.
  2651. Also be careful not to add the same object to the array more than once,
  2652. as this will obviously cause deletion of dangling pointers.
  2653. @param newObject the new object to add to the array
  2654. @see set, insert, addIfNotAlreadyThere, addSorted
  2655. */
  2656. void add (const ObjectClass* const newObject) throw()
  2657. {
  2658. lock.enter();
  2659. this->ensureAllocatedSize (numUsed + 1);
  2660. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2661. lock.exit();
  2662. }
  2663. /** Inserts a new object into the array at the given index.
  2664. Note that the this object will be deleted by the OwnedArray when it
  2665. is removed, so be careful not to delete it somewhere else.
  2666. If the index is less than 0 or greater than the size of the array, the
  2667. element will be added to the end of the array.
  2668. Otherwise, it will be inserted into the array, moving all the later elements
  2669. along to make room.
  2670. Be careful not to add the same object to the array more than once,
  2671. as this will obviously cause deletion of dangling pointers.
  2672. @param indexToInsertAt the index at which the new element should be inserted
  2673. @param newObject the new object to add to the array
  2674. @see add, addSorted, addIfNotAlreadyThere, set
  2675. */
  2676. void insert (int indexToInsertAt,
  2677. const ObjectClass* const newObject) throw()
  2678. {
  2679. if (indexToInsertAt >= 0)
  2680. {
  2681. lock.enter();
  2682. if (indexToInsertAt > numUsed)
  2683. indexToInsertAt = numUsed;
  2684. this->ensureAllocatedSize (numUsed + 1);
  2685. ObjectClass** const e = this->elements + indexToInsertAt;
  2686. const int numToMove = numUsed - indexToInsertAt;
  2687. if (numToMove > 0)
  2688. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2689. *e = const_cast <ObjectClass*> (newObject);
  2690. ++numUsed;
  2691. lock.exit();
  2692. }
  2693. else
  2694. {
  2695. add (newObject);
  2696. }
  2697. }
  2698. /** Appends a new object at the end of the array as long as the array doesn't
  2699. already contain it.
  2700. If the array already contains a matching object, nothing will be done.
  2701. @param newObject the new object to add to the array
  2702. */
  2703. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2704. {
  2705. lock.enter();
  2706. if (! contains (newObject))
  2707. add (newObject);
  2708. lock.exit();
  2709. }
  2710. /** Replaces an object in the array with a different one.
  2711. If the index is less than zero, this method does nothing.
  2712. If the index is beyond the end of the array, the new object is added to the end of the array.
  2713. Be careful not to add the same object to the array more than once,
  2714. as this will obviously cause deletion of dangling pointers.
  2715. @param indexToChange the index whose value you want to change
  2716. @param newObject the new value to set for this index.
  2717. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2718. @see add, insert, remove
  2719. */
  2720. void set (const int indexToChange,
  2721. const ObjectClass* const newObject,
  2722. const bool deleteOldElement = true)
  2723. {
  2724. if (indexToChange >= 0)
  2725. {
  2726. ObjectClass* toDelete = 0;
  2727. lock.enter();
  2728. if (indexToChange < numUsed)
  2729. {
  2730. if (deleteOldElement)
  2731. toDelete = this->elements [indexToChange];
  2732. if (toDelete == newObject)
  2733. toDelete = 0;
  2734. else
  2735. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2736. }
  2737. else
  2738. {
  2739. this->ensureAllocatedSize (numUsed + 1);
  2740. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2741. }
  2742. lock.exit();
  2743. delete toDelete;
  2744. }
  2745. }
  2746. /** Inserts a new object into the array assuming that the array is sorted.
  2747. This will use a comparator to find the position at which the new object
  2748. should go. If the array isn't sorted, the behaviour of this
  2749. method will be unpredictable.
  2750. @param comparator the comparator to use to compare the elements - see the sort method
  2751. for details about this object's structure
  2752. @param newObject the new object to insert to the array
  2753. @see add, sort, indexOfSorted
  2754. */
  2755. template <class ElementComparator>
  2756. void addSorted (ElementComparator& comparator,
  2757. ObjectClass* const newObject) throw()
  2758. {
  2759. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2760. // avoids getting warning messages about the parameter being unused
  2761. lock.enter();
  2762. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2763. lock.exit();
  2764. }
  2765. /** Finds the index of an object in the array, assuming that the array is sorted.
  2766. This will use a comparator to do a binary-chop to find the index of the given
  2767. element, if it exists. If the array isn't sorted, the behaviour of this
  2768. method will be unpredictable.
  2769. @param comparator the comparator to use to compare the elements - see the sort()
  2770. method for details about the form this object should take
  2771. @param objectToLookFor the object to search for
  2772. @returns the index of the element, or -1 if it's not found
  2773. @see addSorted, sort
  2774. */
  2775. template <class ElementComparator>
  2776. int indexOfSorted (ElementComparator& comparator,
  2777. const ObjectClass* const objectToLookFor) const throw()
  2778. {
  2779. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2780. // avoids getting warning messages about the parameter being unused
  2781. lock.enter();
  2782. int start = 0;
  2783. int end = numUsed;
  2784. for (;;)
  2785. {
  2786. if (start >= end)
  2787. {
  2788. lock.exit();
  2789. return -1;
  2790. }
  2791. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2792. {
  2793. lock.exit();
  2794. return start;
  2795. }
  2796. else
  2797. {
  2798. const int halfway = (start + end) >> 1;
  2799. if (halfway == start)
  2800. {
  2801. lock.exit();
  2802. return -1;
  2803. }
  2804. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2805. start = halfway;
  2806. else
  2807. end = halfway;
  2808. }
  2809. }
  2810. }
  2811. /** Removes an object from the array.
  2812. This will remove the object at a given index (optionally also
  2813. deleting it) and move back all the subsequent objects to close the gap.
  2814. If the index passed in is out-of-range, nothing will happen.
  2815. @param indexToRemove the index of the element to remove
  2816. @param deleteObject whether to delete the object that is removed
  2817. @see removeObject, removeRange
  2818. */
  2819. void remove (const int indexToRemove,
  2820. const bool deleteObject = true)
  2821. {
  2822. lock.enter();
  2823. ObjectClass* toDelete = 0;
  2824. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2825. {
  2826. ObjectClass** const e = this->elements + indexToRemove;
  2827. if (deleteObject)
  2828. toDelete = *e;
  2829. --numUsed;
  2830. const int numToShift = numUsed - indexToRemove;
  2831. if (numToShift > 0)
  2832. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2833. if ((numUsed << 1) < this->numAllocated)
  2834. minimiseStorageOverheads();
  2835. }
  2836. lock.exit();
  2837. delete toDelete;
  2838. }
  2839. /** Removes a specified object from the array.
  2840. If the item isn't found, no action is taken.
  2841. @param objectToRemove the object to try to remove
  2842. @param deleteObject whether to delete the object (if it's found)
  2843. @see remove, removeRange
  2844. */
  2845. void removeObject (const ObjectClass* const objectToRemove,
  2846. const bool deleteObject = true)
  2847. {
  2848. lock.enter();
  2849. ObjectClass** e = this->elements;
  2850. for (int i = numUsed; --i >= 0;)
  2851. {
  2852. if (objectToRemove == *e)
  2853. {
  2854. remove ((int) (e - this->elements), deleteObject);
  2855. break;
  2856. }
  2857. ++e;
  2858. }
  2859. lock.exit();
  2860. }
  2861. /** Removes a range of objects from the array.
  2862. This will remove a set of objects, starting from the given index,
  2863. and move any subsequent elements down to close the gap.
  2864. If the range extends beyond the bounds of the array, it will
  2865. be safely clipped to the size of the array.
  2866. @param startIndex the index of the first object to remove
  2867. @param numberToRemove how many objects should be removed
  2868. @param deleteObjects whether to delete the objects that get removed
  2869. @see remove, removeObject
  2870. */
  2871. void removeRange (int startIndex,
  2872. const int numberToRemove,
  2873. const bool deleteObjects = true)
  2874. {
  2875. lock.enter();
  2876. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2877. startIndex = jlimit (0, numUsed, startIndex);
  2878. if (endIndex > startIndex)
  2879. {
  2880. if (deleteObjects)
  2881. {
  2882. for (int i = startIndex; i < endIndex; ++i)
  2883. {
  2884. delete this->elements [i];
  2885. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2886. }
  2887. }
  2888. const int rangeSize = endIndex - startIndex;
  2889. ObjectClass** e = this->elements + startIndex;
  2890. int numToShift = numUsed - endIndex;
  2891. numUsed -= rangeSize;
  2892. while (--numToShift >= 0)
  2893. {
  2894. *e = e [rangeSize];
  2895. ++e;
  2896. }
  2897. if ((numUsed << 1) < this->numAllocated)
  2898. minimiseStorageOverheads();
  2899. }
  2900. lock.exit();
  2901. }
  2902. /** Removes the last n objects from the array.
  2903. @param howManyToRemove how many objects to remove from the end of the array
  2904. @param deleteObjects whether to also delete the objects that are removed
  2905. @see remove, removeObject, removeRange
  2906. */
  2907. void removeLast (int howManyToRemove = 1,
  2908. const bool deleteObjects = true)
  2909. {
  2910. lock.enter();
  2911. if (howManyToRemove >= numUsed)
  2912. {
  2913. clear (deleteObjects);
  2914. }
  2915. else
  2916. {
  2917. while (--howManyToRemove >= 0)
  2918. remove (numUsed - 1, deleteObjects);
  2919. }
  2920. lock.exit();
  2921. }
  2922. /** Swaps a pair of objects in the array.
  2923. If either of the indexes passed in is out-of-range, nothing will happen,
  2924. otherwise the two objects at these positions will be exchanged.
  2925. */
  2926. void swap (const int index1,
  2927. const int index2) throw()
  2928. {
  2929. lock.enter();
  2930. if (((unsigned int) index1) < (unsigned int) numUsed
  2931. && ((unsigned int) index2) < (unsigned int) numUsed)
  2932. {
  2933. swapVariables (this->elements [index1],
  2934. this->elements [index2]);
  2935. }
  2936. lock.exit();
  2937. }
  2938. /** Moves one of the objects to a different position.
  2939. This will move the object to a specified index, shuffling along
  2940. any intervening elements as required.
  2941. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  2942. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  2943. @param currentIndex the index of the object to be moved. If this isn't a
  2944. valid index, then nothing will be done
  2945. @param newIndex the index at which you'd like this object to end up. If this
  2946. is less than zero, it will be moved to the end of the array
  2947. */
  2948. void move (const int currentIndex,
  2949. int newIndex) throw()
  2950. {
  2951. if (currentIndex != newIndex)
  2952. {
  2953. lock.enter();
  2954. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  2955. {
  2956. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  2957. newIndex = numUsed - 1;
  2958. ObjectClass* const value = this->elements [currentIndex];
  2959. if (newIndex > currentIndex)
  2960. {
  2961. memmove (this->elements + currentIndex,
  2962. this->elements + currentIndex + 1,
  2963. (newIndex - currentIndex) * sizeof (ObjectClass*));
  2964. }
  2965. else
  2966. {
  2967. memmove (this->elements + newIndex + 1,
  2968. this->elements + newIndex,
  2969. (currentIndex - newIndex) * sizeof (ObjectClass*));
  2970. }
  2971. this->elements [newIndex] = value;
  2972. }
  2973. lock.exit();
  2974. }
  2975. }
  2976. /** This swaps the contents of this array with those of another array.
  2977. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2978. because it just swaps their internal pointers.
  2979. */
  2980. template <class OtherArrayType>
  2981. void swapWithArray (OtherArrayType& otherArray) throw()
  2982. {
  2983. lock.enter();
  2984. otherArray.lock.enter();
  2985. swapVariables <int> (this->numUsed, otherArray.numUsed);
  2986. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  2987. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  2988. otherArray.lock.exit();
  2989. lock.exit();
  2990. }
  2991. /** Reduces the amount of storage being used by the array.
  2992. Arrays typically allocate slightly more storage than they need, and after
  2993. removing elements, they may have quite a lot of unused space allocated.
  2994. This method will reduce the amount of allocated storage to a minimum.
  2995. */
  2996. void minimiseStorageOverheads() throw()
  2997. {
  2998. lock.enter();
  2999. if (numUsed == 0)
  3000. {
  3001. this->setAllocatedSize (0);
  3002. }
  3003. else
  3004. {
  3005. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3006. if (newAllocation < this->numAllocated)
  3007. this->setAllocatedSize (newAllocation);
  3008. }
  3009. lock.exit();
  3010. }
  3011. /** Increases the array's internal storage to hold a minimum number of elements.
  3012. Calling this before adding a large known number of elements means that
  3013. the array won't have to keep dynamically resizing itself as the elements
  3014. are added, and it'll therefore be more efficient.
  3015. */
  3016. void ensureStorageAllocated (const int minNumElements) throw()
  3017. {
  3018. this->ensureAllocatedSize (minNumElements);
  3019. }
  3020. /** Sorts the elements in the array.
  3021. This will use a comparator object to sort the elements into order. The object
  3022. passed must have a method of the form:
  3023. @code
  3024. int compareElements (ElementType first, ElementType second);
  3025. @endcode
  3026. ..and this method must return:
  3027. - a value of < 0 if the first comes before the second
  3028. - a value of 0 if the two objects are equivalent
  3029. - a value of > 0 if the second comes before the first
  3030. To improve performance, the compareElements() method can be declared as static or const.
  3031. @param comparator the comparator to use for comparing elements.
  3032. @param retainOrderOfEquivalentItems if this is true, then items
  3033. which the comparator says are equivalent will be
  3034. kept in the order in which they currently appear
  3035. in the array. This is slower to perform, but may
  3036. be important in some cases. If it's false, a faster
  3037. algorithm is used, but equivalent elements may be
  3038. rearranged.
  3039. @see sortArray, indexOfSorted
  3040. */
  3041. template <class ElementComparator>
  3042. void sort (ElementComparator& comparator,
  3043. const bool retainOrderOfEquivalentItems = false) const throw()
  3044. {
  3045. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3046. // avoids getting warning messages about the parameter being unused
  3047. lock.enter();
  3048. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3049. lock.exit();
  3050. }
  3051. /** Locks the array's CriticalSection.
  3052. Of course if the type of section used is a DummyCriticalSection, this won't
  3053. have any effect.
  3054. @see unlockArray
  3055. */
  3056. void lockArray() const throw()
  3057. {
  3058. lock.enter();
  3059. }
  3060. /** Unlocks the array's CriticalSection.
  3061. Of course if the type of section used is a DummyCriticalSection, this won't
  3062. have any effect.
  3063. @see lockArray
  3064. */
  3065. void unlockArray() const throw()
  3066. {
  3067. lock.exit();
  3068. }
  3069. juce_UseDebuggingNewOperator
  3070. private:
  3071. int numUsed;
  3072. TypeOfCriticalSectionToUse lock;
  3073. // disallow copy constructor and assignment
  3074. OwnedArray (const OwnedArray&);
  3075. const OwnedArray& operator= (const OwnedArray&);
  3076. };
  3077. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3078. /********* End of inlined file: juce_OwnedArray.h *********/
  3079. /********* Start of inlined file: juce_Time.h *********/
  3080. #ifndef __JUCE_TIME_JUCEHEADER__
  3081. #define __JUCE_TIME_JUCEHEADER__
  3082. /********* Start of inlined file: juce_RelativeTime.h *********/
  3083. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3084. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3085. /** A relative measure of time.
  3086. The time is stored as a number of seconds, at double-precision floating
  3087. point accuracy, and may be positive or negative.
  3088. If you need an absolute time, (i.e. a date + time), see the Time class.
  3089. */
  3090. class JUCE_API RelativeTime
  3091. {
  3092. public:
  3093. /** Creates a RelativeTime.
  3094. @param seconds the number of seconds, which may be +ve or -ve.
  3095. @see milliseconds, minutes, hours, days, weeks
  3096. */
  3097. explicit RelativeTime (const double seconds = 0.0) throw();
  3098. /** Copies another relative time. */
  3099. RelativeTime (const RelativeTime& other) throw();
  3100. /** Copies another relative time. */
  3101. const RelativeTime& operator= (const RelativeTime& other) throw();
  3102. /** Destructor. */
  3103. ~RelativeTime() throw();
  3104. /** Creates a new RelativeTime object representing a number of milliseconds.
  3105. @see minutes, hours, days, weeks
  3106. */
  3107. static const RelativeTime milliseconds (const int milliseconds) throw();
  3108. /** Creates a new RelativeTime object representing a number of milliseconds.
  3109. @see minutes, hours, days, weeks
  3110. */
  3111. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3112. /** Creates a new RelativeTime object representing a number of minutes.
  3113. @see milliseconds, hours, days, weeks
  3114. */
  3115. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3116. /** Creates a new RelativeTime object representing a number of hours.
  3117. @see milliseconds, minutes, days, weeks
  3118. */
  3119. static const RelativeTime hours (const double numberOfHours) throw();
  3120. /** Creates a new RelativeTime object representing a number of days.
  3121. @see milliseconds, minutes, hours, weeks
  3122. */
  3123. static const RelativeTime days (const double numberOfDays) throw();
  3124. /** Creates a new RelativeTime object representing a number of weeks.
  3125. @see milliseconds, minutes, hours, days
  3126. */
  3127. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3128. /** Returns the number of milliseconds this time represents.
  3129. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3130. */
  3131. int64 inMilliseconds() const throw();
  3132. /** Returns the number of seconds this time represents.
  3133. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3134. */
  3135. double inSeconds() const throw() { return seconds; }
  3136. /** Returns the number of minutes this time represents.
  3137. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3138. */
  3139. double inMinutes() const throw();
  3140. /** Returns the number of hours this time represents.
  3141. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3142. */
  3143. double inHours() const throw();
  3144. /** Returns the number of days this time represents.
  3145. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3146. */
  3147. double inDays() const throw();
  3148. /** Returns the number of weeks this time represents.
  3149. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3150. */
  3151. double inWeeks() const throw();
  3152. /** Returns a readable textual description of the time.
  3153. The exact format of the string returned will depend on
  3154. the magnitude of the time - e.g.
  3155. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3156. so that only the two most significant units are printed.
  3157. The returnValueForZeroTime value is the result that is returned if the
  3158. length is zero. Depending on your application you might want to use this
  3159. to return something more relevant like "empty" or "0 secs", etc.
  3160. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3161. */
  3162. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3163. /** Compares two RelativeTimes. */
  3164. bool operator== (const RelativeTime& other) const throw();
  3165. /** Compares two RelativeTimes. */
  3166. bool operator!= (const RelativeTime& other) const throw();
  3167. /** Compares two RelativeTimes. */
  3168. bool operator> (const RelativeTime& other) const throw();
  3169. /** Compares two RelativeTimes. */
  3170. bool operator< (const RelativeTime& other) const throw();
  3171. /** Compares two RelativeTimes. */
  3172. bool operator>= (const RelativeTime& other) const throw();
  3173. /** Compares two RelativeTimes. */
  3174. bool operator<= (const RelativeTime& other) const throw();
  3175. /** Adds another RelativeTime to this one and returns the result. */
  3176. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3177. /** Subtracts another RelativeTime from this one and returns the result. */
  3178. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3179. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3180. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3181. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3182. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3183. /** Adds another RelativeTime to this one. */
  3184. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3185. /** Subtracts another RelativeTime from this one. */
  3186. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3187. /** Adds a number of seconds to this time. */
  3188. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3189. /** Subtracts a number of seconds from this time. */
  3190. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3191. juce_UseDebuggingNewOperator
  3192. private:
  3193. double seconds;
  3194. };
  3195. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3196. /********* End of inlined file: juce_RelativeTime.h *********/
  3197. /**
  3198. Holds an absolute date and time.
  3199. Internally, the time is stored at millisecond precision.
  3200. @see RelativeTime
  3201. */
  3202. class JUCE_API Time
  3203. {
  3204. public:
  3205. /** Creates a Time object.
  3206. This default constructor creates a time of 1st January 1970, (which is
  3207. represented internally as 0ms).
  3208. To create a time object representing the current time, use getCurrentTime().
  3209. @see getCurrentTime
  3210. */
  3211. Time() throw();
  3212. /** Creates a copy of another Time object. */
  3213. Time (const Time& other) throw();
  3214. /** Creates a time based on a number of milliseconds.
  3215. The internal millisecond count is set to 0 (1st January 1970). To create a
  3216. time object set to the current time, use getCurrentTime().
  3217. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3218. 'epoch' (midnight Jan 1st 1970).
  3219. @see getCurrentTime, currentTimeMillis
  3220. */
  3221. Time (const int64 millisecondsSinceEpoch) throw();
  3222. /** Creates a time from a set of date components.
  3223. The timezone is assumed to be whatever the system is using as its locale.
  3224. @param year the year, in 4-digit format, e.g. 2004
  3225. @param month the month, in the range 0 to 11
  3226. @param day the day of the month, in the range 1 to 31
  3227. @param hours hours in 24-hour clock format, 0 to 23
  3228. @param minutes minutes 0 to 59
  3229. @param seconds seconds 0 to 59
  3230. @param milliseconds milliseconds 0 to 999
  3231. @param useLocalTime if true, encode using the current machine's local time; if
  3232. false, it will always work in GMT.
  3233. */
  3234. Time (const int year,
  3235. const int month,
  3236. const int day,
  3237. const int hours,
  3238. const int minutes,
  3239. const int seconds = 0,
  3240. const int milliseconds = 0,
  3241. const bool useLocalTime = true) throw();
  3242. /** Destructor. */
  3243. ~Time() throw();
  3244. /** Copies this time from another one. */
  3245. const Time& operator= (const Time& other) throw();
  3246. /** Returns a Time object that is set to the current system time.
  3247. @see currentTimeMillis
  3248. */
  3249. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3250. /** Returns the time as a number of milliseconds.
  3251. @returns the number of milliseconds this Time object represents, since
  3252. midnight jan 1st 1970.
  3253. @see getMilliseconds
  3254. */
  3255. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3256. /** Returns the year.
  3257. A 4-digit format is used, e.g. 2004.
  3258. */
  3259. int getYear() const throw();
  3260. /** Returns the number of the month.
  3261. The value returned is in the range 0 to 11.
  3262. @see getMonthName
  3263. */
  3264. int getMonth() const throw();
  3265. /** Returns the name of the month.
  3266. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3267. it'll return the long form, e.g. "January"
  3268. @see getMonth
  3269. */
  3270. const String getMonthName (const bool threeLetterVersion) const throw();
  3271. /** Returns the day of the month.
  3272. The value returned is in the range 1 to 31.
  3273. */
  3274. int getDayOfMonth() const throw();
  3275. /** Returns the number of the day of the week.
  3276. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3277. */
  3278. int getDayOfWeek() const throw();
  3279. /** Returns the name of the weekday.
  3280. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3281. false, it'll return the full version, e.g. "Tuesday".
  3282. */
  3283. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3284. /** Returns the number of hours since midnight.
  3285. This is in 24-hour clock format, in the range 0 to 23.
  3286. @see getHoursInAmPmFormat, isAfternoon
  3287. */
  3288. int getHours() const throw();
  3289. /** Returns true if the time is in the afternoon.
  3290. So it returns true for "PM", false for "AM".
  3291. @see getHoursInAmPmFormat, getHours
  3292. */
  3293. bool isAfternoon() const throw();
  3294. /** Returns the hours in 12-hour clock format.
  3295. This will return a value 1 to 12 - use isAfternoon() to find out
  3296. whether this is in the afternoon or morning.
  3297. @see getHours, isAfternoon
  3298. */
  3299. int getHoursInAmPmFormat() const throw();
  3300. /** Returns the number of minutes, 0 to 59. */
  3301. int getMinutes() const throw();
  3302. /** Returns the number of seconds, 0 to 59. */
  3303. int getSeconds() const throw();
  3304. /** Returns the number of milliseconds, 0 to 999.
  3305. Unlike toMilliseconds(), this just returns the position within the
  3306. current second rather than the total number since the epoch.
  3307. @see toMilliseconds
  3308. */
  3309. int getMilliseconds() const throw();
  3310. /** Returns true if the local timezone uses a daylight saving correction. */
  3311. bool isDaylightSavingTime() const throw();
  3312. /** Returns a 3-character string to indicate the local timezone. */
  3313. const String getTimeZone() const throw();
  3314. /** Quick way of getting a string version of a date and time.
  3315. For a more powerful way of formatting the date and time, see the formatted() method.
  3316. @param includeDate whether to include the date in the string
  3317. @param includeTime whether to include the time in the string
  3318. @param includeSeconds if the time is being included, this provides an option not to include
  3319. the seconds in it
  3320. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3321. hour notation.
  3322. @see formatted
  3323. */
  3324. const String toString (const bool includeDate,
  3325. const bool includeTime,
  3326. const bool includeSeconds = true,
  3327. const bool use24HourClock = false) const throw();
  3328. /** Converts this date/time to a string with a user-defined format.
  3329. This uses the C strftime() function to format this time as a string. To save you
  3330. looking it up, these are the escape codes that strftime uses (other codes might
  3331. work on some platforms and not others, but these are the common ones):
  3332. %a is replaced by the locale's abbreviated weekday name.
  3333. %A is replaced by the locale's full weekday name.
  3334. %b is replaced by the locale's abbreviated month name.
  3335. %B is replaced by the locale's full month name.
  3336. %c is replaced by the locale's appropriate date and time representation.
  3337. %d is replaced by the day of the month as a decimal number [01,31].
  3338. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3339. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3340. %j is replaced by the day of the year as a decimal number [001,366].
  3341. %m is replaced by the month as a decimal number [01,12].
  3342. %M is replaced by the minute as a decimal number [00,59].
  3343. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3344. %S is replaced by the second as a decimal number [00,61].
  3345. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3346. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3347. %W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
  3348. %x is replaced by the locale's appropriate date representation.
  3349. %X is replaced by the locale's appropriate time representation.
  3350. %y is replaced by the year without century as a decimal number [00,99].
  3351. %Y is replaced by the year with century as a decimal number.
  3352. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3353. %% is replaced by %.
  3354. @see toString
  3355. */
  3356. const String formatted (const tchar* const format) const throw();
  3357. /** Adds a RelativeTime to this time and returns the result. */
  3358. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3359. /** Subtracts a RelativeTime from this time and returns the result. */
  3360. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3361. /** Returns the relative time difference between this time and another one. */
  3362. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3363. /** Compares two Time objects. */
  3364. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3365. /** Compares two Time objects. */
  3366. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3367. /** Compares two Time objects. */
  3368. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3369. /** Compares two Time objects. */
  3370. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3371. /** Compares two Time objects. */
  3372. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3373. /** Compares two Time objects. */
  3374. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3375. /** Tries to set the computer's clock.
  3376. @returns true if this succeeds, although depending on the system, the
  3377. application might not have sufficient privileges to do this.
  3378. */
  3379. bool setSystemTimeToThisTime() const throw();
  3380. /** Returns the name of a day of the week.
  3381. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3382. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3383. false, it'll return the full version, e.g. "Tuesday".
  3384. */
  3385. static const String getWeekdayName (int dayNumber,
  3386. const bool threeLetterVersion) throw();
  3387. /** Returns the name of one of the months.
  3388. @param monthNumber the month, 0 to 11
  3389. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3390. it'll return the long form, e.g. "January"
  3391. */
  3392. static const String getMonthName (int monthNumber,
  3393. const bool threeLetterVersion) throw();
  3394. // Static methods for getting system timers directly..
  3395. /** Returns the current system time.
  3396. Returns the number of milliseconds since midnight jan 1st 1970.
  3397. Should be accurate to within a few millisecs, depending on platform,
  3398. hardware, etc.
  3399. */
  3400. static int64 currentTimeMillis() throw();
  3401. /** Returns the number of millisecs since system startup.
  3402. Should be accurate to within a few millisecs, depending on platform,
  3403. hardware, etc.
  3404. @see getApproximateMillisecondCounter
  3405. */
  3406. static uint32 getMillisecondCounter() throw();
  3407. /** Returns the number of millisecs since system startup.
  3408. Same as getMillisecondCounter(), but returns a more accurate value, using
  3409. the high-res timer.
  3410. @see getMillisecondCounter
  3411. */
  3412. static double getMillisecondCounterHiRes() throw();
  3413. /** Waits until the getMillisecondCounter() reaches a given value.
  3414. This will make the thread sleep as efficiently as it can while it's waiting.
  3415. */
  3416. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3417. /** Less-accurate but faster version of getMillisecondCounter().
  3418. This will return the last value that getMillisecondCounter() returned, so doesn't
  3419. need to make a system call, but is less accurate - it shouldn't be more than
  3420. 100ms away from the correct time, though, so is still accurate enough for a
  3421. lot of purposes.
  3422. @see getMillisecondCounter
  3423. */
  3424. static uint32 getApproximateMillisecondCounter() throw();
  3425. // High-resolution timers..
  3426. /** Returns the current high-resolution counter's tick-count.
  3427. This is a similar idea to getMillisecondCounter(), but with a higher
  3428. resolution.
  3429. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3430. secondsToHighResolutionTicks
  3431. */
  3432. static int64 getHighResolutionTicks() throw();
  3433. /** Returns the resolution of the high-resolution counter in ticks per second.
  3434. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3435. secondsToHighResolutionTicks
  3436. */
  3437. static int64 getHighResolutionTicksPerSecond() throw();
  3438. /** Converts a number of high-resolution ticks into seconds.
  3439. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3440. secondsToHighResolutionTicks
  3441. */
  3442. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3443. /** Converts a number seconds into high-resolution ticks.
  3444. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3445. highResolutionTicksToSeconds
  3446. */
  3447. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3448. private:
  3449. int64 millisSinceEpoch;
  3450. };
  3451. #endif // __JUCE_TIME_JUCEHEADER__
  3452. /********* End of inlined file: juce_Time.h *********/
  3453. /********* Start of inlined file: juce_StringArray.h *********/
  3454. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3455. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3456. /********* Start of inlined file: juce_VoidArray.h *********/
  3457. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3458. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3459. /********* Start of inlined file: juce_Array.h *********/
  3460. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3461. #define __JUCE_ARRAY_JUCEHEADER__
  3462. /**
  3463. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3464. Examples of arrays are: Array<int> or Array<MyClass*>
  3465. Note that when holding pointers to objects, the array doesn't take any ownership
  3466. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3467. If you're using a class or struct as the element type, it must be
  3468. capable of being copied or moved with a straightforward memcpy, rather than
  3469. needing construction and destruction code.
  3470. For holding lists of strings, use the specialised class StringArray.
  3471. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3472. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3473. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3474. */
  3475. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3476. class Array : private ArrayAllocationBase <ElementType>
  3477. {
  3478. public:
  3479. /** Creates an empty array.
  3480. @param granularity this is the size of increment by which the internal storage
  3481. used by the array will grow. Only change it from the default if you know the
  3482. array is going to be very big and needs to be able to grow efficiently.
  3483. @see ArrayAllocationBase
  3484. */
  3485. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3486. : ArrayAllocationBase <ElementType> (granularity),
  3487. numUsed (0)
  3488. {
  3489. }
  3490. /** Creates a copy of another array.
  3491. @param other the array to copy
  3492. */
  3493. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3494. : ArrayAllocationBase <ElementType> (other.granularity)
  3495. {
  3496. other.lockArray();
  3497. numUsed = other.numUsed;
  3498. this->setAllocatedSize (other.numUsed);
  3499. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3500. other.unlockArray();
  3501. }
  3502. /** Initalises from a null-terminated C array of values.
  3503. @param values the array to copy from
  3504. */
  3505. Array (const ElementType* values) throw()
  3506. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3507. numUsed (0)
  3508. {
  3509. while (*values != 0)
  3510. add (*values++);
  3511. }
  3512. /** Initalises from a C array of values.
  3513. @param values the array to copy from
  3514. @param numValues the number of values in the array
  3515. */
  3516. Array (const ElementType* values, int numValues) throw()
  3517. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3518. numUsed (numValues)
  3519. {
  3520. this->setAllocatedSize (numValues);
  3521. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3522. }
  3523. /** Destructor. */
  3524. ~Array() throw()
  3525. {
  3526. }
  3527. /** Copies another array.
  3528. @param other the array to copy
  3529. */
  3530. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3531. {
  3532. if (this != &other)
  3533. {
  3534. other.lockArray();
  3535. lock.enter();
  3536. this->granularity = other.granularity;
  3537. this->ensureAllocatedSize (other.size());
  3538. numUsed = other.numUsed;
  3539. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3540. minimiseStorageOverheads();
  3541. lock.exit();
  3542. other.unlockArray();
  3543. }
  3544. return *this;
  3545. }
  3546. /** Compares this array to another one.
  3547. Two arrays are considered equal if they both contain the same set of
  3548. elements, in the same order.
  3549. @param other the other array to compare with
  3550. */
  3551. template <class OtherArrayType>
  3552. bool operator== (const OtherArrayType& other) const throw()
  3553. {
  3554. lock.enter();
  3555. if (this->numUsed != other.numUsed)
  3556. {
  3557. lock.exit();
  3558. return false;
  3559. }
  3560. for (int i = numUsed; --i >= 0;)
  3561. {
  3562. if (this->elements [i] != other.elements [i])
  3563. {
  3564. lock.exit();
  3565. return false;
  3566. }
  3567. }
  3568. lock.exit();
  3569. return true;
  3570. }
  3571. /** Compares this array to another one.
  3572. Two arrays are considered equal if they both contain the same set of
  3573. elements, in the same order.
  3574. @param other the other array to compare with
  3575. */
  3576. template <class OtherArrayType>
  3577. bool operator!= (const OtherArrayType& other) const throw()
  3578. {
  3579. return ! operator== (other);
  3580. }
  3581. /** Removes all elements from the array.
  3582. This will remove all the elements, and free any storage that the array is
  3583. using. To clear the array without freeing the storage, use the clearQuick()
  3584. method instead.
  3585. @see clearQuick
  3586. */
  3587. void clear() throw()
  3588. {
  3589. lock.enter();
  3590. this->setAllocatedSize (0);
  3591. numUsed = 0;
  3592. lock.exit();
  3593. }
  3594. /** Removes all elements from the array without freeing the array's allocated storage.
  3595. @see clear
  3596. */
  3597. void clearQuick() throw()
  3598. {
  3599. lock.enter();
  3600. numUsed = 0;
  3601. lock.exit();
  3602. }
  3603. /** Returns the current number of elements in the array.
  3604. */
  3605. inline int size() const throw()
  3606. {
  3607. return numUsed;
  3608. }
  3609. /** Returns one of the elements in the array.
  3610. If the index passed in is beyond the range of valid elements, this
  3611. will return zero.
  3612. If you're certain that the index will always be a valid element, you
  3613. can call getUnchecked() instead, which is faster.
  3614. @param index the index of the element being requested (0 is the first element in the array)
  3615. @see getUnchecked, getFirst, getLast
  3616. */
  3617. inline ElementType operator[] (const int index) const throw()
  3618. {
  3619. lock.enter();
  3620. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3621. ? this->elements [index]
  3622. : ElementType();
  3623. lock.exit();
  3624. return result;
  3625. }
  3626. /** Returns one of the elements in the array, without checking the index passed in.
  3627. Unlike the operator[] method, this will try to return an element without
  3628. checking that the index is within the bounds of the array, so should only
  3629. be used when you're confident that it will always be a valid index.
  3630. @param index the index of the element being requested (0 is the first element in the array)
  3631. @see operator[], getFirst, getLast
  3632. */
  3633. inline ElementType getUnchecked (const int index) const throw()
  3634. {
  3635. lock.enter();
  3636. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3637. const ElementType result = this->elements [index];
  3638. lock.exit();
  3639. return result;
  3640. }
  3641. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3642. This is like getUnchecked, but returns a direct reference to the element, so that
  3643. you can alter it directly. Obviously this can be dangerous, so only use it when
  3644. absolutely necessary.
  3645. @param index the index of the element being requested (0 is the first element in the array)
  3646. @see operator[], getFirst, getLast
  3647. */
  3648. inline ElementType& getReference (const int index) const throw()
  3649. {
  3650. lock.enter();
  3651. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3652. ElementType& result = this->elements [index];
  3653. lock.exit();
  3654. return result;
  3655. }
  3656. /** Returns the first element in the array, or 0 if the array is empty.
  3657. @see operator[], getUnchecked, getLast
  3658. */
  3659. inline ElementType getFirst() const throw()
  3660. {
  3661. lock.enter();
  3662. const ElementType result = (numUsed > 0) ? this->elements [0]
  3663. : ElementType();
  3664. lock.exit();
  3665. return result;
  3666. }
  3667. /** Returns the last element in the array, or 0 if the array is empty.
  3668. @see operator[], getUnchecked, getFirst
  3669. */
  3670. inline ElementType getLast() const throw()
  3671. {
  3672. lock.enter();
  3673. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3674. : ElementType();
  3675. lock.exit();
  3676. return result;
  3677. }
  3678. /** Finds the index of the first element which matches the value passed in.
  3679. This will search the array for the given object, and return the index
  3680. of its first occurrence. If the object isn't found, the method will return -1.
  3681. @param elementToLookFor the value or object to look for
  3682. @returns the index of the object, or -1 if it's not found
  3683. */
  3684. int indexOf (const ElementType elementToLookFor) const throw()
  3685. {
  3686. int result = -1;
  3687. lock.enter();
  3688. const ElementType* e = this->elements;
  3689. for (int i = numUsed; --i >= 0;)
  3690. {
  3691. if (elementToLookFor == *e)
  3692. {
  3693. result = (int) (e - this->elements);
  3694. break;
  3695. }
  3696. ++e;
  3697. }
  3698. lock.exit();
  3699. return result;
  3700. }
  3701. /** Returns true if the array contains at least one occurrence of an object.
  3702. @param elementToLookFor the value or object to look for
  3703. @returns true if the item is found
  3704. */
  3705. bool contains (const ElementType elementToLookFor) const throw()
  3706. {
  3707. lock.enter();
  3708. const ElementType* e = this->elements;
  3709. int num = numUsed;
  3710. while (num >= 4)
  3711. {
  3712. if (*e == elementToLookFor
  3713. || *++e == elementToLookFor
  3714. || *++e == elementToLookFor
  3715. || *++e == elementToLookFor)
  3716. {
  3717. lock.exit();
  3718. return true;
  3719. }
  3720. num -= 4;
  3721. ++e;
  3722. }
  3723. while (num > 0)
  3724. {
  3725. if (elementToLookFor == *e)
  3726. {
  3727. lock.exit();
  3728. return true;
  3729. }
  3730. --num;
  3731. ++e;
  3732. }
  3733. lock.exit();
  3734. return false;
  3735. }
  3736. /** Appends a new element at the end of the array.
  3737. @param newElement the new object to add to the array
  3738. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3739. */
  3740. void add (const ElementType newElement) throw()
  3741. {
  3742. lock.enter();
  3743. this->ensureAllocatedSize (numUsed + 1);
  3744. this->elements [numUsed++] = newElement;
  3745. lock.exit();
  3746. }
  3747. /** Inserts a new element into the array at a given position.
  3748. If the index is less than 0 or greater than the size of the array, the
  3749. element will be added to the end of the array.
  3750. Otherwise, it will be inserted into the array, moving all the later elements
  3751. along to make room.
  3752. @param indexToInsertAt the index at which the new element should be
  3753. inserted (pass in -1 to add it to the end)
  3754. @param newElement the new object to add to the array
  3755. @see add, addSorted, set
  3756. */
  3757. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3758. {
  3759. lock.enter();
  3760. this->ensureAllocatedSize (numUsed + 1);
  3761. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3762. {
  3763. ElementType* const insertPos = this->elements + indexToInsertAt;
  3764. const int numberToMove = numUsed - indexToInsertAt;
  3765. if (numberToMove > 0)
  3766. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3767. *insertPos = newElement;
  3768. ++numUsed;
  3769. }
  3770. else
  3771. {
  3772. this->elements [numUsed++] = newElement;
  3773. }
  3774. lock.exit();
  3775. }
  3776. /** Inserts multiple copies of an element into the array at a given position.
  3777. If the index is less than 0 or greater than the size of the array, the
  3778. element will be added to the end of the array.
  3779. Otherwise, it will be inserted into the array, moving all the later elements
  3780. along to make room.
  3781. @param indexToInsertAt the index at which the new element should be inserted
  3782. @param newElement the new object to add to the array
  3783. @param numberOfTimesToInsertIt how many copies of the value to insert
  3784. @see insert, add, addSorted, set
  3785. */
  3786. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3787. int numberOfTimesToInsertIt) throw()
  3788. {
  3789. if (numberOfTimesToInsertIt > 0)
  3790. {
  3791. lock.enter();
  3792. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3793. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3794. {
  3795. ElementType* insertPos = this->elements + indexToInsertAt;
  3796. const int numberToMove = numUsed - indexToInsertAt;
  3797. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3798. numUsed += numberOfTimesToInsertIt;
  3799. while (--numberOfTimesToInsertIt >= 0)
  3800. *insertPos++ = newElement;
  3801. }
  3802. else
  3803. {
  3804. while (--numberOfTimesToInsertIt >= 0)
  3805. this->elements [numUsed++] = newElement;
  3806. }
  3807. lock.exit();
  3808. }
  3809. }
  3810. /** Inserts an array of values into this array at a given position.
  3811. If the index is less than 0 or greater than the size of the array, the
  3812. new elements will be added to the end of the array.
  3813. Otherwise, they will be inserted into the array, moving all the later elements
  3814. along to make room.
  3815. @param indexToInsertAt the index at which the first new element should be inserted
  3816. @param newElements the new values to add to the array
  3817. @param numberOfElements how many items are in the array
  3818. @see insert, add, addSorted, set
  3819. */
  3820. void insertArray (int indexToInsertAt,
  3821. const ElementType* newElements,
  3822. int numberOfElements) throw()
  3823. {
  3824. if (numberOfElements > 0)
  3825. {
  3826. lock.enter();
  3827. this->ensureAllocatedSize (numUsed + numberOfElements);
  3828. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3829. {
  3830. ElementType* insertPos = this->elements + indexToInsertAt;
  3831. const int numberToMove = numUsed - indexToInsertAt;
  3832. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3833. numUsed += numberOfElements;
  3834. while (--numberOfElements >= 0)
  3835. *insertPos++ = *newElements++;
  3836. }
  3837. else
  3838. {
  3839. while (--numberOfElements >= 0)
  3840. this->elements [numUsed++] = *newElements++;
  3841. }
  3842. lock.exit();
  3843. }
  3844. }
  3845. /** Appends a new element at the end of the array as long as the array doesn't
  3846. already contain it.
  3847. If the array already contains an element that matches the one passed in, nothing
  3848. will be done.
  3849. @param newElement the new object to add to the array
  3850. */
  3851. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3852. {
  3853. lock.enter();
  3854. if (! contains (newElement))
  3855. add (newElement);
  3856. lock.exit();
  3857. }
  3858. /** Replaces an element with a new value.
  3859. If the index is less than zero, this method does nothing.
  3860. If the index is beyond the end of the array, the item is added to the end of the array.
  3861. @param indexToChange the index whose value you want to change
  3862. @param newValue the new value to set for this index.
  3863. @see add, insert
  3864. */
  3865. void set (const int indexToChange,
  3866. const ElementType newValue) throw()
  3867. {
  3868. jassert (indexToChange >= 0);
  3869. if (indexToChange >= 0)
  3870. {
  3871. lock.enter();
  3872. if (indexToChange < numUsed)
  3873. {
  3874. this->elements [indexToChange] = newValue;
  3875. }
  3876. else
  3877. {
  3878. this->ensureAllocatedSize (numUsed + 1);
  3879. this->elements [numUsed++] = newValue;
  3880. }
  3881. lock.exit();
  3882. }
  3883. }
  3884. /** Replaces an element with a new value without doing any bounds-checking.
  3885. This just sets a value directly in the array's internal storage, so you'd
  3886. better make sure it's in range!
  3887. @param indexToChange the index whose value you want to change
  3888. @param newValue the new value to set for this index.
  3889. @see set, getUnchecked
  3890. */
  3891. void setUnchecked (const int indexToChange,
  3892. const ElementType newValue) throw()
  3893. {
  3894. lock.enter();
  3895. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3896. this->elements [indexToChange] = newValue;
  3897. lock.exit();
  3898. }
  3899. /** Adds elements from an array to the end of this array.
  3900. @param elementsToAdd the array of elements to add
  3901. @param numElementsToAdd how many elements are in this other array
  3902. @see add
  3903. */
  3904. void addArray (const ElementType* elementsToAdd,
  3905. int numElementsToAdd) throw()
  3906. {
  3907. lock.enter();
  3908. if (numElementsToAdd > 0)
  3909. {
  3910. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3911. while (--numElementsToAdd >= 0)
  3912. this->elements [numUsed++] = *elementsToAdd++;
  3913. }
  3914. lock.exit();
  3915. }
  3916. /** This swaps the contents of this array with those of another array.
  3917. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3918. because it just swaps their internal pointers.
  3919. */
  3920. template <class OtherArrayType>
  3921. void swapWithArray (OtherArrayType& otherArray) throw()
  3922. {
  3923. lock.enter();
  3924. otherArray.lock.enter();
  3925. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3926. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3927. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3928. otherArray.lock.exit();
  3929. lock.exit();
  3930. }
  3931. /** Adds elements from another array to the end of this array.
  3932. @param arrayToAddFrom the array from which to copy the elements
  3933. @param startIndex the first element of the other array to start copying from
  3934. @param numElementsToAdd how many elements to add from the other array. If this
  3935. value is negative or greater than the number of available elements,
  3936. all available elements will be copied.
  3937. @see add
  3938. */
  3939. template <class OtherArrayType>
  3940. void addArray (const OtherArrayType& arrayToAddFrom,
  3941. int startIndex = 0,
  3942. int numElementsToAdd = -1) throw()
  3943. {
  3944. arrayToAddFrom.lockArray();
  3945. lock.enter();
  3946. jassert (this != &arrayToAddFrom);
  3947. if (startIndex < 0)
  3948. {
  3949. jassertfalse
  3950. startIndex = 0;
  3951. }
  3952. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3953. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3954. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  3955. lock.exit();
  3956. arrayToAddFrom.unlockArray();
  3957. }
  3958. /** Inserts a new element into the array, assuming that the array is sorted.
  3959. This will use a comparator to find the position at which the new element
  3960. should go. If the array isn't sorted, the behaviour of this
  3961. method will be unpredictable.
  3962. @param comparator the comparator to use to compare the elements - see the sort()
  3963. method for details about the form this object should take
  3964. @param newElement the new element to insert to the array
  3965. @see add, sort
  3966. */
  3967. template <class ElementComparator>
  3968. void addSorted (ElementComparator& comparator,
  3969. const ElementType newElement) throw()
  3970. {
  3971. lock.enter();
  3972. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  3973. lock.exit();
  3974. }
  3975. /** Finds the index of an element in the array, assuming that the array is sorted.
  3976. This will use a comparator to do a binary-chop to find the index of the given
  3977. element, if it exists. If the array isn't sorted, the behaviour of this
  3978. method will be unpredictable.
  3979. @param comparator the comparator to use to compare the elements - see the sort()
  3980. method for details about the form this object should take
  3981. @param elementToLookFor the element to search for
  3982. @returns the index of the element, or -1 if it's not found
  3983. @see addSorted, sort
  3984. */
  3985. template <class ElementComparator>
  3986. int indexOfSorted (ElementComparator& comparator,
  3987. const ElementType elementToLookFor) const throw()
  3988. {
  3989. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3990. // avoids getting warning messages about the parameter being unused
  3991. lock.enter();
  3992. int start = 0;
  3993. int end = numUsed;
  3994. for (;;)
  3995. {
  3996. if (start >= end)
  3997. {
  3998. lock.exit();
  3999. return -1;
  4000. }
  4001. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4002. {
  4003. lock.exit();
  4004. return start;
  4005. }
  4006. else
  4007. {
  4008. const int halfway = (start + end) >> 1;
  4009. if (halfway == start)
  4010. {
  4011. lock.exit();
  4012. return -1;
  4013. }
  4014. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4015. start = halfway;
  4016. else
  4017. end = halfway;
  4018. }
  4019. }
  4020. }
  4021. /** Removes an element from the array.
  4022. This will remove the element at a given index, and move back
  4023. all the subsequent elements to close the gap.
  4024. If the index passed in is out-of-range, nothing will happen.
  4025. @param indexToRemove the index of the element to remove
  4026. @returns the element that has been removed
  4027. @see removeValue, removeRange
  4028. */
  4029. ElementType remove (const int indexToRemove) throw()
  4030. {
  4031. lock.enter();
  4032. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4033. {
  4034. --numUsed;
  4035. ElementType* const e = this->elements + indexToRemove;
  4036. ElementType const removed = *e;
  4037. const int numberToShift = numUsed - indexToRemove;
  4038. if (numberToShift > 0)
  4039. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4040. if ((numUsed << 1) < this->numAllocated)
  4041. minimiseStorageOverheads();
  4042. lock.exit();
  4043. return removed;
  4044. }
  4045. else
  4046. {
  4047. lock.exit();
  4048. return ElementType();
  4049. }
  4050. }
  4051. /** Removes an item from the array.
  4052. This will remove the first occurrence of the given element from the array.
  4053. If the item isn't found, no action is taken.
  4054. @param valueToRemove the object to try to remove
  4055. @see remove, removeRange
  4056. */
  4057. void removeValue (const ElementType valueToRemove) throw()
  4058. {
  4059. lock.enter();
  4060. ElementType* e = this->elements;
  4061. for (int i = numUsed; --i >= 0;)
  4062. {
  4063. if (valueToRemove == *e)
  4064. {
  4065. remove ((int) (e - this->elements));
  4066. break;
  4067. }
  4068. ++e;
  4069. }
  4070. lock.exit();
  4071. }
  4072. /** Removes a range of elements from the array.
  4073. This will remove a set of elements, starting from the given index,
  4074. and move subsequent elements down to close the gap.
  4075. If the range extends beyond the bounds of the array, it will
  4076. be safely clipped to the size of the array.
  4077. @param startIndex the index of the first element to remove
  4078. @param numberToRemove how many elements should be removed
  4079. @see remove, removeValue
  4080. */
  4081. void removeRange (int startIndex,
  4082. const int numberToRemove) throw()
  4083. {
  4084. lock.enter();
  4085. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4086. startIndex = jlimit (0, numUsed, startIndex);
  4087. if (endIndex > startIndex)
  4088. {
  4089. const int rangeSize = endIndex - startIndex;
  4090. ElementType* e = this->elements + startIndex;
  4091. int numToShift = numUsed - endIndex;
  4092. numUsed -= rangeSize;
  4093. while (--numToShift >= 0)
  4094. {
  4095. *e = e [rangeSize];
  4096. ++e;
  4097. }
  4098. if ((numUsed << 1) < this->numAllocated)
  4099. minimiseStorageOverheads();
  4100. }
  4101. lock.exit();
  4102. }
  4103. /** Removes the last n elements from the array.
  4104. @param howManyToRemove how many elements to remove from the end of the array
  4105. @see remove, removeValue, removeRange
  4106. */
  4107. void removeLast (const int howManyToRemove = 1) throw()
  4108. {
  4109. lock.enter();
  4110. numUsed = jmax (0, numUsed - howManyToRemove);
  4111. if ((numUsed << 1) < this->numAllocated)
  4112. minimiseStorageOverheads();
  4113. lock.exit();
  4114. }
  4115. /** Removes any elements which are also in another array.
  4116. @param otherArray the other array in which to look for elements to remove
  4117. @see removeValuesNotIn, remove, removeValue, removeRange
  4118. */
  4119. template <class OtherArrayType>
  4120. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4121. {
  4122. otherArray.lockArray();
  4123. lock.enter();
  4124. if (this == &otherArray)
  4125. {
  4126. clear();
  4127. }
  4128. else
  4129. {
  4130. if (otherArray.size() > 0)
  4131. {
  4132. for (int i = numUsed; --i >= 0;)
  4133. if (otherArray.contains (this->elements [i]))
  4134. remove (i);
  4135. }
  4136. }
  4137. lock.exit();
  4138. otherArray.unlockArray();
  4139. }
  4140. /** Removes any elements which are not found in another array.
  4141. Only elements which occur in this other array will be retained.
  4142. @param otherArray the array in which to look for elements NOT to remove
  4143. @see removeValuesIn, remove, removeValue, removeRange
  4144. */
  4145. template <class OtherArrayType>
  4146. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4147. {
  4148. otherArray.lockArray();
  4149. lock.enter();
  4150. if (this != &otherArray)
  4151. {
  4152. if (otherArray.size() <= 0)
  4153. {
  4154. clear();
  4155. }
  4156. else
  4157. {
  4158. for (int i = numUsed; --i >= 0;)
  4159. if (! otherArray.contains (this->elements [i]))
  4160. remove (i);
  4161. }
  4162. }
  4163. lock.exit();
  4164. otherArray.unlockArray();
  4165. }
  4166. /** Swaps over two elements in the array.
  4167. This swaps over the elements found at the two indexes passed in.
  4168. If either index is out-of-range, this method will do nothing.
  4169. @param index1 index of one of the elements to swap
  4170. @param index2 index of the other element to swap
  4171. */
  4172. void swap (const int index1,
  4173. const int index2) throw()
  4174. {
  4175. lock.enter();
  4176. if (((unsigned int) index1) < (unsigned int) numUsed
  4177. && ((unsigned int) index2) < (unsigned int) numUsed)
  4178. {
  4179. swapVariables (this->elements [index1],
  4180. this->elements [index2]);
  4181. }
  4182. lock.exit();
  4183. }
  4184. /** Moves one of the values to a different position.
  4185. This will move the value to a specified index, shuffling along
  4186. any intervening elements as required.
  4187. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4188. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4189. @param currentIndex the index of the value to be moved. If this isn't a
  4190. valid index, then nothing will be done
  4191. @param newIndex the index at which you'd like this value to end up. If this
  4192. is less than zero, the value will be moved to the end
  4193. of the array
  4194. */
  4195. void move (const int currentIndex,
  4196. int newIndex) throw()
  4197. {
  4198. if (currentIndex != newIndex)
  4199. {
  4200. lock.enter();
  4201. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4202. {
  4203. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4204. newIndex = numUsed - 1;
  4205. const ElementType value = this->elements [currentIndex];
  4206. if (newIndex > currentIndex)
  4207. {
  4208. memmove (this->elements + currentIndex,
  4209. this->elements + currentIndex + 1,
  4210. (newIndex - currentIndex) * sizeof (ElementType));
  4211. }
  4212. else
  4213. {
  4214. memmove (this->elements + newIndex + 1,
  4215. this->elements + newIndex,
  4216. (currentIndex - newIndex) * sizeof (ElementType));
  4217. }
  4218. this->elements [newIndex] = value;
  4219. }
  4220. lock.exit();
  4221. }
  4222. }
  4223. /** Reduces the amount of storage being used by the array.
  4224. Arrays typically allocate slightly more storage than they need, and after
  4225. removing elements, they may have quite a lot of unused space allocated.
  4226. This method will reduce the amount of allocated storage to a minimum.
  4227. */
  4228. void minimiseStorageOverheads() throw()
  4229. {
  4230. lock.enter();
  4231. if (numUsed == 0)
  4232. {
  4233. this->setAllocatedSize (0);
  4234. }
  4235. else
  4236. {
  4237. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4238. if (newAllocation < this->numAllocated)
  4239. this->setAllocatedSize (newAllocation);
  4240. }
  4241. lock.exit();
  4242. }
  4243. /** Increases the array's internal storage to hold a minimum number of elements.
  4244. Calling this before adding a large known number of elements means that
  4245. the array won't have to keep dynamically resizing itself as the elements
  4246. are added, and it'll therefore be more efficient.
  4247. */
  4248. void ensureStorageAllocated (const int minNumElements) throw()
  4249. {
  4250. this->ensureAllocatedSize (minNumElements);
  4251. }
  4252. /** Sorts the elements in the array.
  4253. This will use a comparator object to sort the elements into order. The object
  4254. passed must have a method of the form:
  4255. @code
  4256. int compareElements (ElementType first, ElementType second);
  4257. @endcode
  4258. ..and this method must return:
  4259. - a value of < 0 if the first comes before the second
  4260. - a value of 0 if the two objects are equivalent
  4261. - a value of > 0 if the second comes before the first
  4262. To improve performance, the compareElements() method can be declared as static or const.
  4263. @param comparator the comparator to use for comparing elements.
  4264. @param retainOrderOfEquivalentItems if this is true, then items
  4265. which the comparator says are equivalent will be
  4266. kept in the order in which they currently appear
  4267. in the array. This is slower to perform, but may
  4268. be important in some cases. If it's false, a faster
  4269. algorithm is used, but equivalent elements may be
  4270. rearranged.
  4271. @see addSorted, indexOfSorted, sortArray
  4272. */
  4273. template <class ElementComparator>
  4274. void sort (ElementComparator& comparator,
  4275. const bool retainOrderOfEquivalentItems = false) const throw()
  4276. {
  4277. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4278. // avoids getting warning messages about the parameter being unused
  4279. lock.enter();
  4280. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4281. lock.exit();
  4282. }
  4283. /** Locks the array's CriticalSection.
  4284. Of course if the type of section used is a DummyCriticalSection, this won't
  4285. have any effect.
  4286. @see unlockArray
  4287. */
  4288. void lockArray() const throw()
  4289. {
  4290. lock.enter();
  4291. }
  4292. /** Unlocks the array's CriticalSection.
  4293. Of course if the type of section used is a DummyCriticalSection, this won't
  4294. have any effect.
  4295. @see lockArray
  4296. */
  4297. void unlockArray() const throw()
  4298. {
  4299. lock.exit();
  4300. }
  4301. juce_UseDebuggingNewOperator
  4302. private:
  4303. int numUsed;
  4304. TypeOfCriticalSectionToUse lock;
  4305. };
  4306. #endif // __JUCE_ARRAY_JUCEHEADER__
  4307. /********* End of inlined file: juce_Array.h *********/
  4308. /**
  4309. A typedef for an Array of void*'s.
  4310. VoidArrays are used in various places throughout the library instead of
  4311. more strongly-typed arrays, to keep code-size low.
  4312. */
  4313. typedef Array <void*> VoidArray;
  4314. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4315. /********* End of inlined file: juce_VoidArray.h *********/
  4316. #ifndef DOXYGEN
  4317. // (used in StringArray::appendNumbersToDuplicates)
  4318. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4319. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4320. #endif
  4321. /**
  4322. A special array for holding a list of strings.
  4323. @see String, StringPairArray
  4324. */
  4325. class JUCE_API StringArray
  4326. {
  4327. public:
  4328. /** Creates an empty string array */
  4329. StringArray() throw();
  4330. /** Creates a copy of another string array */
  4331. StringArray (const StringArray& other) throw();
  4332. /** Creates a copy of an array of string literals.
  4333. @param strings an array of strings to add. Null pointers in the array will be
  4334. treated as empty strings
  4335. @param numberOfStrings how many items there are in the array
  4336. */
  4337. StringArray (const juce_wchar** const strings,
  4338. const int numberOfStrings) throw();
  4339. /** Creates a copy of an array of string literals.
  4340. @param strings an array of strings to add. Null pointers in the array will be
  4341. treated as empty strings
  4342. @param numberOfStrings how many items there are in the array
  4343. */
  4344. StringArray (const char** const strings,
  4345. const int numberOfStrings) throw();
  4346. /** Creates a copy of a null-terminated array of string literals.
  4347. Each item from the array passed-in is added, until it encounters a null pointer,
  4348. at which point it stops.
  4349. */
  4350. StringArray (const juce_wchar** const strings) throw();
  4351. /** Creates a copy of a null-terminated array of string literals.
  4352. Each item from the array passed-in is added, until it encounters a null pointer,
  4353. at which point it stops.
  4354. */
  4355. StringArray (const char** const strings) throw();
  4356. /** Destructor. */
  4357. virtual ~StringArray() throw();
  4358. /** Copies the contents of another string array into this one */
  4359. const StringArray& operator= (const StringArray& other) throw();
  4360. /** Compares two arrays.
  4361. Comparisons are case-sensitive.
  4362. @returns true only if the other array contains exactly the same strings in the same order
  4363. */
  4364. bool operator== (const StringArray& other) const throw();
  4365. /** Compares two arrays.
  4366. Comparisons are case-sensitive.
  4367. @returns false if the other array contains exactly the same strings in the same order
  4368. */
  4369. bool operator!= (const StringArray& other) const throw();
  4370. /** Returns the number of strings in the array */
  4371. inline int size() const throw() { return strings.size(); };
  4372. /** Returns one of the strings from the array.
  4373. If the index is out-of-range, an empty string is returned.
  4374. Obviously the reference returned shouldn't be stored for later use, as the
  4375. string it refers to may disappear when the array changes.
  4376. */
  4377. const String& operator[] (const int index) const throw();
  4378. /** Searches for a string in the array.
  4379. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4380. @returns true if the string is found inside the array
  4381. */
  4382. bool contains (const String& stringToLookFor,
  4383. const bool ignoreCase = false) const throw();
  4384. /** Searches for a string in the array.
  4385. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4386. @param stringToLookFor the string to try to find
  4387. @param ignoreCase whether the comparison should be case-insensitive
  4388. @param startIndex the first index to start searching from
  4389. @returns the index of the first occurrence of the string in this array,
  4390. or -1 if it isn't found.
  4391. */
  4392. int indexOf (const String& stringToLookFor,
  4393. const bool ignoreCase = false,
  4394. int startIndex = 0) const throw();
  4395. /** Appends a string at the end of the array. */
  4396. void add (const String& stringToAdd) throw();
  4397. /** Inserts a string into the array.
  4398. This will insert a string into the array at the given index, moving
  4399. up the other elements to make room for it.
  4400. If the index is less than zero or greater than the size of the array,
  4401. the new string will be added to the end of the array.
  4402. */
  4403. void insert (const int index,
  4404. const String& stringToAdd) throw();
  4405. /** Adds a string to the array as long as it's not already in there.
  4406. The search can optionally be case-insensitive.
  4407. */
  4408. void addIfNotAlreadyThere (const String& stringToAdd,
  4409. const bool ignoreCase = false) throw();
  4410. /** Replaces one of the strings in the array with another one.
  4411. If the index is higher than the array's size, the new string will be
  4412. added to the end of the array; if it's less than zero nothing happens.
  4413. */
  4414. void set (const int index,
  4415. const String& newString) throw();
  4416. /** Appends some strings from another array to the end of this one.
  4417. @param other the array to add
  4418. @param startIndex the first element of the other array to add
  4419. @param numElementsToAdd the maximum number of elements to add (if this is
  4420. less than zero, they are all added)
  4421. */
  4422. void addArray (const StringArray& other,
  4423. int startIndex = 0,
  4424. int numElementsToAdd = -1) throw();
  4425. /** Breaks up a string into tokens and adds them to this array.
  4426. This will tokenise the given string using whitespace characters as the
  4427. token delimiters, and will add these tokens to the end of the array.
  4428. @returns the number of tokens added
  4429. */
  4430. int addTokens (const tchar* const stringToTokenise,
  4431. const bool preserveQuotedStrings) throw();
  4432. /** Breaks up a string into tokens and adds them to this array.
  4433. This will tokenise the given string (using the string passed in to define the
  4434. token delimiters), and will add these tokens to the end of the array.
  4435. @param stringToTokenise the string to tokenise
  4436. @param breakCharacters a string of characters, any of which will be considered
  4437. to be a token delimiter.
  4438. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4439. which are treated as quotes. Any text occurring
  4440. between quotes is not broken up into tokens.
  4441. @returns the number of tokens added
  4442. */
  4443. int addTokens (const tchar* const stringToTokenise,
  4444. const tchar* breakCharacters,
  4445. const tchar* quoteCharacters) throw();
  4446. /** Breaks up a string into lines and adds them to this array.
  4447. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4448. to the array. Line-break characters are omitted from the strings that are added to
  4449. the array.
  4450. */
  4451. int addLines (const tchar* stringToBreakUp) throw();
  4452. /** Removes all elements from the array. */
  4453. void clear() throw();
  4454. /** Removes a string from the array.
  4455. If the index is out-of-range, no action will be taken.
  4456. */
  4457. void remove (const int index) throw();
  4458. /** Finds a string in the array and removes it.
  4459. This will remove the first occurrence of the given string from the array. The
  4460. comparison may be case-insensitive depending on the ignoreCase parameter.
  4461. */
  4462. void removeString (const String& stringToRemove,
  4463. const bool ignoreCase = false) throw();
  4464. /** Removes any duplicated elements from the array.
  4465. If any string appears in the array more than once, only the first occurrence of
  4466. it will be retained.
  4467. @param ignoreCase whether to use a case-insensitive comparison
  4468. */
  4469. void removeDuplicates (const bool ignoreCase) throw();
  4470. /** Removes empty strings from the array.
  4471. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4472. characters will also be removed
  4473. */
  4474. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4475. /** Moves one of the strings to a different position.
  4476. This will move the string to a specified index, shuffling along
  4477. any intervening elements as required.
  4478. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4479. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4480. @param currentIndex the index of the value to be moved. If this isn't a
  4481. valid index, then nothing will be done
  4482. @param newIndex the index at which you'd like this value to end up. If this
  4483. is less than zero, the value will be moved to the end
  4484. of the array
  4485. */
  4486. void move (const int currentIndex, int newIndex) throw();
  4487. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4488. void trim() throw();
  4489. /** Adds numbers to the strings in the array, to make each string unique.
  4490. This will add numbers to the ends of groups of similar strings.
  4491. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4492. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4493. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4494. also has a number appended to it.
  4495. @param preNumberString when adding a number, this string is added before the number
  4496. @param postNumberString this string is appended after any numbers that are added
  4497. */
  4498. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4499. const bool appendNumberToFirstInstance,
  4500. const tchar* const preNumberString = defaultPreNumberString,
  4501. const tchar* const postNumberString = defaultPostNumberString) throw();
  4502. /** Joins the strings in the array together into one string.
  4503. This will join a range of elements from the array into a string, separating
  4504. them with a given string.
  4505. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4506. @param separatorString the string to insert between all the strings
  4507. @param startIndex the first element to join
  4508. @param numberOfElements how many elements to join together. If this is less
  4509. than zero, all available elements will be used.
  4510. */
  4511. const String joinIntoString (const String& separatorString,
  4512. int startIndex = 0,
  4513. int numberOfElements = -1) const throw();
  4514. /** Sorts the array into alphabetical order.
  4515. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4516. */
  4517. void sort (const bool ignoreCase) throw();
  4518. /** Reduces the amount of storage being used by the array.
  4519. Arrays typically allocate slightly more storage than they need, and after
  4520. removing elements, they may have quite a lot of unused space allocated.
  4521. This method will reduce the amount of allocated storage to a minimum.
  4522. */
  4523. void minimiseStorageOverheads() throw();
  4524. juce_UseDebuggingNewOperator
  4525. private:
  4526. VoidArray strings;
  4527. };
  4528. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4529. /********* End of inlined file: juce_StringArray.h *********/
  4530. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4531. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4532. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4533. /**
  4534. A class to hold a resizable block of raw data.
  4535. */
  4536. class JUCE_API MemoryBlock
  4537. {
  4538. public:
  4539. /** Create an uninitialised block with 0 size. */
  4540. MemoryBlock() throw();
  4541. /** Creates a memory block with a given initial size.
  4542. @param initialSize the size of block to create
  4543. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4544. */
  4545. MemoryBlock (const int initialSize,
  4546. const bool initialiseToZero = false) throw();
  4547. /** Creates a copy of another memory block. */
  4548. MemoryBlock (const MemoryBlock& other) throw();
  4549. /** Creates a memory block using a copy of a block of data.
  4550. @param dataToInitialiseFrom some data to copy into this block
  4551. @param sizeInBytes how much space to use
  4552. */
  4553. MemoryBlock (const void* const dataToInitialiseFrom,
  4554. const int sizeInBytes) throw();
  4555. /** Destructor. */
  4556. ~MemoryBlock() throw();
  4557. /** Copies another memory block onto this one.
  4558. This block will be resized and copied to exactly match the other one.
  4559. */
  4560. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4561. /** Compares two memory blocks.
  4562. @returns true only if the two blocks are the same size and have identical contents.
  4563. */
  4564. bool operator== (const MemoryBlock& other) const throw();
  4565. /** Compares two memory blocks.
  4566. @returns true if the two blocks are different sizes or have different contents.
  4567. */
  4568. bool operator!= (const MemoryBlock& other) const throw();
  4569. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4570. Note that the pointer returned will probably become invalid when the
  4571. block is resized.
  4572. */
  4573. template <class DataType>
  4574. operator DataType*() const throw() { return (DataType*) data; }
  4575. /** Returns a void pointer to the data.
  4576. Note that the pointer returned will probably become invalid when the
  4577. block is resized.
  4578. */
  4579. void* getData() const throw() { return data; }
  4580. /** Returns a byte from the memory block.
  4581. This returns a reference, so you can also use it to set a byte.
  4582. */
  4583. char& operator[] (const int offset) const throw() { return data [offset]; }
  4584. /** Returns the block's current allocated size, in bytes. */
  4585. int getSize() const throw() { return size; }
  4586. /** Resizes the memory block.
  4587. This will try to keep as much of the block's current content as it can,
  4588. and can optionally be made to clear any new space that gets allocated at
  4589. the end of the block.
  4590. @param newSize the new desired size for the block
  4591. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4592. whether to clear the new section or just leave it
  4593. uninitialised
  4594. @see ensureSize
  4595. */
  4596. void setSize (const int newSize,
  4597. const bool initialiseNewSpaceToZero = false) throw();
  4598. /** Increases the block's size only if it's smaller than a given size.
  4599. @param minimumSize if the block is already bigger than this size, no action
  4600. will be taken; otherwise it will be increased to this size
  4601. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4602. whether to clear the new section or just leave it
  4603. uninitialised
  4604. @see setSize
  4605. */
  4606. void ensureSize (const int minimumSize,
  4607. const bool initialiseNewSpaceToZero = false) throw();
  4608. /** Fills the entire memory block with a repeated byte value.
  4609. This is handy for clearing a block of memory to zero.
  4610. */
  4611. void fillWith (const uint8 valueToUse) throw();
  4612. /** Adds another block of data to the end of this one.
  4613. This block's size will be increased accordingly.
  4614. */
  4615. void append (const void* const data,
  4616. const int numBytes) throw();
  4617. /** Copies data into this MemoryBlock from a memory address.
  4618. @param srcData the memory location of the data to copy into this block
  4619. @param destinationOffset the offset in this block at which the data being copied should begin
  4620. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4621. it will be clipped so not to do anything nasty)
  4622. */
  4623. void copyFrom (const void* srcData,
  4624. int destinationOffset,
  4625. int numBytes) throw();
  4626. /** Copies data from this MemoryBlock to a memory address.
  4627. @param destData the memory location to write to
  4628. @param sourceOffset the offset within this block from which the copied data will be read
  4629. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4630. zeros will be used for that portion of the data)
  4631. */
  4632. void copyTo (void* destData,
  4633. int sourceOffset,
  4634. int numBytes) const throw();
  4635. /** Chops out a section of the block.
  4636. This will remove a section of the memory block and close the gap around it,
  4637. shifting any subsequent data downwards and reducing the size of the block.
  4638. If the range specified goes beyond the size of the block, it will be clipped.
  4639. */
  4640. void removeSection (int startByte, int numBytesToRemove) throw();
  4641. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4642. characters in the system's default encoding. */
  4643. const String toString() const throw();
  4644. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4645. The block will be resized to the number of valid bytes read from the string.
  4646. Non-hex characters in the string will be ignored.
  4647. @see String::toHexString()
  4648. */
  4649. void loadFromHexString (const String& sourceHexString) throw();
  4650. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4651. void setBitRange (int bitRangeStart,
  4652. int numBits,
  4653. int binaryNumberToApply) throw();
  4654. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4655. int getBitRange (int bitRangeStart,
  4656. int numBitsToRead) const throw();
  4657. /** Returns a string of characters that represent the binary contents of this block.
  4658. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4659. of simple non-extended characters, e.g. for storage in XML.
  4660. @see fromBase64Encoding
  4661. */
  4662. const String toBase64Encoding() const throw();
  4663. /** Takes a string of encoded characters and turns it into binary data.
  4664. The string passed in must have been created by to64BitEncoding(), and this
  4665. block will be resized to recreate the original data block.
  4666. @see toBase64Encoding
  4667. */
  4668. bool fromBase64Encoding (const String& encodedString) throw();
  4669. juce_UseDebuggingNewOperator
  4670. private:
  4671. char* data;
  4672. int size;
  4673. };
  4674. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4675. /********* End of inlined file: juce_MemoryBlock.h *********/
  4676. class FileInputStream;
  4677. class FileOutputStream;
  4678. /**
  4679. Represents a local file or directory.
  4680. This class encapsulates the absolute pathname of a file or directory, and
  4681. has methods for finding out about the file and changing its properties.
  4682. To read or write to the file, there are methods for returning an input or
  4683. output stream.
  4684. @see FileInputStream, FileOutputStream
  4685. */
  4686. class JUCE_API File
  4687. {
  4688. public:
  4689. /** Creates an (invalid) file object.
  4690. The file is initially set to an empty path, so getFullPath() will return
  4691. an empty string, and comparing the file to File::nonexistent will return
  4692. true.
  4693. You can use its operator= method to point it at a proper file.
  4694. */
  4695. File() throw() {}
  4696. /** Creates a file from an absolute path.
  4697. If the path supplied is a relative path, it is taken to be relative
  4698. to the current working directory (see File::getCurrentWorkingDirectory()),
  4699. but this isn't a recommended way of creating a file, because you
  4700. never know what the CWD is going to be.
  4701. On the Mac/Linux, the path can include "~" notation for referring to
  4702. user home directories.
  4703. */
  4704. File (const String& path) throw();
  4705. /** Creates a copy of another file object. */
  4706. File (const File& other) throw();
  4707. /** Destructor. */
  4708. ~File() throw() {}
  4709. /** Sets the file based on an absolute pathname.
  4710. If the path supplied is a relative path, it is taken to be relative
  4711. to the current working directory (see File::getCurrentWorkingDirectory()),
  4712. but this isn't a recommended way of creating a file, because you
  4713. never know what the CWD is going to be.
  4714. On the Mac/Linux, the path can include "~" notation for referring to
  4715. user home directories.
  4716. */
  4717. const File& operator= (const String& newFilePath) throw();
  4718. /** Copies from another file object. */
  4719. const File& operator= (const File& otherFile) throw();
  4720. /** This static constant is used for referring to an 'invalid' file. */
  4721. static const File nonexistent;
  4722. /** Checks whether the file actually exists.
  4723. @returns true if the file exists, either as a file or a directory.
  4724. @see existsAsFile, isDirectory
  4725. */
  4726. bool exists() const throw();
  4727. /** Checks whether the file exists and is a file rather than a directory.
  4728. @returns true only if this is a real file, false if it's a directory
  4729. or doesn't exist
  4730. @see exists, isDirectory
  4731. */
  4732. bool existsAsFile() const throw();
  4733. /** Checks whether the file is a directory that exists.
  4734. @returns true only if the file is a directory which actually exists, so
  4735. false if it's a file or doesn't exist at all
  4736. @see exists, existsAsFile
  4737. */
  4738. bool isDirectory() const throw();
  4739. /** Returns the size of the file in bytes.
  4740. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4741. */
  4742. int64 getSize() const throw();
  4743. /** Utility function to convert a file size in bytes to a neat string description.
  4744. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4745. 2000000 would produce "2 MB", etc.
  4746. */
  4747. static const String descriptionOfSizeInBytes (const int64 bytes);
  4748. /** Returns the complete, absolute path of this file.
  4749. This includes the filename and all its parent folders. On Windows it'll
  4750. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4751. path starting from the root folder.
  4752. If you just want the file's name, you should use getFileName() or
  4753. getFileNameWithoutExtension().
  4754. @see getFileName, getRelativePathFrom
  4755. */
  4756. const String& getFullPathName() const throw() { return fullPath; }
  4757. /** Returns the last section of the pathname.
  4758. Returns just the final part of the path - e.g. if the whole path
  4759. is "/moose/fish/foo.txt" this will return "foo.txt".
  4760. For a directory, it returns the final part of the path - e.g. for the
  4761. directory "/moose/fish" it'll return "fish".
  4762. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4763. "/moose/.fish", it'll return ".fish"
  4764. @see getFullPathName, getFileNameWithoutExtension
  4765. */
  4766. const String getFileName() const throw();
  4767. /** Creates a relative path that refers to a file relatively to a given directory.
  4768. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4769. would return "../../foo.txt".
  4770. If it's not possible to navigate from one file to the other, an absolute
  4771. path is returned. If the paths are invalid, an empty string may also be
  4772. returned.
  4773. @param directoryToBeRelativeTo the directory which the resultant string will
  4774. be relative to. If this is actually a file rather than
  4775. a directory, its parent directory will be used instead.
  4776. If it doesn't exist, it's assumed to be a directory.
  4777. @see getChildFile, isAbsolutePath
  4778. */
  4779. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4780. /** Returns the file's extension.
  4781. Returns the file extension of this file, also including the dot.
  4782. e.g. "/moose/fish/foo.txt" would return ".txt"
  4783. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4784. */
  4785. const String getFileExtension() const throw();
  4786. /** Checks whether the file has a given extension.
  4787. @param extensionToTest the extension to look for - it doesn't matter whether or
  4788. not this string has a dot at the start, so ".wav" and "wav"
  4789. will have the same effect. The comparison used is
  4790. case-insensitve.
  4791. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4792. */
  4793. bool hasFileExtension (const String& extensionToTest) const throw();
  4794. /** Returns a version of this file with a different file extension.
  4795. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4796. @param newExtension the new extension, either with or without a dot at the start (this
  4797. doesn't make any difference). To get remove a file's extension altogether,
  4798. pass an empty string into this function.
  4799. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4800. */
  4801. const File withFileExtension (const String& newExtension) const throw();
  4802. /** Returns the last part of the filename, without its file extension.
  4803. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4804. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4805. */
  4806. const String getFileNameWithoutExtension() const throw();
  4807. /** Returns a 32-bit hash-code that identifies this file.
  4808. This is based on the filename. Obviously it's possible, although unlikely, that
  4809. two files will have the same hash-code.
  4810. */
  4811. int hashCode() const throw();
  4812. /** Returns a 64-bit hash-code that identifies this file.
  4813. This is based on the filename. Obviously it's possible, although unlikely, that
  4814. two files will have the same hash-code.
  4815. */
  4816. int64 hashCode64() const throw();
  4817. /** Returns a file based on a relative path.
  4818. This will find a child file or directory of the current object.
  4819. e.g.
  4820. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4821. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4822. If the string is actually an absolute path, it will be treated as such, e.g.
  4823. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4824. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4825. */
  4826. const File getChildFile (String relativePath) const throw();
  4827. /** Returns a file which is in the same directory as this one.
  4828. This is equivalent to getParentDirectory().getChildFile (name).
  4829. @see getChildFile, getParentDirectory
  4830. */
  4831. const File getSiblingFile (const String& siblingFileName) const throw();
  4832. /** Returns the directory that contains this file or directory.
  4833. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4834. */
  4835. const File getParentDirectory() const throw();
  4836. /** Checks whether a file is somewhere inside a directory.
  4837. Returns true if this file is somewhere inside a subdirectory of the directory
  4838. that is passed in. Neither file actually has to exist, because the function
  4839. just checks the paths for similarities.
  4840. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4841. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4842. */
  4843. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4844. /** Chooses a filename relative to this one that doesn't already exist.
  4845. If this file is a directory, this will return a child file of this
  4846. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4847. it finds one that isn't already there.
  4848. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4849. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4850. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4851. @param prefix the string to use for the filename before the number
  4852. @param suffix the string to add to the filename after the number
  4853. @param putNumbersInBrackets if true, this will create filenames in the
  4854. format "prefix(number)suffix", if false, it will leave the
  4855. brackets out.
  4856. */
  4857. const File getNonexistentChildFile (const String& prefix,
  4858. const String& suffix,
  4859. bool putNumbersInBrackets = true) const throw();
  4860. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4861. If this file doesn't exist, this will just return itself, otherwise it
  4862. will return an appropriate sibling that doesn't exist, e.g. if a file
  4863. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4864. @param putNumbersInBrackets whether to add brackets around the numbers that
  4865. get appended to the new filename.
  4866. */
  4867. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4868. /** Compares the pathnames for two files. */
  4869. bool operator== (const File& otherFile) const throw();
  4870. /** Compares the pathnames for two files. */
  4871. bool operator!= (const File& otherFile) const throw();
  4872. /** Checks whether a file can be created or written to.
  4873. @returns true if it's possible to create and write to this file. If the file
  4874. doesn't already exist, this will check its parent directory to
  4875. see if writing is allowed.
  4876. @see setReadOnly
  4877. */
  4878. bool hasWriteAccess() const throw();
  4879. /** Changes the write-permission of a file or directory.
  4880. @param shouldBeReadOnly whether to add or remove write-permission
  4881. @param applyRecursively if the file is a directory and this is true, it will
  4882. recurse through all the subfolders changing the permissions
  4883. of all files
  4884. @returns true if it manages to change the file's permissions.
  4885. @see hasWriteAccess
  4886. */
  4887. bool setReadOnly (const bool shouldBeReadOnly,
  4888. const bool applyRecursively = false) const throw();
  4889. /** Returns true if this file is a hidden or system file.
  4890. The criteria for deciding whether a file is hidden are platform-dependent.
  4891. */
  4892. bool isHidden() const throw();
  4893. /** Returns the last modification time of this file.
  4894. @returns the time, or an invalid time if the file doesn't exist.
  4895. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4896. */
  4897. const Time getLastModificationTime() const throw();
  4898. /** Returns the last time this file was accessed.
  4899. @returns the time, or an invalid time if the file doesn't exist.
  4900. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4901. */
  4902. const Time getLastAccessTime() const throw();
  4903. /** Returns the time that this file was created.
  4904. @returns the time, or an invalid time if the file doesn't exist.
  4905. @see getLastModificationTime, getLastAccessTime
  4906. */
  4907. const Time getCreationTime() const throw();
  4908. /** Changes the modification time for this file.
  4909. @param newTime the time to apply to the file
  4910. @returns true if it manages to change the file's time.
  4911. @see getLastModificationTime, setLastAccessTime, setCreationTime
  4912. */
  4913. bool setLastModificationTime (const Time& newTime) const throw();
  4914. /** Changes the last-access time for this file.
  4915. @param newTime the time to apply to the file
  4916. @returns true if it manages to change the file's time.
  4917. @see getLastAccessTime, setLastModificationTime, setCreationTime
  4918. */
  4919. bool setLastAccessTime (const Time& newTime) const throw();
  4920. /** Changes the creation date for this file.
  4921. @param newTime the time to apply to the file
  4922. @returns true if it manages to change the file's time.
  4923. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4924. */
  4925. bool setCreationTime (const Time& newTime) const throw();
  4926. /** Creates an empty file if it doesn't already exist.
  4927. If the file that this object refers to doesn't exist, this will create a file
  4928. of zero size.
  4929. If it already exists or is a directory, this method will do nothing.
  4930. @returns true if the file has been created (or if it already existed).
  4931. @see createDirectory
  4932. */
  4933. bool create() const throw();
  4934. /** Creates a new directory for this filename.
  4935. This will try to create the file as a directory, and fill also create
  4936. any parent directories it needs in order to complete the operation.
  4937. @returns true if the directory has been created successfully, (or if it
  4938. already existed beforehand).
  4939. @see create
  4940. */
  4941. bool createDirectory() const throw();
  4942. /** Deletes a file.
  4943. If this file is actually a directory, it may not be deleted correctly if it
  4944. contains files. See deleteRecursively() as a better way of deleting directories.
  4945. @returns true if the file has been successfully deleted (or if it didn't exist to
  4946. begin with).
  4947. @see deleteRecursively
  4948. */
  4949. bool deleteFile() const throw();
  4950. /** Deletes a file or directory and all its subdirectories.
  4951. If this file is a directory, this will try to delete it and all its subfolders. If
  4952. it's just a file, it will just try to delete the file.
  4953. @returns true if the file and all its subfolders have been successfully deleted
  4954. (or if it didn't exist to begin with).
  4955. @see deleteFile
  4956. */
  4957. bool deleteRecursively() const throw();
  4958. /** Moves or renames a file.
  4959. Tries to move a file to a different location.
  4960. If the target file already exists, this will attempt to delete it first, and
  4961. will fail if this can't be done.
  4962. Note that the destination file isn't the directory to put it in, it's the actual
  4963. filename that you want the new file to have.
  4964. @returns true if the operation succeeds
  4965. */
  4966. bool moveFileTo (const File& targetLocation) const throw();
  4967. /** Copies a file.
  4968. Tries to copy a file to a different location.
  4969. If the target file already exists, this will attempt to delete it first, and
  4970. will fail if this can't be done.
  4971. @returns true if the operation succeeds
  4972. */
  4973. bool copyFileTo (const File& targetLocation) const throw();
  4974. /** Copies a directory.
  4975. Tries to copy an entire directory, recursively.
  4976. If this file isn't a directory or if any target files can't be created, this
  4977. will return false.
  4978. @param newDirectory the directory that this one should be copied to. Note that this
  4979. is the name of the actual directory to create, not the directory
  4980. into which the new one should be placed, so there must be enough
  4981. write privileges to create it if it doesn't exist. Any files inside
  4982. it will be overwritten by similarly named ones that are copied.
  4983. */
  4984. bool copyDirectoryTo (const File& newDirectory) const throw();
  4985. /** Used in file searching, to specify whether to return files, directories, or both.
  4986. */
  4987. enum TypesOfFileToFind
  4988. {
  4989. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  4990. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  4991. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  4992. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  4993. };
  4994. /** Searches inside a directory for files matching a wildcard pattern.
  4995. Assuming that this file is a directory, this method will search it
  4996. for either files or subdirectories whose names match a filename pattern.
  4997. @param results an array to which File objects will be added for the
  4998. files that the search comes up with
  4999. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5000. return files, directories, or both. If the ignoreHiddenFiles flag
  5001. is also added to this value, hidden files won't be returned
  5002. @param searchRecursively if true, all subdirectories will be recursed into to do
  5003. an exhaustive search
  5004. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5005. @returns the number of results that have been found
  5006. @see getNumberOfChildFiles, DirectoryIterator
  5007. */
  5008. int findChildFiles (OwnedArray<File>& results,
  5009. const int whatToLookFor,
  5010. const bool searchRecursively,
  5011. const String& wildCardPattern = JUCE_T("*")) const throw();
  5012. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5013. Assuming that this file is a directory, this method will search it
  5014. for either files or subdirectories whose names match a filename pattern,
  5015. and will return the number of matches found.
  5016. This isn't a recursive call, and will only search this directory, not
  5017. its children.
  5018. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5019. count files, directories, or both. If the ignoreHiddenFiles flag
  5020. is also added to this value, hidden files won't be counted
  5021. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5022. @returns the number of matches found
  5023. @see findChildFiles, DirectoryIterator
  5024. */
  5025. int getNumberOfChildFiles (const int whatToLookFor,
  5026. const String& wildCardPattern = JUCE_T("*")) const throw();
  5027. /** Creates a stream to read from this file.
  5028. @returns a stream that will read from this file (initially positioned at the
  5029. start of the file), or 0 if the file can't be opened for some reason
  5030. @see createOutputStream, loadFileAsData
  5031. */
  5032. FileInputStream* createInputStream() const throw();
  5033. /** Creates a stream to write to this file.
  5034. If the file exists, the stream that is returned will be positioned ready for
  5035. writing at the end of the file, so you might want to use deleteFile() first
  5036. to write to an empty file.
  5037. @returns a stream that will write to this file (initially positioned at the
  5038. end of the file), or 0 if the file can't be opened for some reason
  5039. @see createInputStream, printf, appendData, appendText
  5040. */
  5041. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5042. /** Loads a file's contents into memory as a block of binary data.
  5043. Of course, trying to load a very large file into memory will blow up, so
  5044. it's better to check first.
  5045. @param result the data block to which the file's contents should be appended - note
  5046. that if the memory block might already contain some data, you
  5047. might want to clear it first
  5048. @returns true if the file could all be read into memory
  5049. */
  5050. bool loadFileAsData (MemoryBlock& result) const throw();
  5051. /** Reads a file into memory as a string.
  5052. Attempts to load the entire file as a zero-terminated string.
  5053. This makes use of InputStream::readEntireStreamAsString, which should
  5054. automatically cope with unicode/acsii file formats.
  5055. */
  5056. const String loadFileAsString() const throw();
  5057. /** Writes text to the end of the file.
  5058. This will try to do a printf to the file.
  5059. @returns false if it can't write to the file for some reason
  5060. */
  5061. bool printf (const tchar* format, ...) const throw();
  5062. /** Appends a block of binary data to the end of the file.
  5063. This will try to write the given buffer to the end of the file.
  5064. @returns false if it can't write to the file for some reason
  5065. */
  5066. bool appendData (const void* const dataToAppend,
  5067. const int numberOfBytes) const throw();
  5068. /** Replaces this file's contents with a given block of data.
  5069. This will delete the file and replace it with the given data.
  5070. A nice feature of this method is that it's safe - instead of deleting
  5071. the file first and then re-writing it, it creates a new temporary file,
  5072. writes the data to that, and then moves the new file to replace the existing
  5073. file. This means that if the power gets pulled out or something crashes,
  5074. you're a lot less likely to end up with an empty file..
  5075. Returns true if the operation succeeds, or false if it fails.
  5076. @see appendText
  5077. */
  5078. bool replaceWithData (const void* const dataToWrite,
  5079. const int numberOfBytes) const throw();
  5080. /** Appends a string to the end of the file.
  5081. This will try to append a text string to the file, as either 16-bit unicode
  5082. or 8-bit characters in the default system encoding.
  5083. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5084. the endianness of the file.
  5085. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5086. @see replaceWithText
  5087. */
  5088. bool appendText (const String& textToAppend,
  5089. const bool asUnicode = false,
  5090. const bool writeUnicodeHeaderBytes = false) const throw();
  5091. /** Replaces this file's contents with a given text string.
  5092. This will delete the file and replace it with the given text.
  5093. A nice feature of this method is that it's safe - instead of deleting
  5094. the file first and then re-writing it, it creates a new temporary file,
  5095. writes the text to that, and then moves the new file to replace the existing
  5096. file. This means that if the power gets pulled out or something crashes,
  5097. you're a lot less likely to end up with an empty file..
  5098. For an explanation of the parameters here, see the appendText() method.
  5099. Returns true if the operation succeeds, or false if it fails.
  5100. @see appendText
  5101. */
  5102. bool replaceWithText (const String& textToWrite,
  5103. const bool asUnicode = false,
  5104. const bool writeUnicodeHeaderBytes = false) const throw();
  5105. /** Creates a set of files to represent each file root.
  5106. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5107. to which ones are available. On the Mac/Linux, this will probably
  5108. just add a single entry for "/".
  5109. */
  5110. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5111. /** Finds the name of the drive on which this file lives.
  5112. @returns the volume label of the drive, or an empty string if this isn't possible
  5113. */
  5114. const String getVolumeLabel() const throw();
  5115. /** Returns the serial number of the volume on which this file lives.
  5116. @returns the serial number, or zero if there's a problem doing this
  5117. */
  5118. int getVolumeSerialNumber() const throw();
  5119. /** Returns the number of bytes free on the drive that this file lives on.
  5120. @returns the number of bytes free, or 0 if there's a problem finding this out
  5121. */
  5122. int64 getBytesFreeOnVolume() const throw();
  5123. /** Returns true if this file is on a CD or DVD drive. */
  5124. bool isOnCDRomDrive() const throw();
  5125. /** Returns true if this file is on a hard disk.
  5126. This will fail if it's a network drive, but will still be true for
  5127. removable hard-disks.
  5128. */
  5129. bool isOnHardDisk() const throw();
  5130. /** Returns true if this file is on a removable disk drive.
  5131. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5132. */
  5133. bool isOnRemovableDrive() const throw();
  5134. /** Launches the file as a process.
  5135. - if the file is executable, this will run it.
  5136. - if it's a document of some kind, it will launch the document with its
  5137. default viewer application.
  5138. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5139. */
  5140. bool startAsProcess (const String& parameters = String::empty) const throw();
  5141. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5142. */
  5143. enum SpecialLocationType
  5144. {
  5145. /** The user's home folder. This is the same as using File ("~"). */
  5146. userHomeDirectory,
  5147. /** The user's default documents folder. On Windows, this might be the user's
  5148. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5149. doesn't tend to have one of these, so it might just return their home folder.
  5150. */
  5151. userDocumentsDirectory,
  5152. /** The folder that contains the user's desktop objects. */
  5153. userDesktopDirectory,
  5154. /** The folder in which applications store their persistent user-specific settings.
  5155. On Windows, this might be "\Documents and Settings\username\Application Data".
  5156. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5157. always create your own sub-folder to put them in, to avoid making a mess.
  5158. */
  5159. userApplicationDataDirectory,
  5160. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5161. of the computer, rather than just the current user.
  5162. On the Mac it'll be "/Library", on Windows, it could be something like
  5163. "\Documents and Settings\All Users\Application Data".
  5164. Depending on the setup, this folder may be read-only.
  5165. */
  5166. commonApplicationDataDirectory,
  5167. /** The folder that should be used for temporary files.
  5168. Always delete them when you're finished, to keep the user's computer tidy!
  5169. */
  5170. tempDirectory,
  5171. /** Returns this application's executable file.
  5172. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5173. host app.
  5174. On the mac this will return the unix binary, not the package folder - see
  5175. currentApplicationFile for that.
  5176. */
  5177. currentExecutableFile,
  5178. /** Returns this application's location.
  5179. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5180. host app.
  5181. On the mac this will return the package folder (if it's in one), not the unix binary
  5182. that's inside it - compare with currentExecutableFile.
  5183. */
  5184. currentApplicationFile,
  5185. /** The directory in which applications normally get installed.
  5186. So on windows, this would be something like "c:\program files", on the
  5187. Mac "/Applications", or "/usr" on linux.
  5188. */
  5189. globalApplicationsDirectory,
  5190. /** The most likely place where a user might store their music files.
  5191. */
  5192. userMusicDirectory,
  5193. /** The most likely place where a user might store their movie files.
  5194. */
  5195. userMoviesDirectory,
  5196. };
  5197. /** Finds the location of a special type of file or directory, such as a home folder or
  5198. documents folder.
  5199. @see SpecialLocationType
  5200. */
  5201. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5202. /** Returns a temporary file in the system's temp directory.
  5203. This will try to return the name of a non-existent temp file.
  5204. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5205. */
  5206. static const File createTempFile (const String& fileNameEnding) throw();
  5207. /** Returns the current working directory.
  5208. @see setAsCurrentWorkingDirectory
  5209. */
  5210. static const File getCurrentWorkingDirectory() throw();
  5211. /** Sets the current working directory to be this file.
  5212. For this to work the file must point to a valid directory.
  5213. @returns true if the current directory has been changed.
  5214. @see getCurrentWorkingDirectory
  5215. */
  5216. bool setAsCurrentWorkingDirectory() const throw();
  5217. /** The system-specific file separator character.
  5218. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5219. */
  5220. static const tchar separator;
  5221. /** The system-specific file separator character, as a string.
  5222. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5223. */
  5224. static const tchar* separatorString;
  5225. /** Removes illegal characters from a filename.
  5226. This will return a copy of the given string after removing characters
  5227. that are not allowed in a legal filename, and possibly shortening the
  5228. string if it's too long.
  5229. Because this will remove slashes, don't use it on an absolute pathname.
  5230. @see createLegalPathName
  5231. */
  5232. static const String createLegalFileName (const String& fileNameToFix) throw();
  5233. /** Removes illegal characters from a pathname.
  5234. Similar to createLegalFileName(), but this won't remove slashes, so can
  5235. be used on a complete pathname.
  5236. @see createLegalFileName
  5237. */
  5238. static const String createLegalPathName (const String& pathNameToFix) throw();
  5239. /** Indicates whether filenames are case-sensitive on the current operating system.
  5240. */
  5241. static bool areFileNamesCaseSensitive();
  5242. /** Returns true if the string seems to be a fully-specified absolute path.
  5243. */
  5244. static bool isAbsolutePath (const String& path) throw();
  5245. juce_UseDebuggingNewOperator
  5246. private:
  5247. String fullPath;
  5248. // internal way of contructing a file without checking the path
  5249. friend class DirectoryIterator;
  5250. File (const String&, int) throw();
  5251. const String getPathUpToLastSlash() const throw();
  5252. };
  5253. #endif // __JUCE_FILE_JUCEHEADER__
  5254. /********* End of inlined file: juce_File.h *********/
  5255. /**
  5256. A simple implemenation of a Logger that writes to a file.
  5257. @see Logger
  5258. */
  5259. class JUCE_API FileLogger : public Logger
  5260. {
  5261. public:
  5262. /** Creates a FileLogger for a given file.
  5263. @param fileToWriteTo the file that to use - new messages will be appended
  5264. to the file. If the file doesn't exist, it will be created,
  5265. along with any parent directories that are needed.
  5266. @param welcomeMessage when opened, the logger will write a header to the log, along
  5267. with the current date and time, and this welcome message
  5268. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5269. but is larger than this number of bytes, then the start of the
  5270. file will be truncated to keep the size down. This prevents a log
  5271. file getting ridiculously large over time. The file will be truncated
  5272. at a new-line boundary. If this value is less than zero, no size limit
  5273. will be imposed; if it's zero, the file will always be deleted. Note that
  5274. the size is only checked once when this object is created - any logging
  5275. that is done later will be appended without any checking
  5276. */
  5277. FileLogger (const File& fileToWriteTo,
  5278. const String& welcomeMessage,
  5279. const int maxInitialFileSizeBytes = 128 * 1024);
  5280. /** Destructor. */
  5281. ~FileLogger();
  5282. void logMessage (const String& message);
  5283. /** Helper function to create a log file in the correct place for this platform.
  5284. On Windows this will return a logger with a path such as:
  5285. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5286. On the Mac it'll create something like:
  5287. ~/Library/Logs/[logFileName]
  5288. The method might return 0 if the file can't be created for some reason.
  5289. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5290. it's best to use the something like the name of your application here.
  5291. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5292. call it "log.txt" because if it goes in a directory with logs
  5293. from other applications (as it will do on the Mac) then no-one
  5294. will know which one is yours!
  5295. @param welcomeMessage a message that will be written to the log when it's opened.
  5296. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5297. */
  5298. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5299. const String& logFileName,
  5300. const String& welcomeMessage,
  5301. const int maxInitialFileSizeBytes = 128 * 1024);
  5302. juce_UseDebuggingNewOperator
  5303. private:
  5304. File logFile;
  5305. CriticalSection logLock;
  5306. FileOutputStream* logStream;
  5307. void trimFileSize (int maxFileSizeBytes) const;
  5308. FileLogger (const FileLogger&);
  5309. const FileLogger& operator= (const FileLogger&);
  5310. };
  5311. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5312. /********* End of inlined file: juce_FileLogger.h *********/
  5313. #endif
  5314. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5315. /********* Start of inlined file: juce_Initialisation.h *********/
  5316. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5317. #define __JUCE_INITIALISATION_JUCEHEADER__
  5318. /** Initialises Juce's GUI classes.
  5319. If you're embedding Juce into an application that uses its own event-loop rather
  5320. than using the START_JUCE_APPLICATION macro, call this function before making any
  5321. Juce calls, to make sure things are initialised correctly.
  5322. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5323. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5324. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5325. */
  5326. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5327. /** Clears up any static data being used by Juce's GUI classes.
  5328. If you're embedding Juce into an application that uses its own event-loop rather
  5329. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5330. code to clean up any juce objects that might be lying around.
  5331. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5332. */
  5333. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5334. /** Initialises the core parts of Juce.
  5335. If you're embedding Juce into either a command-line program, call this function
  5336. at the start of your main() function to make sure that Juce is initialised correctly.
  5337. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5338. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5339. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5340. */
  5341. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5342. /** Clears up any static data being used by Juce's non-gui core classes.
  5343. If you're embedding Juce into either a command-line program, call this function
  5344. at the end of your main() function if you want to make sure any Juce objects are
  5345. cleaned up correctly.
  5346. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5347. */
  5348. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5349. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5350. /********* End of inlined file: juce_Initialisation.h *********/
  5351. #endif
  5352. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5353. #endif
  5354. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  5355. #endif
  5356. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5357. #endif
  5358. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5359. #endif
  5360. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5361. /********* Start of inlined file: juce_Random.h *********/
  5362. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5363. #define __JUCE_RANDOM_JUCEHEADER__
  5364. /********* Start of inlined file: juce_BitArray.h *********/
  5365. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5366. #define __JUCE_BITARRAY_JUCEHEADER__
  5367. class MemoryBlock;
  5368. /**
  5369. An array of on/off bits, also usable to store large binary integers.
  5370. A BitArray acts like an arbitrarily large integer whose bits can be set or
  5371. cleared, and some basic mathematical operations can be done on the number as
  5372. a whole.
  5373. */
  5374. class JUCE_API BitArray
  5375. {
  5376. public:
  5377. /** Creates an empty BitArray */
  5378. BitArray() throw();
  5379. /** Creates a BitArray containing an integer value in its low bits.
  5380. The low 32 bits of the array are initialised with this value.
  5381. */
  5382. BitArray (const unsigned int value) throw();
  5383. /** Creates a BitArray containing an integer value in its low bits.
  5384. The low 32 bits of the array are initialised with the absolute value
  5385. passed in, and its sign is set to reflect the sign of the number.
  5386. */
  5387. BitArray (const int value) throw();
  5388. /** Creates a BitArray containing an integer value in its low bits.
  5389. The low 64 bits of the array are initialised with the absolute value
  5390. passed in, and its sign is set to reflect the sign of the number.
  5391. */
  5392. BitArray (int64 value) throw();
  5393. /** Creates a copy of another BitArray. */
  5394. BitArray (const BitArray& other) throw();
  5395. /** Destructor. */
  5396. ~BitArray() throw();
  5397. /** Copies another BitArray onto this one. */
  5398. const BitArray& operator= (const BitArray& other) throw();
  5399. /** Two arrays are the same if the same bits are set. */
  5400. bool operator== (const BitArray& other) const throw();
  5401. /** Two arrays are the same if the same bits are set. */
  5402. bool operator!= (const BitArray& other) const throw();
  5403. /** Clears all bits in the BitArray to 0. */
  5404. void clear() throw();
  5405. /** Clears a particular bit in the array. */
  5406. void clearBit (const int bitNumber) throw();
  5407. /** Sets a specified bit to 1.
  5408. If the bit number is high, this will grow the array to accomodate it.
  5409. */
  5410. void setBit (const int bitNumber) throw();
  5411. /** Sets or clears a specified bit. */
  5412. void setBit (const int bitNumber,
  5413. const bool shouldBeSet) throw();
  5414. /** Sets a range of bits to be either on or off.
  5415. @param startBit the first bit to change
  5416. @param numBits the number of bits to change
  5417. @param shouldBeSet whether to turn these bits on or off
  5418. */
  5419. void setRange (int startBit,
  5420. int numBits,
  5421. const bool shouldBeSet) throw();
  5422. /** Inserts a bit an a given position, shifting up any bits above it. */
  5423. void insertBit (const int bitNumber,
  5424. const bool shouldBeSet) throw();
  5425. /** Returns the value of a specified bit in the array.
  5426. If the index is out-of-range, the result will be false.
  5427. */
  5428. bool operator[] (const int bit) const throw();
  5429. /** Returns true if no bits are set. */
  5430. bool isEmpty() const throw();
  5431. /** Returns a range of bits in the array as an integer value.
  5432. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  5433. Asking for more than 32 bits isn't allowed (obviously).
  5434. */
  5435. int getBitRangeAsInt (int startBit, int numBits) const throw();
  5436. /** Sets a range of bits in the array based on an integer value.
  5437. Copies the given integer into the array, starting at startBit,
  5438. and only using up to numBits of the available bits.
  5439. */
  5440. void setBitRangeAsInt (int startBit, int numBits,
  5441. unsigned int valueToSet) throw();
  5442. /** Performs a bitwise OR with another BitArray.
  5443. The result ends up in this array.
  5444. */
  5445. void orWith (const BitArray& other) throw();
  5446. /** Performs a bitwise AND with another BitArray.
  5447. The result ends up in this array.
  5448. */
  5449. void andWith (const BitArray& other) throw();
  5450. /** Performs a bitwise XOR with another BitArray.
  5451. The result ends up in this array.
  5452. */
  5453. void xorWith (const BitArray& other) throw();
  5454. /** Adds another BitArray's value to this one.
  5455. Treating the two arrays as large positive integers, this
  5456. adds them up and puts the result in this array.
  5457. */
  5458. void add (const BitArray& other) throw();
  5459. /** Subtracts another BitArray's value from this one.
  5460. Treating the two arrays as large positive integers, this
  5461. subtracts them and puts the result in this array.
  5462. Note that if the result should be negative, this won't be
  5463. handled correctly.
  5464. */
  5465. void subtract (const BitArray& other) throw();
  5466. /** Multiplies another BitArray's value with this one.
  5467. Treating the two arrays as large positive integers, this
  5468. multiplies them and puts the result in this array.
  5469. */
  5470. void multiplyBy (const BitArray& other) throw();
  5471. /** Divides another BitArray's value into this one and also produces a remainder.
  5472. Treating the two arrays as large positive integers, this
  5473. divides this value by the other, leaving the quotient in this
  5474. array, and the remainder is copied into the other BitArray passed in.
  5475. */
  5476. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  5477. /** Returns the largest value that will divide both this value and the one
  5478. passed-in.
  5479. */
  5480. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  5481. /** Performs a modulo operation on this value.
  5482. The result is stored in this value.
  5483. */
  5484. void modulo (const BitArray& divisor) throw();
  5485. /** Performs a combined exponent and modulo operation.
  5486. This BitArray's value becomes (this ^ exponent) % modulus.
  5487. */
  5488. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  5489. /** Performs an inverse modulo on the value.
  5490. i.e. the result is (this ^ -1) mod (modulus).
  5491. */
  5492. void inverseModulo (const BitArray& modulus) throw();
  5493. /** Shifts a section of bits left or right.
  5494. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  5495. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  5496. */
  5497. void shiftBits (int howManyBitsLeft,
  5498. int startBit = 0) throw();
  5499. /** Does a signed comparison of two BitArrays.
  5500. Return values are:
  5501. - 0 if the numbers are the same
  5502. - < 0 if this number is smaller than the other
  5503. - > 0 if this number is bigger than the other
  5504. */
  5505. int compare (const BitArray& other) const throw();
  5506. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  5507. Return values are:
  5508. - 0 if the numbers are the same
  5509. - < 0 if this number is smaller than the other
  5510. - > 0 if this number is bigger than the other
  5511. */
  5512. int compareAbsolute (const BitArray& other) const throw();
  5513. /** Returns true if the value is less than zero.
  5514. @see setNegative, negate
  5515. */
  5516. bool isNegative() const throw();
  5517. /** Changes the sign of the number to be positive or negative.
  5518. @see isNegative, negate
  5519. */
  5520. void setNegative (const bool shouldBeNegative) throw();
  5521. /** Inverts the sign of the number.
  5522. @see isNegative, setNegative
  5523. */
  5524. void negate() throw();
  5525. /** Counts the total number of set bits in the array. */
  5526. int countNumberOfSetBits() const throw();
  5527. /** Looks for the index of the next set bit after a given starting point.
  5528. searches from startIndex (inclusive) upwards for the first set bit,
  5529. and returns its index.
  5530. If no set bits are found, it returns -1.
  5531. */
  5532. int findNextSetBit (int startIndex = 0) const throw();
  5533. /** Looks for the index of the next clear bit after a given starting point.
  5534. searches from startIndex (inclusive) upwards for the first clear bit,
  5535. and returns its index.
  5536. */
  5537. int findNextClearBit (int startIndex = 0) const throw();
  5538. /** Returns the index of the highest set bit in the array.
  5539. If the array is empty, this will return -1.
  5540. */
  5541. int getHighestBit() const throw();
  5542. /** Converts the array to a number string.
  5543. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5544. */
  5545. const String toString (const int base) const throw();
  5546. /** Converts a number string to an array.
  5547. Any non-valid characters will be ignored.
  5548. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5549. */
  5550. void parseString (const String& text,
  5551. const int base) throw();
  5552. /** Turns the array into a block of binary data.
  5553. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5554. of the array, and so on.
  5555. @see loadFromMemoryBlock
  5556. */
  5557. const MemoryBlock toMemoryBlock() const throw();
  5558. /** Copies a block of raw data onto this array.
  5559. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5560. of the array, and so on.
  5561. @see toMemoryBlock
  5562. */
  5563. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  5564. juce_UseDebuggingNewOperator
  5565. private:
  5566. void ensureSize (const int numVals) throw();
  5567. unsigned int* values;
  5568. int numValues, highestBit;
  5569. bool negative;
  5570. };
  5571. #endif // __JUCE_BITARRAY_JUCEHEADER__
  5572. /********* End of inlined file: juce_BitArray.h *********/
  5573. /**
  5574. A simple pseudo-random number generator.
  5575. */
  5576. class JUCE_API Random
  5577. {
  5578. public:
  5579. /** Creates a Random object based on a seed value.
  5580. For a given seed value, the subsequent numbers generated by this object
  5581. will be predictable, so a good idea is to set this value based
  5582. on the time, e.g.
  5583. new Random (Time::currentTimeMillis())
  5584. */
  5585. Random (const int64 seedValue) throw();
  5586. /** Destructor. */
  5587. ~Random() throw();
  5588. /** Returns the next random 32 bit integer.
  5589. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5590. */
  5591. int nextInt() throw();
  5592. /** Returns the next random number, limited to a given range.
  5593. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5594. */
  5595. int nextInt (const int maxValue) throw();
  5596. /** Returns the next 64-bit random number.
  5597. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5598. */
  5599. int64 nextInt64() throw();
  5600. /** Returns the next random floating-point number.
  5601. @returns a random value in the range 0 to 1.0
  5602. */
  5603. float nextFloat() throw();
  5604. /** Returns the next random floating-point number.
  5605. @returns a random value in the range 0 to 1.0
  5606. */
  5607. double nextDouble() throw();
  5608. /** Returns the next random boolean value.
  5609. */
  5610. bool nextBool() throw();
  5611. /** Returns a BitArray containing a random number.
  5612. @returns a random value in the range 0 to (maximumValue - 1).
  5613. */
  5614. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  5615. /** Sets a range of bits in a BitArray to random values. */
  5616. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  5617. /** To avoid the overhead of having to create a new Random object whenever
  5618. you need a number, this is a shared application-wide object that
  5619. can be used.
  5620. It's not thread-safe though, so threads should use their own Random object.
  5621. */
  5622. static Random& getSystemRandom() throw();
  5623. /** Resets this Random object to a given seed value. */
  5624. void setSeed (const int64 newSeed) throw();
  5625. /** Reseeds this generator using a value generated from various semi-random system
  5626. properties like the current time, etc.
  5627. Because this function convolves the time with the last seed value, calling
  5628. it repeatedly will increase the randomness of the final result.
  5629. */
  5630. void setSeedRandomly();
  5631. juce_UseDebuggingNewOperator
  5632. private:
  5633. int64 seed;
  5634. };
  5635. #endif // __JUCE_RANDOM_JUCEHEADER__
  5636. /********* End of inlined file: juce_Random.h *********/
  5637. #endif
  5638. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5639. #endif
  5640. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5641. /********* Start of inlined file: juce_Singleton.h *********/
  5642. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5643. #define __JUCE_SINGLETON_JUCEHEADER__
  5644. /********* Start of inlined file: juce_ScopedLock.h *********/
  5645. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5646. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5647. /**
  5648. Automatically locks and unlocks a CriticalSection object.
  5649. Use one of these as a local variable to control access to a CriticalSection.
  5650. e.g. @code
  5651. CriticalSection myCriticalSection;
  5652. for (;;)
  5653. {
  5654. const ScopedLock myScopedLock (myCriticalSection);
  5655. // myCriticalSection is now locked
  5656. ...do some stuff...
  5657. // myCriticalSection gets unlocked here.
  5658. }
  5659. @endcode
  5660. @see CriticalSection, ScopedUnlock
  5661. */
  5662. class JUCE_API ScopedLock
  5663. {
  5664. public:
  5665. /** Creates a ScopedLock.
  5666. As soon as it is created, this will lock the CriticalSection, and
  5667. when the ScopedLock object is deleted, the CriticalSection will
  5668. be unlocked.
  5669. Make sure this object is created and deleted by the same thread,
  5670. otherwise there are no guarantees what will happen! Best just to use it
  5671. as a local stack object, rather than creating one with the new() operator.
  5672. */
  5673. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5674. /** Destructor.
  5675. The CriticalSection will be unlocked when the destructor is called.
  5676. Make sure this object is created and deleted by the same thread,
  5677. otherwise there are no guarantees what will happen!
  5678. */
  5679. inline ~ScopedLock() throw() { lock_.exit(); }
  5680. private:
  5681. const CriticalSection& lock_;
  5682. ScopedLock (const ScopedLock&);
  5683. const ScopedLock& operator= (const ScopedLock&);
  5684. };
  5685. /**
  5686. Automatically unlocks and re-locks a CriticalSection object.
  5687. This is the reverse of a ScopedLock object - instead of locking the critical
  5688. section for the lifetime of this object, it unlocks it.
  5689. Make sure you don't try to unlock critical sections that aren't actually locked!
  5690. e.g. @code
  5691. CriticalSection myCriticalSection;
  5692. for (;;)
  5693. {
  5694. const ScopedLock myScopedLock (myCriticalSection);
  5695. // myCriticalSection is now locked
  5696. ... do some stuff with it locked ..
  5697. while (xyz)
  5698. {
  5699. ... do some stuff with it locked ..
  5700. const ScopedUnlock unlocker (myCriticalSection);
  5701. // myCriticalSection is now unlocked for the remainder of this block,
  5702. // and re-locked at the end.
  5703. ...do some stuff with it unlocked ...
  5704. }
  5705. // myCriticalSection gets unlocked here.
  5706. }
  5707. @endcode
  5708. @see CriticalSection, ScopedLock
  5709. */
  5710. class ScopedUnlock
  5711. {
  5712. public:
  5713. /** Creates a ScopedUnlock.
  5714. As soon as it is created, this will unlock the CriticalSection, and
  5715. when the ScopedLock object is deleted, the CriticalSection will
  5716. be re-locked.
  5717. Make sure this object is created and deleted by the same thread,
  5718. otherwise there are no guarantees what will happen! Best just to use it
  5719. as a local stack object, rather than creating one with the new() operator.
  5720. */
  5721. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5722. /** Destructor.
  5723. The CriticalSection will be unlocked when the destructor is called.
  5724. Make sure this object is created and deleted by the same thread,
  5725. otherwise there are no guarantees what will happen!
  5726. */
  5727. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5728. private:
  5729. const CriticalSection& lock_;
  5730. ScopedUnlock (const ScopedLock&);
  5731. const ScopedUnlock& operator= (const ScopedUnlock&);
  5732. };
  5733. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5734. /********* End of inlined file: juce_ScopedLock.h *********/
  5735. /**
  5736. Macro to declare member variables and methods for a singleton class.
  5737. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  5738. to the class's definition.
  5739. If allowOnlyOneInstance == true, it won't allow the object to be created
  5740. more than once in the process's lifetime.
  5741. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5742. implementation code.
  5743. Clients can then call the static MyClass::getInstance() to get a pointer to the
  5744. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  5745. is currently extant
  5746. it's a very good idea to also add the call clearSingletonInstance() to the
  5747. destructor of the class, in case it is deleted by other means than deleteInstance()
  5748. e.g. @code
  5749. class MySingleton
  5750. {
  5751. public:
  5752. MySingleton()
  5753. {
  5754. }
  5755. ~MySingleton()
  5756. {
  5757. // this ensures that no dangling pointers are left when the
  5758. // singleton is deleted.
  5759. clearSingletonInstance();
  5760. }
  5761. juce_DeclareSingleton (MySingleton, false)
  5762. };
  5763. juce_ImplementSingleton (MySingleton)
  5764. // example of usage:
  5765. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5766. ...
  5767. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5768. @endcode
  5769. If you know that your object will only be created and deleted by a single thread, you
  5770. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5771. of this one.
  5772. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5773. */
  5774. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  5775. \
  5776. static classname* _singletonInstance; \
  5777. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5778. \
  5779. static classname* getInstance() \
  5780. { \
  5781. if (_singletonInstance == 0) \
  5782. {\
  5783. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5784. \
  5785. if (_singletonInstance == 0) \
  5786. { \
  5787. static bool alreadyInside = false; \
  5788. static bool createdOnceAlready = false; \
  5789. \
  5790. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5791. jassert (! problem); \
  5792. if (! problem) \
  5793. { \
  5794. createdOnceAlready = true; \
  5795. alreadyInside = true; \
  5796. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5797. alreadyInside = false; \
  5798. \
  5799. _singletonInstance = newObject; \
  5800. } \
  5801. } \
  5802. } \
  5803. \
  5804. return _singletonInstance; \
  5805. } \
  5806. \
  5807. static inline classname* getInstanceWithoutCreating() throw() \
  5808. { \
  5809. return _singletonInstance; \
  5810. } \
  5811. \
  5812. static void deleteInstance() \
  5813. { \
  5814. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5815. if (_singletonInstance != 0) \
  5816. { \
  5817. classname* const old = _singletonInstance; \
  5818. _singletonInstance = 0; \
  5819. delete old; \
  5820. } \
  5821. } \
  5822. \
  5823. void clearSingletonInstance() throw() \
  5824. { \
  5825. if (_singletonInstance == this) \
  5826. _singletonInstance = 0; \
  5827. }
  5828. /** This is a counterpart to the juce_DeclareSingleton macro.
  5829. After adding the juce_DeclareSingleton to the class definition, this macro has
  5830. to be used in the cpp file.
  5831. */
  5832. #define juce_ImplementSingleton(classname) \
  5833. \
  5834. classname* classname::_singletonInstance = 0; \
  5835. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5836. /**
  5837. Macro to declare member variables and methods for a singleton class.
  5838. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5839. section to make access to it thread-safe. If you know that your object will
  5840. only ever be created or deleted by a single thread, then this is a
  5841. more efficient version to use.
  5842. See the documentation for juce_DeclareSingleton for more information about
  5843. how to use it, the only difference being that you have to use
  5844. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5845. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5846. */
  5847. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  5848. \
  5849. static classname* _singletonInstance; \
  5850. \
  5851. static classname* getInstance() \
  5852. { \
  5853. if (_singletonInstance == 0) \
  5854. { \
  5855. static bool alreadyInside = false; \
  5856. static bool createdOnceAlready = false; \
  5857. \
  5858. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5859. jassert (! problem); \
  5860. if (! problem) \
  5861. { \
  5862. createdOnceAlready = true; \
  5863. alreadyInside = true; \
  5864. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5865. alreadyInside = false; \
  5866. \
  5867. _singletonInstance = newObject; \
  5868. } \
  5869. } \
  5870. \
  5871. return _singletonInstance; \
  5872. } \
  5873. \
  5874. static inline classname* getInstanceWithoutCreating() throw() \
  5875. { \
  5876. return _singletonInstance; \
  5877. } \
  5878. \
  5879. static void deleteInstance() \
  5880. { \
  5881. if (_singletonInstance != 0) \
  5882. { \
  5883. classname* const old = _singletonInstance; \
  5884. _singletonInstance = 0; \
  5885. delete old; \
  5886. } \
  5887. } \
  5888. \
  5889. void clearSingletonInstance() throw() \
  5890. { \
  5891. if (_singletonInstance == this) \
  5892. _singletonInstance = 0; \
  5893. }
  5894. /**
  5895. Macro to declare member variables and methods for a singleton class.
  5896. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5897. for recursion or repeated instantiation. It's intended for use as a lightweight
  5898. version of a singleton, where you're using it in very straightforward
  5899. circumstances and don't need the extra checking.
  5900. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  5901. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  5902. See the documentation for juce_DeclareSingleton for more information about
  5903. how to use it, the only difference being that you have to use
  5904. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5905. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  5906. */
  5907. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  5908. \
  5909. static classname* _singletonInstance; \
  5910. \
  5911. static classname* getInstance() \
  5912. { \
  5913. if (_singletonInstance == 0) \
  5914. _singletonInstance = new classname(); \
  5915. \
  5916. return _singletonInstance; \
  5917. } \
  5918. \
  5919. static inline classname* getInstanceWithoutCreating() throw() \
  5920. { \
  5921. return _singletonInstance; \
  5922. } \
  5923. \
  5924. static void deleteInstance() \
  5925. { \
  5926. if (_singletonInstance != 0) \
  5927. { \
  5928. classname* const old = _singletonInstance; \
  5929. _singletonInstance = 0; \
  5930. delete old; \
  5931. } \
  5932. } \
  5933. \
  5934. void clearSingletonInstance() throw() \
  5935. { \
  5936. if (_singletonInstance == this) \
  5937. _singletonInstance = 0; \
  5938. }
  5939. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  5940. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  5941. to the class definition, this macro has to be used somewhere in the cpp file.
  5942. */
  5943. #define juce_ImplementSingleton_SingleThreaded(classname) \
  5944. \
  5945. classname* classname::_singletonInstance = 0;
  5946. #endif // __JUCE_SINGLETON_JUCEHEADER__
  5947. /********* End of inlined file: juce_Singleton.h *********/
  5948. #endif
  5949. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  5950. #endif
  5951. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5952. /********* Start of inlined file: juce_SystemStats.h *********/
  5953. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5954. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  5955. /**
  5956. Contains methods for finding out about the current hardware and OS configuration.
  5957. */
  5958. class JUCE_API SystemStats
  5959. {
  5960. public:
  5961. /** Returns the current version of JUCE,
  5962. (just in case you didn't already know at compile-time.)
  5963. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  5964. */
  5965. static const String getJUCEVersion() throw();
  5966. /** The set of possible results of the getOperatingSystemType() method.
  5967. */
  5968. enum OperatingSystemType
  5969. {
  5970. UnknownOS = 0,
  5971. MacOSX = 0x1000,
  5972. Linux = 0x2000,
  5973. Win95 = 0x4001,
  5974. Win98 = 0x4002,
  5975. WinNT351 = 0x4103,
  5976. WinNT40 = 0x4104,
  5977. Win2000 = 0x4105,
  5978. WinXP = 0x4106,
  5979. WinVista = 0x4107,
  5980. Windows = 0x4000, /**< To test whether any version of Windows is running,
  5981. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  5982. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  5983. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  5984. };
  5985. /** Returns the type of operating system we're running on.
  5986. @returns one of the values from the OperatingSystemType enum.
  5987. @see getOperatingSystemName
  5988. */
  5989. static OperatingSystemType getOperatingSystemType() throw();
  5990. /** Returns the name of the type of operating system we're running on.
  5991. @returns a string describing the OS type.
  5992. @see getOperatingSystemType
  5993. */
  5994. static const String getOperatingSystemName() throw();
  5995. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  5996. */
  5997. static bool isOperatingSystem64Bit() throw();
  5998. // CPU and memory information..
  5999. /** Returns the approximate CPU speed.
  6000. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6001. what year you're reading this...)
  6002. */
  6003. static int getCpuSpeedInMegaherz() throw();
  6004. /** Returns a string to indicate the CPU vendor.
  6005. Might not be known on some systems.
  6006. */
  6007. static const String getCpuVendor() throw();
  6008. /** Checks whether Intel MMX instructions are available. */
  6009. static bool hasMMX() throw();
  6010. /** Checks whether Intel SSE instructions are available. */
  6011. static bool hasSSE() throw();
  6012. /** Checks whether Intel SSE2 instructions are available. */
  6013. static bool hasSSE2() throw();
  6014. /** Checks whether AMD 3DNOW instructions are available. */
  6015. static bool has3DNow() throw();
  6016. /** Returns the number of CPUs.
  6017. */
  6018. static int getNumCpus() throw();
  6019. /** Returns a clock-cycle tick counter, if available.
  6020. If the machine can do it, this will return a tick-count
  6021. where each tick is one cpu clock cycle - used for profiling
  6022. code.
  6023. @returns the tick count, or zero if not available.
  6024. */
  6025. static int64 getClockCycleCounter() throw();
  6026. /** Finds out how much RAM is in the machine.
  6027. @returns the approximate number of megabytes of memory, or zero if
  6028. something goes wrong when finding out.
  6029. */
  6030. static int getMemorySizeInMegabytes() throw();
  6031. /** Returns the system page-size.
  6032. This is only used by programmers with beards.
  6033. */
  6034. static int getPageSize() throw();
  6035. /** Returns a list of MAC addresses found on this machine.
  6036. @param addresses an array into which the MAC addresses should be copied
  6037. @param maxNum the number of elements in this array
  6038. @param littleEndian the endianness of the numbers to return. Note that
  6039. the default values of this parameter are different on
  6040. Mac/PC to avoid breaking old software that was written
  6041. before this parameter was added (when the two systems
  6042. defaulted to using different endiannesses). In newer
  6043. software you probably want to specify an explicit value
  6044. for this.
  6045. @returns the number of MAC addresses that were found
  6046. */
  6047. static int getMACAddresses (int64* addresses, int maxNum,
  6048. #if JUCE_MAC
  6049. const bool littleEndian = true) throw();
  6050. #else
  6051. const bool littleEndian = false) throw();
  6052. #endif
  6053. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6054. static void initialiseStats() throw();
  6055. };
  6056. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6057. /********* End of inlined file: juce_SystemStats.h *********/
  6058. #endif
  6059. #ifndef __JUCE_TIME_JUCEHEADER__
  6060. #endif
  6061. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6062. #endif
  6063. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6064. #endif
  6065. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6066. #endif
  6067. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6068. #endif
  6069. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6070. #endif
  6071. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6072. #endif
  6073. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6074. /********* Start of inlined file: juce_PropertySet.h *********/
  6075. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6076. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6077. /********* Start of inlined file: juce_StringPairArray.h *********/
  6078. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6079. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6080. /**
  6081. A container for holding a set of strings which are keyed by another string.
  6082. @see StringArray
  6083. */
  6084. class JUCE_API StringPairArray
  6085. {
  6086. public:
  6087. /** Creates an empty array */
  6088. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6089. /** Creates a copy of another array */
  6090. StringPairArray (const StringPairArray& other) throw();
  6091. /** Destructor. */
  6092. ~StringPairArray() throw();
  6093. /** Copies the contents of another string array into this one */
  6094. const StringPairArray& operator= (const StringPairArray& other) throw();
  6095. /** Compares two arrays.
  6096. Comparisons are case-sensitive.
  6097. @returns true only if the other array contains exactly the same strings with the same keys
  6098. */
  6099. bool operator== (const StringPairArray& other) const throw();
  6100. /** Compares two arrays.
  6101. Comparisons are case-sensitive.
  6102. @returns false if the other array contains exactly the same strings with the same keys
  6103. */
  6104. bool operator!= (const StringPairArray& other) const throw();
  6105. /** Finds the value corresponding to a key string.
  6106. If no such key is found, this will just return an empty string. To check whether
  6107. a given key actually exists (because it might actually be paired with an empty string), use
  6108. the getAllKeys() method to obtain a list.
  6109. Obviously the reference returned shouldn't be stored for later use, as the
  6110. string it refers to may disappear when the array changes.
  6111. @see getValue
  6112. */
  6113. const String& operator[] (const String& key) const throw();
  6114. /** Finds the value corresponding to a key string.
  6115. If no such key is found, this will just return the value provided as a default.
  6116. @see operator[]
  6117. */
  6118. const String getValue (const String& key, const String& defaultReturnValue) const;
  6119. /** Returns a list of all keys in the array. */
  6120. const StringArray& getAllKeys() const throw() { return keys; }
  6121. /** Returns a list of all values in the array. */
  6122. const StringArray& getAllValues() const throw() { return values; }
  6123. /** Returns the number of strings in the array */
  6124. inline int size() const throw() { return keys.size(); };
  6125. /** Adds or amends a key/value pair.
  6126. If a value already exists with this key, its value will be overwritten,
  6127. otherwise the key/value pair will be added to the array.
  6128. */
  6129. void set (const String& key,
  6130. const String& value) throw();
  6131. /** Adds the items from another array to this one.
  6132. This is equivalent to using set() to add each of the pairs from the other array.
  6133. */
  6134. void addArray (const StringPairArray& other);
  6135. /** Removes all elements from the array. */
  6136. void clear() throw();
  6137. /** Removes a string from the array based on its key.
  6138. If the key isn't found, nothing will happen.
  6139. */
  6140. void remove (const String& key) throw();
  6141. /** Removes a string from the array based on its index.
  6142. If the index is out-of-range, no action will be taken.
  6143. */
  6144. void remove (const int index) throw();
  6145. /** Reduces the amount of storage being used by the array.
  6146. Arrays typically allocate slightly more storage than they need, and after
  6147. removing elements, they may have quite a lot of unused space allocated.
  6148. This method will reduce the amount of allocated storage to a minimum.
  6149. */
  6150. void minimiseStorageOverheads() throw();
  6151. juce_UseDebuggingNewOperator
  6152. private:
  6153. StringArray keys, values;
  6154. bool ignoreCase;
  6155. };
  6156. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6157. /********* End of inlined file: juce_StringPairArray.h *********/
  6158. /********* Start of inlined file: juce_XmlElement.h *********/
  6159. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6160. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6161. /********* Start of inlined file: juce_OutputStream.h *********/
  6162. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6163. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6164. /********* Start of inlined file: juce_InputStream.h *********/
  6165. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6166. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6167. /** The base class for streams that read data.
  6168. Input and output streams are used throughout the library - subclasses can override
  6169. some or all of the virtual functions to implement their behaviour.
  6170. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6171. */
  6172. class JUCE_API InputStream
  6173. {
  6174. public:
  6175. /** Destructor. */
  6176. virtual ~InputStream() {}
  6177. /** Returns the total number of bytes available for reading in this stream.
  6178. Note that this is the number of bytes available from the start of the
  6179. stream, not from the current position.
  6180. If the size of the stream isn't actually known, this may return -1.
  6181. */
  6182. virtual int64 getTotalLength() = 0;
  6183. /** Returns true if the stream has no more data to read. */
  6184. virtual bool isExhausted() = 0;
  6185. /** Reads a set of bytes from the stream into a memory buffer.
  6186. This is the only read method that subclasses actually need to implement, as the
  6187. InputStream base class implements the other read methods in terms of this one (although
  6188. it's often more efficient for subclasses to implement them directly).
  6189. @param destBuffer the destination buffer for the data
  6190. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6191. memory block passed in is big enough to contain this
  6192. many bytes.
  6193. @returns the actual number of bytes that were read, which may be less than
  6194. maxBytesToRead if the stream is exhausted before it gets that far
  6195. */
  6196. virtual int read (void* destBuffer,
  6197. int maxBytesToRead) = 0;
  6198. /** Reads a byte from the stream.
  6199. If the stream is exhausted, this will return zero.
  6200. @see OutputStream::writeByte
  6201. */
  6202. virtual char readByte();
  6203. /** Reads a boolean from the stream.
  6204. The bool is encoded as a single byte - 1 for true, 0 for false.
  6205. If the stream is exhausted, this will return false.
  6206. @see OutputStream::writeBool
  6207. */
  6208. virtual bool readBool();
  6209. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6210. If the next two bytes read are byte1 and byte2, this returns
  6211. (byte1 | (byte2 << 8)).
  6212. If the stream is exhausted partway through reading the bytes, this will return zero.
  6213. @see OutputStream::writeShort, readShortBigEndian
  6214. */
  6215. virtual short readShort();
  6216. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6217. If the next two bytes read are byte1 and byte2, this returns
  6218. (byte2 | (byte1 << 8)).
  6219. If the stream is exhausted partway through reading the bytes, this will return zero.
  6220. @see OutputStream::writeShortBigEndian, readShort
  6221. */
  6222. virtual short readShortBigEndian();
  6223. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6224. If the next four bytes are byte1 to byte4, this returns
  6225. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6226. If the stream is exhausted partway through reading the bytes, this will return zero.
  6227. @see OutputStream::writeInt, readIntBigEndian
  6228. */
  6229. virtual int readInt();
  6230. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6231. If the next four bytes are byte1 to byte4, this returns
  6232. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6233. If the stream is exhausted partway through reading the bytes, this will return zero.
  6234. @see OutputStream::writeIntBigEndian, readInt
  6235. */
  6236. virtual int readIntBigEndian();
  6237. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6238. If the next eight bytes are byte1 to byte8, this returns
  6239. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6240. If the stream is exhausted partway through reading the bytes, this will return zero.
  6241. @see OutputStream::writeInt64, readInt64BigEndian
  6242. */
  6243. virtual int64 readInt64();
  6244. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6245. If the next eight bytes are byte1 to byte8, this returns
  6246. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6247. If the stream is exhausted partway through reading the bytes, this will return zero.
  6248. @see OutputStream::writeInt64BigEndian, readInt64
  6249. */
  6250. virtual int64 readInt64BigEndian();
  6251. /** Reads four bytes as a 32-bit floating point value.
  6252. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6253. If the stream is exhausted partway through reading the bytes, this will return zero.
  6254. @see OutputStream::writeFloat, readDouble
  6255. */
  6256. virtual float readFloat();
  6257. /** Reads four bytes as a 32-bit floating point value.
  6258. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6259. If the stream is exhausted partway through reading the bytes, this will return zero.
  6260. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6261. */
  6262. virtual float readFloatBigEndian();
  6263. /** Reads eight bytes as a 64-bit floating point value.
  6264. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6265. If the stream is exhausted partway through reading the bytes, this will return zero.
  6266. @see OutputStream::writeDouble, readFloat
  6267. */
  6268. virtual double readDouble();
  6269. /** Reads eight bytes as a 64-bit floating point value.
  6270. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6271. If the stream is exhausted partway through reading the bytes, this will return zero.
  6272. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6273. */
  6274. virtual double readDoubleBigEndian();
  6275. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6276. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6277. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6278. @see OutputStream::writeCompressedInt()
  6279. */
  6280. virtual int readCompressedInt();
  6281. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6282. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6283. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6284. After this call, the stream's position will be left pointing to the character
  6285. following the line-feed, but the linefeeds aren't included in the string that
  6286. is returned.
  6287. */
  6288. virtual const String readNextLine();
  6289. /** Reads a zero-terminated string from the stream.
  6290. This will read characters from the stream until it hits a zero character or
  6291. end-of-stream.
  6292. @see OutputStream::writeString, readEntireStreamAsString
  6293. */
  6294. virtual const String readString();
  6295. /** Tries to read the whole stream and turn it into a string.
  6296. This will read from the stream's current position until the end-of-stream, and
  6297. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6298. */
  6299. virtual const String readEntireStreamAsString();
  6300. /** Reads from the stream and appends the data to a MemoryBlock.
  6301. @param destBlock the block to append the data onto
  6302. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6303. of bytes that will be read - if it's negative, data
  6304. will be read until the stream is exhausted.
  6305. @returns the number of bytes that were added to the memory block
  6306. */
  6307. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6308. int maxNumBytesToRead = -1);
  6309. /** Returns the offset of the next byte that will be read from the stream.
  6310. @see setPosition
  6311. */
  6312. virtual int64 getPosition() = 0;
  6313. /** Tries to move the current read position of the stream.
  6314. The position is an absolute number of bytes from the stream's start.
  6315. Some streams might not be able to do this, in which case they should do
  6316. nothing and return false. Others might be able to manage it by resetting
  6317. themselves and skipping to the correct position, although this is
  6318. obviously a bit slow.
  6319. @returns true if the stream manages to reposition itself correctly
  6320. @see getPosition
  6321. */
  6322. virtual bool setPosition (int64 newPosition) = 0;
  6323. /** Reads and discards a number of bytes from the stream.
  6324. Some input streams might implement this efficiently, but the base
  6325. class will just keep reading data until the requisite number of bytes
  6326. have been done.
  6327. */
  6328. virtual void skipNextBytes (int64 numBytesToSkip);
  6329. juce_UseDebuggingNewOperator
  6330. protected:
  6331. InputStream() throw() {}
  6332. };
  6333. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6334. /********* End of inlined file: juce_InputStream.h *********/
  6335. /**
  6336. The base class for streams that write data to some kind of destination.
  6337. Input and output streams are used throughout the library - subclasses can override
  6338. some or all of the virtual functions to implement their behaviour.
  6339. @see InputStream, MemoryOutputStream, FileOutputStream
  6340. */
  6341. class JUCE_API OutputStream
  6342. {
  6343. public:
  6344. /** Destructor.
  6345. Some subclasses might want to do things like call flush() during their
  6346. destructors.
  6347. */
  6348. virtual ~OutputStream();
  6349. /** If the stream is using a buffer, this will ensure it gets written
  6350. out to the destination. */
  6351. virtual void flush() = 0;
  6352. /** Tries to move the stream's output position.
  6353. Not all streams will be able to seek to a new position - this will return
  6354. false if it fails to work.
  6355. @see getPosition
  6356. */
  6357. virtual bool setPosition (int64 newPosition) = 0;
  6358. /** Returns the stream's current position.
  6359. @see setPosition
  6360. */
  6361. virtual int64 getPosition() = 0;
  6362. /** Writes a block of data to the stream.
  6363. When creating a subclass of OutputStream, this is the only write method
  6364. that needs to be overloaded - the base class has methods for writing other
  6365. types of data which use this to do the work.
  6366. @returns false if the write operation fails for some reason
  6367. */
  6368. virtual bool write (const void* dataToWrite,
  6369. int howManyBytes) = 0;
  6370. /** Writes a single byte to the stream.
  6371. @see InputStream::readByte
  6372. */
  6373. virtual void writeByte (char byte);
  6374. /** Writes a boolean to the stream.
  6375. This is encoded as a byte - either 1 or 0.
  6376. @see InputStream::readBool
  6377. */
  6378. virtual void writeBool (bool boolValue);
  6379. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6380. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6381. @see InputStream::readShort
  6382. */
  6383. virtual void writeShort (short value);
  6384. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6385. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6386. @see InputStream::readShortBigEndian
  6387. */
  6388. virtual void writeShortBigEndian (short value);
  6389. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6390. @see InputStream::readInt
  6391. */
  6392. virtual void writeInt (int value);
  6393. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6394. @see InputStream::readIntBigEndian
  6395. */
  6396. virtual void writeIntBigEndian (int value);
  6397. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6398. @see InputStream::readInt64
  6399. */
  6400. virtual void writeInt64 (int64 value);
  6401. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6402. @see InputStream::readInt64BigEndian
  6403. */
  6404. virtual void writeInt64BigEndian (int64 value);
  6405. /** Writes a 32-bit floating point value to the stream.
  6406. The binary 32-bit encoding of the float is written as a little-endian int.
  6407. @see InputStream::readFloat
  6408. */
  6409. virtual void writeFloat (float value);
  6410. /** Writes a 32-bit floating point value to the stream.
  6411. The binary 32-bit encoding of the float is written as a big-endian int.
  6412. @see InputStream::readFloatBigEndian
  6413. */
  6414. virtual void writeFloatBigEndian (float value);
  6415. /** Writes a 64-bit floating point value to the stream.
  6416. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6417. @see InputStream::readDouble
  6418. */
  6419. virtual void writeDouble (double value);
  6420. /** Writes a 64-bit floating point value to the stream.
  6421. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6422. @see InputStream::readDoubleBigEndian
  6423. */
  6424. virtual void writeDoubleBigEndian (double value);
  6425. /** Writes a condensed encoding of a 32-bit integer.
  6426. If you're storing a lot of integers which are unlikely to have very large values,
  6427. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6428. under 0xffff only 3 bytes, etc.
  6429. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6430. @see InputStream::readCompressedInt
  6431. */
  6432. virtual void writeCompressedInt (int value);
  6433. /** Stores a string in the stream.
  6434. This isn't the method to use if you're trying to append text to the end of a
  6435. text-file! It's intended for storing a string for later retrieval
  6436. by InputStream::readString.
  6437. For appending text to a file, instead use writeText, printf, or operator<<
  6438. @see InputStream::readString, writeText, printf, operator<<
  6439. */
  6440. virtual void writeString (const String& text);
  6441. /** Writes a string of text to the stream.
  6442. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6443. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6444. should only be done at the start of a file).
  6445. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6446. */
  6447. virtual void writeText (const String& text,
  6448. const bool asUnicode,
  6449. const bool writeUnicodeHeaderBytes);
  6450. /** Writes a string of text to the stream.
  6451. @see writeText
  6452. */
  6453. virtual void printf (const char* format, ...);
  6454. /** Reads data from an input stream and writes it to this stream.
  6455. @param source the stream to read from
  6456. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6457. less than zero, it will keep reading until the input
  6458. is exhausted)
  6459. */
  6460. virtual int writeFromInputStream (InputStream& source,
  6461. int maxNumBytesToWrite);
  6462. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6463. virtual OutputStream& operator<< (const int number);
  6464. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6465. virtual OutputStream& operator<< (const double number);
  6466. /** Writes a character to the stream. */
  6467. virtual OutputStream& operator<< (const char character);
  6468. /** Writes a null-terminated string to the stream. */
  6469. virtual OutputStream& operator<< (const char* const text);
  6470. /** Writes a null-terminated unicode text string to the stream, converting it
  6471. to 8-bit characters in the default system encoding. */
  6472. virtual OutputStream& operator<< (const juce_wchar* const text);
  6473. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6474. virtual OutputStream& operator<< (const String& text);
  6475. juce_UseDebuggingNewOperator
  6476. protected:
  6477. OutputStream() throw();
  6478. };
  6479. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6480. /********* End of inlined file: juce_OutputStream.h *********/
  6481. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6482. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6483. will be the name of a pointer to each child element.
  6484. E.g. @code
  6485. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6486. forEachXmlChildElement (*myParentXml, child)
  6487. {
  6488. if (child->hasTagName ("FOO"))
  6489. doSomethingWithXmlElement (child);
  6490. }
  6491. @endcode
  6492. @see forEachXmlChildElementWithTagName
  6493. */
  6494. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6495. \
  6496. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6497. childElementVariableName != 0; \
  6498. childElementVariableName = childElementVariableName->getNextElement())
  6499. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6500. which have a specified tag.
  6501. This does the same job as the forEachXmlChildElement macro, but only for those
  6502. elements that have a particular tag name.
  6503. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6504. will be the name of a pointer to each child element. The requiredTagName is the
  6505. tag name to match.
  6506. E.g. @code
  6507. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6508. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6509. {
  6510. // the child object is now guaranteed to be a <MYTAG> element..
  6511. doSomethingWithMYTAGElement (child);
  6512. }
  6513. @endcode
  6514. @see forEachXmlChildElement
  6515. */
  6516. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6517. \
  6518. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6519. childElementVariableName != 0; \
  6520. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6521. /** Used to build a tree of elements representing an XML document.
  6522. An XML document can be parsed into a tree of XmlElements, each of which
  6523. represents an XML tag structure, and which may itself contain other
  6524. nested elements.
  6525. An XmlElement can also be converted back into a text document, and has
  6526. lots of useful methods for manipulating its attributes and sub-elements,
  6527. so XmlElements can actually be used as a handy general-purpose data
  6528. structure.
  6529. Here's an example of parsing some elements: @code
  6530. // check we're looking at the right kind of document..
  6531. if (myElement->hasTagName ("ANIMALS"))
  6532. {
  6533. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6534. forEachXmlChildElement (*myElement, e)
  6535. {
  6536. if (e->hasTagName ("GIRAFFE"))
  6537. {
  6538. // found a giraffe, so use some of its attributes..
  6539. String giraffeName = e->getStringAttribute ("name");
  6540. int giraffeAge = e->getIntAttribute ("age");
  6541. bool isFriendly = e->getBoolAttribute ("friendly");
  6542. }
  6543. }
  6544. }
  6545. @endcode
  6546. And here's an example of how to create an XML document from scratch: @code
  6547. // create an outer node called "ANIMALS"
  6548. XmlElement animalsList ("ANIMALS");
  6549. for (int i = 0; i < numAnimals; ++i)
  6550. {
  6551. // create an inner element..
  6552. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6553. giraffe->setAttribute ("name", "nigel");
  6554. giraffe->setAttribute ("age", 10);
  6555. giraffe->setAttribute ("friendly", true);
  6556. // ..and add our new element to the parent node
  6557. animalsList.addChildElement (giraffe);
  6558. }
  6559. // now we can turn the whole thing into a text document..
  6560. String myXmlDoc = animalsList.createDocument (String::empty);
  6561. @endcode
  6562. @see XmlDocument
  6563. */
  6564. class JUCE_API XmlElement
  6565. {
  6566. public:
  6567. /** Creates an XmlElement with this tag name. */
  6568. XmlElement (const String& tagName) throw();
  6569. /** Creates a (deep) copy of another element. */
  6570. XmlElement (const XmlElement& other) throw();
  6571. /** Creates a (deep) copy of another element. */
  6572. const XmlElement& operator= (const XmlElement& other) throw();
  6573. /** Deleting an XmlElement will also delete all its child elements. */
  6574. ~XmlElement() throw();
  6575. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6576. The elements are only considered equivalent if they contain the same attiributes
  6577. with the same values, and have the same sub-nodes.
  6578. @param other the other element to compare to
  6579. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6580. same attributes in a different order will be
  6581. considered the same; if false, the attributes must
  6582. be in the same order as well
  6583. */
  6584. bool isEquivalentTo (const XmlElement* const other,
  6585. const bool ignoreOrderOfAttributes) const throw();
  6586. /** Returns an XML text document that represents this element.
  6587. The string returned can be parsed to recreate the same XmlElement that
  6588. was used to create it.
  6589. @param dtdToUse the DTD to add to the document
  6590. @param allOnOneLine if true, this means that the document will not contain any
  6591. linefeeds, so it'll be smaller but not very easy to read.
  6592. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6593. document
  6594. @param encodingType the character encoding format string to put into the xml
  6595. header
  6596. @param lineWrapLength the line length that will be used before items get placed on
  6597. a new line. This isn't an absolute maximum length, it just
  6598. determines how lists of attributes get broken up
  6599. @see writeToFile
  6600. */
  6601. const String createDocument (const String& dtdToUse,
  6602. const bool allOnOneLine = false,
  6603. const bool includeXmlHeader = true,
  6604. const tchar* const encodingType = JUCE_T("UTF-8"),
  6605. const int lineWrapLength = 60) const throw();
  6606. /** Writes the element to a file as an XML document.
  6607. To improve safety in case something goes wrong while writing the file, this
  6608. will actually write the document to a new temporary file in the same
  6609. directory as the destination file, and if this succeeds, it will rename this
  6610. new file as the destination file (overwriting any existing file that was there).
  6611. @param destinationFile the file to write to. If this already exists, it will be
  6612. overwritten.
  6613. @param dtdToUse the DTD to add to the document
  6614. @param encodingType the character encoding format string to put into the xml
  6615. header
  6616. @param lineWrapLength the line length that will be used before items get placed on
  6617. a new line. This isn't an absolute maximum length, it just
  6618. determines how lists of attributes get broken up
  6619. @returns true if the file is written successfully; false if something goes wrong
  6620. in the process
  6621. @see createDocument
  6622. */
  6623. bool writeToFile (const File& destinationFile,
  6624. const String& dtdToUse,
  6625. const tchar* const encodingType = JUCE_T("UTF-8"),
  6626. const int lineWrapLength = 60) const throw();
  6627. /** Returns this element's tag type name.
  6628. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6629. "MOOSE".
  6630. @see hasTagName
  6631. */
  6632. inline const String& getTagName() const throw() { return tagName; }
  6633. /** Tests whether this element has a particular tag name.
  6634. @param possibleTagName the tag name you're comparing it with
  6635. @see getTagName
  6636. */
  6637. bool hasTagName (const tchar* const possibleTagName) const throw();
  6638. /** Returns the number of XML attributes this element contains.
  6639. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6640. return 2.
  6641. */
  6642. int getNumAttributes() const throw();
  6643. /** Returns the name of one of the elements attributes.
  6644. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6645. getAttributeName(1) would return "antlers".
  6646. @see getAttributeValue, getStringAttribute
  6647. */
  6648. const String& getAttributeName (const int attributeIndex) const throw();
  6649. /** Returns the value of one of the elements attributes.
  6650. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6651. getAttributeName(1) would return "2".
  6652. @see getAttributeName, getStringAttribute
  6653. */
  6654. const String& getAttributeValue (const int attributeIndex) const throw();
  6655. // Attribute-handling methods..
  6656. /** Checks whether the element contains an attribute with a certain name. */
  6657. bool hasAttribute (const tchar* const attributeName) const throw();
  6658. /** Returns the value of a named attribute.
  6659. @param attributeName the name of the attribute to look up
  6660. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6661. with this name
  6662. */
  6663. const String getStringAttribute (const tchar* const attributeName,
  6664. const tchar* const defaultReturnValue = 0) const throw();
  6665. /** Compares the value of a named attribute with a value passed-in.
  6666. @param attributeName the name of the attribute to look up
  6667. @param stringToCompareAgainst the value to compare it with
  6668. @param ignoreCase whether the comparison should be case-insensitive
  6669. @returns true if the value of the attribute is the same as the string passed-in;
  6670. false if it's different (or if no such attribute exists)
  6671. */
  6672. bool compareAttribute (const tchar* const attributeName,
  6673. const tchar* const stringToCompareAgainst,
  6674. const bool ignoreCase = false) const throw();
  6675. /** Returns the value of a named attribute as an integer.
  6676. This will try to find the attribute and convert it to an integer (using
  6677. the String::getIntValue() method).
  6678. @param attributeName the name of the attribute to look up
  6679. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6680. with this name
  6681. @see setAttribute (const tchar* const, int)
  6682. */
  6683. int getIntAttribute (const tchar* const attributeName,
  6684. const int defaultReturnValue = 0) const throw();
  6685. /** Returns the value of a named attribute as floating-point.
  6686. This will try to find the attribute and convert it to an integer (using
  6687. the String::getDoubleValue() method).
  6688. @param attributeName the name of the attribute to look up
  6689. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6690. with this name
  6691. @see setAttribute (const tchar* const, double)
  6692. */
  6693. double getDoubleAttribute (const tchar* const attributeName,
  6694. const double defaultReturnValue = 0.0) const throw();
  6695. /** Returns the value of a named attribute as a boolean.
  6696. This will try to find the attribute and interpret it as a boolean. To do this,
  6697. it'll return true if the value is "1", "true", "y", etc, or false for other
  6698. values.
  6699. @param attributeName the name of the attribute to look up
  6700. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6701. with this name
  6702. */
  6703. bool getBoolAttribute (const tchar* const attributeName,
  6704. const bool defaultReturnValue = false) const throw();
  6705. /** Adds a named attribute to the element.
  6706. If the element already contains an attribute with this name, it's value will
  6707. be updated to the new value. If there's no such attribute yet, a new one will
  6708. be added.
  6709. Note that there are other setAttribute() methods that take integers,
  6710. doubles, etc. to make it easy to store numbers.
  6711. @param attributeName the name of the attribute to set
  6712. @param newValue the value to set it to
  6713. @see removeAttribute
  6714. */
  6715. void setAttribute (const tchar* const attributeName,
  6716. const String& newValue) throw();
  6717. /** Adds a named attribute to the element.
  6718. If the element already contains an attribute with this name, it's value will
  6719. be updated to the new value. If there's no such attribute yet, a new one will
  6720. be added.
  6721. Note that there are other setAttribute() methods that take integers,
  6722. doubles, etc. to make it easy to store numbers.
  6723. @param attributeName the name of the attribute to set
  6724. @param newValue the value to set it to
  6725. */
  6726. void setAttribute (const tchar* const attributeName,
  6727. const tchar* const newValue) throw();
  6728. /** Adds a named attribute to the element, setting it to an integer value.
  6729. If the element already contains an attribute with this name, it's value will
  6730. be updated to the new value. If there's no such attribute yet, a new one will
  6731. be added.
  6732. Note that there are other setAttribute() methods that take integers,
  6733. doubles, etc. to make it easy to store numbers.
  6734. @param attributeName the name of the attribute to set
  6735. @param newValue the value to set it to
  6736. */
  6737. void setAttribute (const tchar* const attributeName,
  6738. const int newValue) throw();
  6739. /** Adds a named attribute to the element, setting it to a floating-point value.
  6740. If the element already contains an attribute with this name, it's value will
  6741. be updated to the new value. If there's no such attribute yet, a new one will
  6742. be added.
  6743. Note that there are other setAttribute() methods that take integers,
  6744. doubles, etc. to make it easy to store numbers.
  6745. @param attributeName the name of the attribute to set
  6746. @param newValue the value to set it to
  6747. */
  6748. void setAttribute (const tchar* const attributeName,
  6749. const double newValue) throw();
  6750. /** Removes a named attribute from the element.
  6751. @param attributeName the name of the attribute to remove
  6752. @see removeAllAttributes
  6753. */
  6754. void removeAttribute (const tchar* const attributeName) throw();
  6755. /** Removes all attributes from this element.
  6756. */
  6757. void removeAllAttributes() throw();
  6758. // Child element methods..
  6759. /** Returns the first of this element's sub-elements.
  6760. see getNextElement() for an example of how to iterate the sub-elements.
  6761. @see forEachXmlChildElement
  6762. */
  6763. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6764. /** Returns the next of this element's siblings.
  6765. This can be used for iterating an element's sub-elements, e.g.
  6766. @code
  6767. XmlElement* child = myXmlDocument->getFirstChildElement();
  6768. while (child != 0)
  6769. {
  6770. ...do stuff with this child..
  6771. child = child->getNextElement();
  6772. }
  6773. @endcode
  6774. Note that when iterating the child elements, some of them might be
  6775. text elements as well as XML tags - use isTextElement() to work this
  6776. out.
  6777. Also, it's much easier and neater to use this method indirectly via the
  6778. forEachXmlChildElement macro.
  6779. @returns the sibling element that follows this one, or zero if this is the last
  6780. element in its parent
  6781. @see getNextElement, isTextElement, forEachXmlChildElement
  6782. */
  6783. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6784. /** Returns the next of this element's siblings which has the specified tag
  6785. name.
  6786. This is like getNextElement(), but will scan through the list until it
  6787. finds an element with the given tag name.
  6788. @see getNextElement, forEachXmlChildElementWithTagName
  6789. */
  6790. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6791. /** Returns the number of sub-elements in this element.
  6792. @see getChildElement
  6793. */
  6794. int getNumChildElements() const throw();
  6795. /** Returns the sub-element at a certain index.
  6796. It's not very efficient to iterate the sub-elements by index - see
  6797. getNextElement() for an example of how best to iterate.
  6798. @returns the n'th child of this element, or 0 if the index is out-of-range
  6799. @see getNextElement, isTextElement, getChildByName
  6800. */
  6801. XmlElement* getChildElement (const int index) const throw();
  6802. /** Returns the first sub-element with a given tag-name.
  6803. @param tagNameToLookFor the tag name of the element you want to find
  6804. @returns the first element with this tag name, or 0 if none is found
  6805. @see getNextElement, isTextElement, getChildElement
  6806. */
  6807. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6808. /** Appends an element to this element's list of children.
  6809. Child elements are deleted automatically when their parent is deleted, so
  6810. make sure the object that you pass in will not be deleted by anything else,
  6811. and make sure it's not already the child of another element.
  6812. @see getFirstChildElement, getNextElement, getNumChildElements,
  6813. getChildElement, removeChildElement
  6814. */
  6815. void addChildElement (XmlElement* const newChildElement) throw();
  6816. /** Inserts an element into this element's list of children.
  6817. Child elements are deleted automatically when their parent is deleted, so
  6818. make sure the object that you pass in will not be deleted by anything else,
  6819. and make sure it's not already the child of another element.
  6820. @param newChildNode the element to add
  6821. @param indexToInsertAt the index at which to insert the new element - if this is
  6822. below zero, it will be added to the end of the list
  6823. @see addChildElement, insertChildElement
  6824. */
  6825. void insertChildElement (XmlElement* const newChildNode,
  6826. int indexToInsertAt) throw();
  6827. /** Replaces one of this element's children with another node.
  6828. If the current element passed-in isn't actually a child of this element,
  6829. this will return false and the new one won't be added. Otherwise, the
  6830. existing element will be deleted, replaced with the new one, and it
  6831. will return true.
  6832. */
  6833. bool replaceChildElement (XmlElement* const currentChildElement,
  6834. XmlElement* const newChildNode) throw();
  6835. /** Removes a child element.
  6836. @param childToRemove the child to look for and remove
  6837. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6838. just remove it
  6839. */
  6840. void removeChildElement (XmlElement* const childToRemove,
  6841. const bool shouldDeleteTheChild) throw();
  6842. /** Deletes all the child elements in the element.
  6843. @see removeChildElement, deleteAllChildElementsWithTagName
  6844. */
  6845. void deleteAllChildElements() throw();
  6846. /** Deletes all the child elements with a given tag name.
  6847. @see removeChildElement
  6848. */
  6849. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6850. /** Returns true if the given element is a child of this one. */
  6851. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6852. /** Recursively searches all sub-elements to find one that contains the specified
  6853. child element.
  6854. */
  6855. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6856. /** Sorts the child elements using a comparator.
  6857. This will use a comparator object to sort the elements into order. The object
  6858. passed must have a method of the form:
  6859. @code
  6860. int compareElements (const XmlElement* first, const XmlElement* second);
  6861. @endcode
  6862. ..and this method must return:
  6863. - a value of < 0 if the first comes before the second
  6864. - a value of 0 if the two objects are equivalent
  6865. - a value of > 0 if the second comes before the first
  6866. To improve performance, the compareElements() method can be declared as static or const.
  6867. @param comparator the comparator to use for comparing elements.
  6868. @param retainOrderOfEquivalentItems if this is true, then items
  6869. which the comparator says are equivalent will be
  6870. kept in the order in which they currently appear
  6871. in the array. This is slower to perform, but may
  6872. be important in some cases. If it's false, a faster
  6873. algorithm is used, but equivalent elements may be
  6874. rearranged.
  6875. */
  6876. template <class ElementComparator>
  6877. void sortChildElements (ElementComparator& comparator,
  6878. const bool retainOrderOfEquivalentItems = false) throw()
  6879. {
  6880. const int num = getNumChildElements();
  6881. if (num > 1)
  6882. {
  6883. XmlElement** const elems = getChildElementsAsArray (num);
  6884. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  6885. reorderChildElements (elems, num);
  6886. delete[] elems;
  6887. }
  6888. }
  6889. /** Returns true if this element is a section of text.
  6890. Elements can either be an XML tag element or a secton of text, so this
  6891. is used to find out what kind of element this one is.
  6892. @see getAllText, addTextElement, deleteAllTextElements
  6893. */
  6894. bool isTextElement() const throw();
  6895. /** Returns the text for a text element.
  6896. Note that if you have an element like this:
  6897. @code<xyz>hello</xyz>@endcode
  6898. then calling getText on the "xyz" element won't return "hello", because that is
  6899. actually stored in a special text sub-element inside the xyz element. To get the
  6900. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6901. use getAllSubText() to do this automatically.
  6902. @see isTextElement, getAllSubText, getChildElementAllSubText
  6903. */
  6904. const String getText() const throw();
  6905. /** Sets the text in a text element.
  6906. Note that this is only a valid call if this element is a text element. If it's
  6907. not, then no action will be performed.
  6908. */
  6909. void setText (const String& newText) throw();
  6910. /** Returns all the text from this element's child nodes.
  6911. This iterates all the child elements and when it finds text elements,
  6912. it concatenates their text into a big string which it returns.
  6913. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6914. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6915. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6916. */
  6917. const String getAllSubText() const throw();
  6918. /** Returns all the sub-text of a named child element.
  6919. If there is a child element with the given tag name, this will return
  6920. all of its sub-text (by calling getAllSubText() on it). If there is
  6921. no such child element, this will return the default string passed-in.
  6922. @see getAllSubText
  6923. */
  6924. const String getChildElementAllSubText (const tchar* const childTagName,
  6925. const String& defaultReturnValue) const throw();
  6926. /** Appends a section of text to this element.
  6927. @see isTextElement, getText, getAllSubText
  6928. */
  6929. void addTextElement (const String& text) throw();
  6930. /** Removes all the text elements from this element.
  6931. @see isTextElement, getText, getAllSubText, addTextElement
  6932. */
  6933. void deleteAllTextElements() throw();
  6934. /** Creates a text element that can be added to a parent element.
  6935. */
  6936. static XmlElement* createTextElement (const String& text) throw();
  6937. juce_UseDebuggingNewOperator
  6938. private:
  6939. friend class XmlDocument;
  6940. String tagName;
  6941. XmlElement* firstChildElement;
  6942. XmlElement* nextElement;
  6943. struct XmlAttributeNode
  6944. {
  6945. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6946. XmlAttributeNode (const String& name, const String& value) throw();
  6947. String name, value;
  6948. XmlAttributeNode* next;
  6949. };
  6950. XmlAttributeNode* attributes;
  6951. XmlElement (int) throw(); // for internal use
  6952. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6953. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6954. void writeElementAsText (OutputStream& out,
  6955. const int indentationLevel,
  6956. const int lineWrapLength) const throw();
  6957. XmlElement** getChildElementsAsArray (const int) const throw();
  6958. void reorderChildElements (XmlElement** const, const int) throw();
  6959. };
  6960. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6961. /********* End of inlined file: juce_XmlElement.h *********/
  6962. /**
  6963. A set of named property values, which can be strings, integers, floating point, etc.
  6964. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6965. to load and save types other than strings.
  6966. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6967. messages and saves/loads the list from a file.
  6968. */
  6969. class JUCE_API PropertySet
  6970. {
  6971. public:
  6972. /** Creates an empty PropertySet.
  6973. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6974. case-insensitive way
  6975. */
  6976. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6977. /** Creates a copy of another PropertySet.
  6978. */
  6979. PropertySet (const PropertySet& other) throw();
  6980. /** Copies another PropertySet over this one.
  6981. */
  6982. const PropertySet& operator= (const PropertySet& other) throw();
  6983. /** Destructor. */
  6984. virtual ~PropertySet();
  6985. /** Returns one of the properties as a string.
  6986. If the value isn't found in this set, then this will look for it in a fallback
  6987. property set (if you've specified one with the setFallbackPropertySet() method),
  6988. and if it can't find one there, it'll return the default value passed-in.
  6989. @param keyName the name of the property to retrieve
  6990. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6991. */
  6992. const String getValue (const String& keyName,
  6993. const String& defaultReturnValue = String::empty) const throw();
  6994. /** Returns one of the properties as an integer.
  6995. If the value isn't found in this set, then this will look for it in a fallback
  6996. property set (if you've specified one with the setFallbackPropertySet() method),
  6997. and if it can't find one there, it'll return the default value passed-in.
  6998. @param keyName the name of the property to retrieve
  6999. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7000. */
  7001. int getIntValue (const String& keyName,
  7002. const int defaultReturnValue = 0) const throw();
  7003. /** Returns one of the properties as an double.
  7004. If the value isn't found in this set, then this will look for it in a fallback
  7005. property set (if you've specified one with the setFallbackPropertySet() method),
  7006. and if it can't find one there, it'll return the default value passed-in.
  7007. @param keyName the name of the property to retrieve
  7008. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7009. */
  7010. double getDoubleValue (const String& keyName,
  7011. const double defaultReturnValue = 0.0) const throw();
  7012. /** Returns one of the properties as an boolean.
  7013. The result will be true if the string found for this key name can be parsed as a non-zero
  7014. integer.
  7015. If the value isn't found in this set, then this will look for it in a fallback
  7016. property set (if you've specified one with the setFallbackPropertySet() method),
  7017. and if it can't find one there, it'll return the default value passed-in.
  7018. @param keyName the name of the property to retrieve
  7019. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7020. */
  7021. bool getBoolValue (const String& keyName,
  7022. const bool defaultReturnValue = false) const throw();
  7023. /** Returns one of the properties as an XML element.
  7024. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7025. key isn't found, or if the entry contains an string that isn't valid XML.
  7026. If the value isn't found in this set, then this will look for it in a fallback
  7027. property set (if you've specified one with the setFallbackPropertySet() method),
  7028. and if it can't find one there, it'll return the default value passed-in.
  7029. @param keyName the name of the property to retrieve
  7030. */
  7031. XmlElement* getXmlValue (const String& keyName) const;
  7032. /** Sets a named property as a string.
  7033. @param keyName the name of the property to set. (This mustn't be an empty string)
  7034. @param value the new value to set it to
  7035. */
  7036. void setValue (const String& keyName, const String& value) throw();
  7037. /** Sets a named property as a string.
  7038. @param keyName the name of the property to set. (This mustn't be an empty string)
  7039. @param value the new value to set it to
  7040. */
  7041. void setValue (const String& keyName, const tchar* const value) throw();
  7042. /** Sets a named property to an integer.
  7043. @param keyName the name of the property to set. (This mustn't be an empty string)
  7044. @param value the new value to set it to
  7045. */
  7046. void setValue (const String& keyName, const int value) throw();
  7047. /** Sets a named property to a double.
  7048. @param keyName the name of the property to set. (This mustn't be an empty string)
  7049. @param value the new value to set it to
  7050. */
  7051. void setValue (const String& keyName, const double value) throw();
  7052. /** Sets a named property to a boolean.
  7053. @param keyName the name of the property to set. (This mustn't be an empty string)
  7054. @param value the new value to set it to
  7055. */
  7056. void setValue (const String& keyName, const bool value) throw();
  7057. /** Sets a named property to an XML element.
  7058. @param keyName the name of the property to set. (This mustn't be an empty string)
  7059. @param xml the new element to set it to. If this is zero, the value will be set to
  7060. an empty string
  7061. @see getXmlValue
  7062. */
  7063. void setValue (const String& keyName, const XmlElement* const xml);
  7064. /** Deletes a property.
  7065. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7066. */
  7067. void removeValue (const String& keyName) throw();
  7068. /** Returns true if the properies include the given key. */
  7069. bool containsKey (const String& keyName) const throw();
  7070. /** Removes all values. */
  7071. void clear();
  7072. /** Returns the keys/value pair array containing all the properties. */
  7073. StringPairArray& getAllProperties() throw() { return properties; }
  7074. /** Returns the lock used when reading or writing to this set */
  7075. const CriticalSection& getLock() const throw() { return lock; }
  7076. /** Returns an XML element which encapsulates all the items in this property set.
  7077. The string parameter is the tag name that should be used for the node.
  7078. @see restoreFromXml
  7079. */
  7080. XmlElement* createXml (const String& nodeName) const throw();
  7081. /** Reloads a set of properties that were previously stored as XML.
  7082. The node passed in must have been created by the createXml() method.
  7083. @see createXml
  7084. */
  7085. void restoreFromXml (const XmlElement& xml) throw();
  7086. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7087. set in this one.
  7088. If you set this up to be a pointer to a second property set, then whenever one
  7089. of the getValue() methods fails to find an entry in this set, it will look up that
  7090. value in the fallback set, and if it finds it, it will return that.
  7091. Make sure that you don't delete the fallback set while it's still being used by
  7092. another set! To remove the fallback set, just call this method with a null pointer.
  7093. @see getFallbackPropertySet
  7094. */
  7095. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7096. /** Returns the fallback property set.
  7097. @see setFallbackPropertySet
  7098. */
  7099. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7100. juce_UseDebuggingNewOperator
  7101. protected:
  7102. /** Subclasses can override this to be told when one of the properies has been changed.
  7103. */
  7104. virtual void propertyChanged();
  7105. private:
  7106. StringPairArray properties;
  7107. PropertySet* fallbackProperties;
  7108. CriticalSection lock;
  7109. bool ignoreCaseOfKeys;
  7110. };
  7111. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7112. /********* End of inlined file: juce_PropertySet.h *********/
  7113. #endif
  7114. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7115. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7116. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7117. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7118. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7119. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7120. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7121. /**
  7122. Adds reference-counting to an object.
  7123. To add reference-counting to a class, derive it from this class, and
  7124. use the ReferenceCountedObjectPtr class to point to it.
  7125. e.g. @code
  7126. class MyClass : public ReferenceCountedObject
  7127. {
  7128. void foo();
  7129. // This is a neat way of declaring a typedef for a pointer class,
  7130. // rather than typing out the full templated name each time..
  7131. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7132. };
  7133. MyClass::Ptr p = new MyClass();
  7134. MyClass::Ptr p2 = p;
  7135. p = 0;
  7136. p2->foo();
  7137. @endcode
  7138. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7139. careful not to delete the object manually.
  7140. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7141. */
  7142. class JUCE_API ReferenceCountedObject
  7143. {
  7144. public:
  7145. /** Increments the object's reference count.
  7146. This is done automatically by the smart pointer, but is public just
  7147. in case it's needed for nefarious purposes.
  7148. */
  7149. inline void incReferenceCount() throw()
  7150. {
  7151. atomicIncrement (refCounts);
  7152. jassert (refCounts > 0);
  7153. }
  7154. /** Decreases the object's reference count.
  7155. If the count gets to zero, the object will be deleted.
  7156. */
  7157. inline void decReferenceCount() throw()
  7158. {
  7159. jassert (refCounts > 0);
  7160. if (atomicDecrementAndReturn (refCounts) == 0)
  7161. delete this;
  7162. }
  7163. /** Returns the object's current reference count. */
  7164. inline int getReferenceCount() const throw()
  7165. {
  7166. return refCounts;
  7167. }
  7168. protected:
  7169. /** Creates the reference-counted object (with an initial ref count of zero). */
  7170. ReferenceCountedObject()
  7171. : refCounts (0)
  7172. {
  7173. }
  7174. /** Destructor. */
  7175. virtual ~ReferenceCountedObject()
  7176. {
  7177. // it's dangerous to delete an object that's still referenced by something else!
  7178. jassert (refCounts == 0);
  7179. }
  7180. private:
  7181. int refCounts;
  7182. };
  7183. /**
  7184. Used to point to an object of type ReferenceCountedObject.
  7185. It's wise to use a typedef instead of typing out the templated name
  7186. each time - e.g.
  7187. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7188. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7189. */
  7190. template <class ReferenceCountedObjectClass>
  7191. class ReferenceCountedObjectPtr
  7192. {
  7193. public:
  7194. /** Creates a pointer to a null object. */
  7195. inline ReferenceCountedObjectPtr() throw()
  7196. : referencedObject (0)
  7197. {
  7198. }
  7199. /** Creates a pointer to an object.
  7200. This will increment the object's reference-count if it is non-null.
  7201. */
  7202. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7203. : referencedObject (refCountedObject)
  7204. {
  7205. if (refCountedObject != 0)
  7206. refCountedObject->incReferenceCount();
  7207. }
  7208. /** Copies another pointer.
  7209. This will increment the object's reference-count (if it is non-null).
  7210. */
  7211. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7212. : referencedObject (other.referencedObject)
  7213. {
  7214. if (referencedObject != 0)
  7215. referencedObject->incReferenceCount();
  7216. }
  7217. /** Changes this pointer to point at a different object.
  7218. The reference count of the old object is decremented, and it might be
  7219. deleted if it hits zero. The new object's count is incremented.
  7220. */
  7221. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7222. {
  7223. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7224. if (newObject != referencedObject)
  7225. {
  7226. if (newObject != 0)
  7227. newObject->incReferenceCount();
  7228. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7229. referencedObject = newObject;
  7230. if (oldObject != 0)
  7231. oldObject->decReferenceCount();
  7232. }
  7233. return *this;
  7234. }
  7235. /** Changes this pointer to point at a different object.
  7236. The reference count of the old object is decremented, and it might be
  7237. deleted if it hits zero. The new object's count is incremented.
  7238. */
  7239. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7240. {
  7241. if (referencedObject != newObject)
  7242. {
  7243. if (newObject != 0)
  7244. newObject->incReferenceCount();
  7245. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7246. referencedObject = newObject;
  7247. if (oldObject != 0)
  7248. oldObject->decReferenceCount();
  7249. }
  7250. return *this;
  7251. }
  7252. /** Destructor.
  7253. This will decrement the object's reference-count, and may delete it if it
  7254. gets to zero.
  7255. */
  7256. inline ~ReferenceCountedObjectPtr()
  7257. {
  7258. if (referencedObject != 0)
  7259. referencedObject->decReferenceCount();
  7260. }
  7261. /** Returns the object that this pointer references.
  7262. The pointer returned may be zero, of course.
  7263. */
  7264. inline operator ReferenceCountedObjectClass*() const throw()
  7265. {
  7266. return referencedObject;
  7267. }
  7268. /** Returns true if this pointer refers to the given object. */
  7269. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7270. {
  7271. return referencedObject == object;
  7272. }
  7273. /** Returns true if this pointer doesn't refer to the given object. */
  7274. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7275. {
  7276. return referencedObject != object;
  7277. }
  7278. // the -> operator is called on the referenced object
  7279. inline ReferenceCountedObjectClass* operator->() const throw()
  7280. {
  7281. return referencedObject;
  7282. }
  7283. private:
  7284. ReferenceCountedObjectClass* referencedObject;
  7285. };
  7286. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7287. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7288. /**
  7289. Holds a list of objects derived from ReferenceCountedObject.
  7290. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7291. and takes care of incrementing and decrementing their ref counts when they
  7292. are added and removed from the array.
  7293. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7294. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7295. @see Array, OwnedArray, StringArray
  7296. */
  7297. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7298. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7299. {
  7300. public:
  7301. /** Creates an empty array.
  7302. @param granularity this is the size of increment by which the internal storage
  7303. used by the array will grow. Only change it from the default if you know the
  7304. array is going to be very big and needs to be able to grow efficiently.
  7305. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7306. */
  7307. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7308. : ArrayAllocationBase <ObjectClass*> (granularity),
  7309. numUsed (0)
  7310. {
  7311. }
  7312. /** Creates a copy of another array */
  7313. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7314. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  7315. numUsed (other.numUsed)
  7316. {
  7317. other.lockArray();
  7318. this->setAllocatedSize (numUsed);
  7319. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7320. for (int i = numUsed; --i >= 0;)
  7321. if (this->elements[i] != 0)
  7322. this->elements[i]->incReferenceCount();
  7323. other.unlockArray();
  7324. }
  7325. /** Copies another array into this one.
  7326. Any existing objects in this array will first be released.
  7327. */
  7328. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7329. {
  7330. if (this != &other)
  7331. {
  7332. other.lockArray();
  7333. lock.enter();
  7334. clear();
  7335. this->granularity = other.granularity;
  7336. this->ensureAllocatedSize (other.numUsed);
  7337. numUsed = other.numUsed;
  7338. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7339. minimiseStorageOverheads();
  7340. for (int i = numUsed; --i >= 0;)
  7341. if (this->elements[i] != 0)
  7342. this->elements[i]->incReferenceCount();
  7343. lock.exit();
  7344. other.unlockArray();
  7345. }
  7346. return *this;
  7347. }
  7348. /** Destructor.
  7349. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7350. */
  7351. ~ReferenceCountedArray()
  7352. {
  7353. clear();
  7354. }
  7355. /** Removes all objects from the array.
  7356. Any objects in the array that are not referenced from elsewhere will be deleted.
  7357. */
  7358. void clear()
  7359. {
  7360. lock.enter();
  7361. while (numUsed > 0)
  7362. if (this->elements [--numUsed] != 0)
  7363. this->elements [numUsed]->decReferenceCount();
  7364. jassert (numUsed == 0);
  7365. this->setAllocatedSize (0);
  7366. lock.exit();
  7367. }
  7368. /** Returns the current number of objects in the array. */
  7369. inline int size() const throw()
  7370. {
  7371. return numUsed;
  7372. }
  7373. /** Returns a pointer to the object at this index in the array.
  7374. If the index is out-of-range, this will return a null pointer, (and
  7375. it could be null anyway, because it's ok for the array to hold null
  7376. pointers as well as objects).
  7377. @see getUnchecked
  7378. */
  7379. inline ObjectClass* operator[] (const int index) const throw()
  7380. {
  7381. lock.enter();
  7382. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  7383. ? this->elements [index]
  7384. : (ObjectClass*) 0;
  7385. lock.exit();
  7386. return result;
  7387. }
  7388. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7389. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7390. it can be used when you're sure the index if always going to be legal.
  7391. */
  7392. inline ObjectClass* getUnchecked (const int index) const throw()
  7393. {
  7394. lock.enter();
  7395. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7396. ObjectClass* const result = this->elements [index];
  7397. lock.exit();
  7398. return result;
  7399. }
  7400. /** Returns a pointer to the first object in the array.
  7401. This will return a null pointer if the array's empty.
  7402. @see getLast
  7403. */
  7404. inline ObjectClass* getFirst() const throw()
  7405. {
  7406. lock.enter();
  7407. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  7408. : (ObjectClass*) 0;
  7409. lock.exit();
  7410. return result;
  7411. }
  7412. /** Returns a pointer to the last object in the array.
  7413. This will return a null pointer if the array's empty.
  7414. @see getFirst
  7415. */
  7416. inline ObjectClass* getLast() const throw()
  7417. {
  7418. lock.enter();
  7419. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  7420. : (ObjectClass*) 0;
  7421. lock.exit();
  7422. return result;
  7423. }
  7424. /** Finds the index of the first occurrence of an object in the array.
  7425. @param objectToLookFor the object to look for
  7426. @returns the index at which the object was found, or -1 if it's not found
  7427. */
  7428. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7429. {
  7430. int result = -1;
  7431. lock.enter();
  7432. ObjectClass** e = this->elements;
  7433. for (int i = numUsed; --i >= 0;)
  7434. {
  7435. if (objectToLookFor == *e)
  7436. {
  7437. result = (int) (e - this->elements);
  7438. break;
  7439. }
  7440. ++e;
  7441. }
  7442. lock.exit();
  7443. return result;
  7444. }
  7445. /** Returns true if the array contains a specified object.
  7446. @param objectToLookFor the object to look for
  7447. @returns true if the object is in the array
  7448. */
  7449. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7450. {
  7451. lock.enter();
  7452. ObjectClass** e = this->elements;
  7453. for (int i = numUsed; --i >= 0;)
  7454. {
  7455. if (objectToLookFor == *e)
  7456. {
  7457. lock.exit();
  7458. return true;
  7459. }
  7460. ++e;
  7461. }
  7462. lock.exit();
  7463. return false;
  7464. }
  7465. /** Appends a new object to the end of the array.
  7466. This will increase the new object's reference count.
  7467. @param newObject the new object to add to the array
  7468. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7469. */
  7470. void add (ObjectClass* const newObject) throw()
  7471. {
  7472. lock.enter();
  7473. this->ensureAllocatedSize (numUsed + 1);
  7474. this->elements [numUsed++] = newObject;
  7475. if (newObject != 0)
  7476. newObject->incReferenceCount();
  7477. lock.exit();
  7478. }
  7479. /** Inserts a new object into the array at the given index.
  7480. If the index is less than 0 or greater than the size of the array, the
  7481. element will be added to the end of the array.
  7482. Otherwise, it will be inserted into the array, moving all the later elements
  7483. along to make room.
  7484. This will increase the new object's reference count.
  7485. @param indexToInsertAt the index at which the new element should be inserted
  7486. @param newObject the new object to add to the array
  7487. @see add, addSorted, addIfNotAlreadyThere, set
  7488. */
  7489. void insert (int indexToInsertAt,
  7490. ObjectClass* const newObject) throw()
  7491. {
  7492. if (indexToInsertAt >= 0)
  7493. {
  7494. lock.enter();
  7495. if (indexToInsertAt > numUsed)
  7496. indexToInsertAt = numUsed;
  7497. this->ensureAllocatedSize (numUsed + 1);
  7498. ObjectClass** const e = this->elements + indexToInsertAt;
  7499. const int numToMove = numUsed - indexToInsertAt;
  7500. if (numToMove > 0)
  7501. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7502. *e = newObject;
  7503. if (newObject != 0)
  7504. newObject->incReferenceCount();
  7505. ++numUsed;
  7506. lock.exit();
  7507. }
  7508. else
  7509. {
  7510. add (newObject);
  7511. }
  7512. }
  7513. /** Appends a new object at the end of the array as long as the array doesn't
  7514. already contain it.
  7515. If the array already contains a matching object, nothing will be done.
  7516. @param newObject the new object to add to the array
  7517. */
  7518. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7519. {
  7520. lock.enter();
  7521. if (! contains (newObject))
  7522. add (newObject);
  7523. lock.exit();
  7524. }
  7525. /** Replaces an object in the array with a different one.
  7526. If the index is less than zero, this method does nothing.
  7527. If the index is beyond the end of the array, the new object is added to the end of the array.
  7528. The object being added has its reference count increased, and if it's replacing
  7529. another object, then that one has its reference count decreased, and may be deleted.
  7530. @param indexToChange the index whose value you want to change
  7531. @param newObject the new value to set for this index.
  7532. @see add, insert, remove
  7533. */
  7534. void set (const int indexToChange,
  7535. ObjectClass* const newObject)
  7536. {
  7537. if (indexToChange >= 0)
  7538. {
  7539. lock.enter();
  7540. if (newObject != 0)
  7541. newObject->incReferenceCount();
  7542. if (indexToChange < numUsed)
  7543. {
  7544. if (this->elements [indexToChange] != 0)
  7545. this->elements [indexToChange]->decReferenceCount();
  7546. this->elements [indexToChange] = newObject;
  7547. }
  7548. else
  7549. {
  7550. this->ensureAllocatedSize (numUsed + 1);
  7551. this->elements [numUsed++] = newObject;
  7552. }
  7553. lock.exit();
  7554. }
  7555. }
  7556. /** Adds elements from another array to the end of this array.
  7557. @param arrayToAddFrom the array from which to copy the elements
  7558. @param startIndex the first element of the other array to start copying from
  7559. @param numElementsToAdd how many elements to add from the other array. If this
  7560. value is negative or greater than the number of available elements,
  7561. all available elements will be copied.
  7562. @see add
  7563. */
  7564. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7565. int startIndex = 0,
  7566. int numElementsToAdd = -1) throw()
  7567. {
  7568. arrayToAddFrom.lockArray();
  7569. lock.enter();
  7570. if (startIndex < 0)
  7571. {
  7572. jassertfalse
  7573. startIndex = 0;
  7574. }
  7575. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7576. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7577. if (numElementsToAdd > 0)
  7578. {
  7579. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  7580. while (--numElementsToAdd >= 0)
  7581. add (arrayToAddFrom.getUnchecked (startIndex++));
  7582. }
  7583. lock.exit();
  7584. arrayToAddFrom.unlockArray();
  7585. }
  7586. /** Inserts a new object into the array assuming that the array is sorted.
  7587. This will use a comparator to find the position at which the new object
  7588. should go. If the array isn't sorted, the behaviour of this
  7589. method will be unpredictable.
  7590. @param comparator the comparator object to use to compare the elements - see the
  7591. sort() method for details about this object's form
  7592. @param newObject the new object to insert to the array
  7593. @see add, sort
  7594. */
  7595. template <class ElementComparator>
  7596. void addSorted (ElementComparator& comparator,
  7597. ObjectClass* newObject) throw()
  7598. {
  7599. lock.enter();
  7600. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  7601. lock.exit();
  7602. }
  7603. /** Removes an object from the array.
  7604. This will remove the object at a given index and move back all the
  7605. subsequent objects to close the gap.
  7606. If the index passed in is out-of-range, nothing will happen.
  7607. The object that is removed will have its reference count decreased,
  7608. and may be deleted if not referenced from elsewhere.
  7609. @param indexToRemove the index of the element to remove
  7610. @see removeObject, removeRange
  7611. */
  7612. void remove (const int indexToRemove)
  7613. {
  7614. lock.enter();
  7615. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7616. {
  7617. ObjectClass** const e = this->elements + indexToRemove;
  7618. if (*e != 0)
  7619. (*e)->decReferenceCount();
  7620. --numUsed;
  7621. const int numberToShift = numUsed - indexToRemove;
  7622. if (numberToShift > 0)
  7623. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7624. if ((numUsed << 1) < this->numAllocated)
  7625. minimiseStorageOverheads();
  7626. }
  7627. lock.exit();
  7628. }
  7629. /** Removes the first occurrence of a specified object from the array.
  7630. If the item isn't found, no action is taken. If it is found, it is
  7631. removed and has its reference count decreased.
  7632. @param objectToRemove the object to try to remove
  7633. @see remove, removeRange
  7634. */
  7635. void removeObject (ObjectClass* const objectToRemove)
  7636. {
  7637. lock.enter();
  7638. remove (indexOf (objectToRemove));
  7639. lock.exit();
  7640. }
  7641. /** Removes a range of objects from the array.
  7642. This will remove a set of objects, starting from the given index,
  7643. and move any subsequent elements down to close the gap.
  7644. If the range extends beyond the bounds of the array, it will
  7645. be safely clipped to the size of the array.
  7646. The objects that are removed will have their reference counts decreased,
  7647. and may be deleted if not referenced from elsewhere.
  7648. @param startIndex the index of the first object to remove
  7649. @param numberToRemove how many objects should be removed
  7650. @see remove, removeObject
  7651. */
  7652. void removeRange (const int startIndex,
  7653. const int numberToRemove)
  7654. {
  7655. lock.enter();
  7656. const int start = jlimit (0, numUsed, startIndex);
  7657. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7658. if (end > start)
  7659. {
  7660. int i;
  7661. for (i = start; i < end; ++i)
  7662. {
  7663. if (this->elements[i] != 0)
  7664. {
  7665. this->elements[i]->decReferenceCount();
  7666. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7667. }
  7668. }
  7669. const int rangeSize = end - start;
  7670. ObjectClass** e = this->elements + start;
  7671. i = numUsed - end;
  7672. numUsed -= rangeSize;
  7673. while (--i >= 0)
  7674. {
  7675. *e = e [rangeSize];
  7676. ++e;
  7677. }
  7678. if ((numUsed << 1) < this->numAllocated)
  7679. minimiseStorageOverheads();
  7680. }
  7681. lock.exit();
  7682. }
  7683. /** Removes the last n objects from the array.
  7684. The objects that are removed will have their reference counts decreased,
  7685. and may be deleted if not referenced from elsewhere.
  7686. @param howManyToRemove how many objects to remove from the end of the array
  7687. @see remove, removeObject, removeRange
  7688. */
  7689. void removeLast (int howManyToRemove = 1)
  7690. {
  7691. lock.enter();
  7692. if (howManyToRemove > numUsed)
  7693. howManyToRemove = numUsed;
  7694. while (--howManyToRemove >= 0)
  7695. remove (numUsed - 1);
  7696. lock.exit();
  7697. }
  7698. /** Swaps a pair of objects in the array.
  7699. If either of the indexes passed in is out-of-range, nothing will happen,
  7700. otherwise the two objects at these positions will be exchanged.
  7701. */
  7702. void swap (const int index1,
  7703. const int index2) throw()
  7704. {
  7705. lock.enter();
  7706. if (((unsigned int) index1) < (unsigned int) numUsed
  7707. && ((unsigned int) index2) < (unsigned int) numUsed)
  7708. {
  7709. swapVariables (this->elements [index1],
  7710. this->elements [index2]);
  7711. }
  7712. lock.exit();
  7713. }
  7714. /** Moves one of the objects to a different position.
  7715. This will move the object to a specified index, shuffling along
  7716. any intervening elements as required.
  7717. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7718. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7719. @param currentIndex the index of the object to be moved. If this isn't a
  7720. valid index, then nothing will be done
  7721. @param newIndex the index at which you'd like this object to end up. If this
  7722. is less than zero, it will be moved to the end of the array
  7723. */
  7724. void move (const int currentIndex,
  7725. int newIndex) throw()
  7726. {
  7727. if (currentIndex != newIndex)
  7728. {
  7729. lock.enter();
  7730. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7731. {
  7732. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7733. newIndex = numUsed - 1;
  7734. ObjectClass* const value = this->elements [currentIndex];
  7735. if (newIndex > currentIndex)
  7736. {
  7737. memmove (this->elements + currentIndex,
  7738. this->elements + currentIndex + 1,
  7739. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7740. }
  7741. else
  7742. {
  7743. memmove (this->elements + newIndex + 1,
  7744. this->elements + newIndex,
  7745. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7746. }
  7747. this->elements [newIndex] = value;
  7748. }
  7749. lock.exit();
  7750. }
  7751. }
  7752. /** Compares this array to another one.
  7753. @returns true only if the other array contains the same objects in the same order
  7754. */
  7755. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7756. {
  7757. other.lockArray();
  7758. lock.enter();
  7759. bool result = numUsed == other.numUsed;
  7760. if (result)
  7761. {
  7762. for (int i = numUsed; --i >= 0;)
  7763. {
  7764. if (this->elements [i] != other.elements [i])
  7765. {
  7766. result = false;
  7767. break;
  7768. }
  7769. }
  7770. }
  7771. lock.exit();
  7772. other.unlockArray();
  7773. return result;
  7774. }
  7775. /** Compares this array to another one.
  7776. @see operator==
  7777. */
  7778. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7779. {
  7780. return ! operator== (other);
  7781. }
  7782. /** Sorts the elements in the array.
  7783. This will use a comparator object to sort the elements into order. The object
  7784. passed must have a method of the form:
  7785. @code
  7786. int compareElements (ElementType first, ElementType second);
  7787. @endcode
  7788. ..and this method must return:
  7789. - a value of < 0 if the first comes before the second
  7790. - a value of 0 if the two objects are equivalent
  7791. - a value of > 0 if the second comes before the first
  7792. To improve performance, the compareElements() method can be declared as static or const.
  7793. @param comparator the comparator to use for comparing elements.
  7794. @param retainOrderOfEquivalentItems if this is true, then items
  7795. which the comparator says are equivalent will be
  7796. kept in the order in which they currently appear
  7797. in the array. This is slower to perform, but may
  7798. be important in some cases. If it's false, a faster
  7799. algorithm is used, but equivalent elements may be
  7800. rearranged.
  7801. @see sortArray
  7802. */
  7803. template <class ElementComparator>
  7804. void sort (ElementComparator& comparator,
  7805. const bool retainOrderOfEquivalentItems = false) const throw()
  7806. {
  7807. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7808. // avoids getting warning messages about the parameter being unused
  7809. lock.enter();
  7810. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7811. lock.exit();
  7812. }
  7813. /** Reduces the amount of storage being used by the array.
  7814. Arrays typically allocate slightly more storage than they need, and after
  7815. removing elements, they may have quite a lot of unused space allocated.
  7816. This method will reduce the amount of allocated storage to a minimum.
  7817. */
  7818. void minimiseStorageOverheads() throw()
  7819. {
  7820. lock.enter();
  7821. if (numUsed == 0)
  7822. {
  7823. this->setAllocatedSize (0);
  7824. }
  7825. else
  7826. {
  7827. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  7828. if (newAllocation < this->numAllocated)
  7829. this->setAllocatedSize (newAllocation);
  7830. }
  7831. lock.exit();
  7832. }
  7833. /** Locks the array's CriticalSection.
  7834. Of course if the type of section used is a DummyCriticalSection, this won't
  7835. have any effect.
  7836. @see unlockArray
  7837. */
  7838. void lockArray() const throw()
  7839. {
  7840. lock.enter();
  7841. }
  7842. /** Unlocks the array's CriticalSection.
  7843. Of course if the type of section used is a DummyCriticalSection, this won't
  7844. have any effect.
  7845. @see lockArray
  7846. */
  7847. void unlockArray() const throw()
  7848. {
  7849. lock.exit();
  7850. }
  7851. juce_UseDebuggingNewOperator
  7852. private:
  7853. int numUsed;
  7854. TypeOfCriticalSectionToUse lock;
  7855. };
  7856. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7857. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7858. #endif
  7859. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7860. #endif
  7861. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7862. /********* Start of inlined file: juce_SortedSet.h *********/
  7863. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7864. #define __JUCE_SORTEDSET_JUCEHEADER__
  7865. #if JUCE_MSVC
  7866. #pragma warning (push)
  7867. #pragma warning (disable: 4512)
  7868. #endif
  7869. /**
  7870. Holds a set of unique primitive objects, such as ints or doubles.
  7871. A set can only hold one item with a given value, so if for example it's a
  7872. set of integers, attempting to add the same integer twice will do nothing
  7873. the second time.
  7874. Internally, the list of items is kept sorted (which means that whatever
  7875. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7876. to determine the order), and searching the set for known values is very fast
  7877. because it uses a binary-chop method.
  7878. Note that if you're using a class or struct as the element type, it must be
  7879. capable of being copied or moved with a straightforward memcpy, rather than
  7880. needing construction and destruction code.
  7881. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7882. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7883. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7884. */
  7885. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7886. class SortedSet : private ArrayAllocationBase <ElementType>
  7887. {
  7888. public:
  7889. /** Creates an empty set.
  7890. @param granularity this is the size of increment by which the internal storage
  7891. used by the array will grow. Only change it from the default if you know the
  7892. array is going to be very big and needs to be able to grow efficiently.
  7893. @see ArrayAllocationBase
  7894. */
  7895. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7896. : ArrayAllocationBase <ElementType> (granularity),
  7897. numUsed (0)
  7898. {
  7899. }
  7900. /** Creates a copy of another set.
  7901. @param other the set to copy
  7902. */
  7903. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7904. : ArrayAllocationBase <ElementType> (other.granularity)
  7905. {
  7906. other.lockSet();
  7907. numUsed = other.numUsed;
  7908. setAllocatedSize (other.numUsed);
  7909. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7910. other.unlockSet();
  7911. }
  7912. /** Destructor. */
  7913. ~SortedSet() throw()
  7914. {
  7915. }
  7916. /** Copies another set over this one.
  7917. @param other the set to copy
  7918. */
  7919. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7920. {
  7921. if (this != &other)
  7922. {
  7923. other.lockSet();
  7924. lock.enter();
  7925. this->granularity = other.granularity;
  7926. ensureAllocatedSize (other.size());
  7927. numUsed = other.numUsed;
  7928. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7929. minimiseStorageOverheads();
  7930. lock.exit();
  7931. other.unlockSet();
  7932. }
  7933. return *this;
  7934. }
  7935. /** Compares this set to another one.
  7936. Two sets are considered equal if they both contain the same set of
  7937. elements.
  7938. @param other the other set to compare with
  7939. */
  7940. bool operator== (const SortedSet<ElementType>& other) const throw()
  7941. {
  7942. lock.enter();
  7943. if (numUsed != other.numUsed)
  7944. {
  7945. lock.exit();
  7946. return false;
  7947. }
  7948. for (int i = numUsed; --i >= 0;)
  7949. {
  7950. if (this->elements [i] != other.elements [i])
  7951. {
  7952. lock.exit();
  7953. return false;
  7954. }
  7955. }
  7956. lock.exit();
  7957. return true;
  7958. }
  7959. /** Compares this set to another one.
  7960. Two sets are considered equal if they both contain the same set of
  7961. elements.
  7962. @param other the other set to compare with
  7963. */
  7964. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7965. {
  7966. return ! operator== (other);
  7967. }
  7968. /** Removes all elements from the set.
  7969. This will remove all the elements, and free any storage that the set is
  7970. using. To clear it without freeing the storage, use the clearQuick()
  7971. method instead.
  7972. @see clearQuick
  7973. */
  7974. void clear() throw()
  7975. {
  7976. lock.enter();
  7977. this->setAllocatedSize (0);
  7978. numUsed = 0;
  7979. lock.exit();
  7980. }
  7981. /** Removes all elements from the set without freeing the array's allocated storage.
  7982. @see clear
  7983. */
  7984. void clearQuick() throw()
  7985. {
  7986. lock.enter();
  7987. numUsed = 0;
  7988. lock.exit();
  7989. }
  7990. /** Returns the current number of elements in the set.
  7991. */
  7992. inline int size() const throw()
  7993. {
  7994. return numUsed;
  7995. }
  7996. /** Returns one of the elements in the set.
  7997. If the index passed in is beyond the range of valid elements, this
  7998. will return zero.
  7999. If you're certain that the index will always be a valid element, you
  8000. can call getUnchecked() instead, which is faster.
  8001. @param index the index of the element being requested (0 is the first element in the set)
  8002. @see getUnchecked, getFirst, getLast
  8003. */
  8004. inline ElementType operator[] (const int index) const throw()
  8005. {
  8006. lock.enter();
  8007. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8008. ? this->elements [index]
  8009. : (ElementType) 0;
  8010. lock.exit();
  8011. return result;
  8012. }
  8013. /** Returns one of the elements in the set, without checking the index passed in.
  8014. Unlike the operator[] method, this will try to return an element without
  8015. checking that the index is within the bounds of the set, so should only
  8016. be used when you're confident that it will always be a valid index.
  8017. @param index the index of the element being requested (0 is the first element in the set)
  8018. @see operator[], getFirst, getLast
  8019. */
  8020. inline ElementType getUnchecked (const int index) const throw()
  8021. {
  8022. lock.enter();
  8023. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8024. const ElementType result = this->elements [index];
  8025. lock.exit();
  8026. return result;
  8027. }
  8028. /** Returns the first element in the set, or 0 if the set is empty.
  8029. @see operator[], getUnchecked, getLast
  8030. */
  8031. inline ElementType getFirst() const throw()
  8032. {
  8033. lock.enter();
  8034. const ElementType result = (numUsed > 0) ? this->elements [0]
  8035. : (ElementType) 0;
  8036. lock.exit();
  8037. return result;
  8038. }
  8039. /** Returns the last element in the set, or 0 if the set is empty.
  8040. @see operator[], getUnchecked, getFirst
  8041. */
  8042. inline ElementType getLast() const throw()
  8043. {
  8044. lock.enter();
  8045. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8046. : (ElementType) 0;
  8047. lock.exit();
  8048. return result;
  8049. }
  8050. /** Finds the index of the first element which matches the value passed in.
  8051. This will search the set for the given object, and return the index
  8052. of its first occurrence. If the object isn't found, the method will return -1.
  8053. @param elementToLookFor the value or object to look for
  8054. @returns the index of the object, or -1 if it's not found
  8055. */
  8056. int indexOf (const ElementType elementToLookFor) const throw()
  8057. {
  8058. lock.enter();
  8059. int start = 0;
  8060. int end = numUsed;
  8061. for (;;)
  8062. {
  8063. if (start >= end)
  8064. {
  8065. lock.exit();
  8066. return -1;
  8067. }
  8068. else if (elementToLookFor == this->elements [start])
  8069. {
  8070. lock.exit();
  8071. return start;
  8072. }
  8073. else
  8074. {
  8075. const int halfway = (start + end) >> 1;
  8076. if (halfway == start)
  8077. {
  8078. lock.exit();
  8079. return -1;
  8080. }
  8081. else if (elementToLookFor >= this->elements [halfway])
  8082. start = halfway;
  8083. else
  8084. end = halfway;
  8085. }
  8086. }
  8087. }
  8088. /** Returns true if the set contains at least one occurrence of an object.
  8089. @param elementToLookFor the value or object to look for
  8090. @returns true if the item is found
  8091. */
  8092. bool contains (const ElementType elementToLookFor) const throw()
  8093. {
  8094. lock.enter();
  8095. int start = 0;
  8096. int end = numUsed;
  8097. for (;;)
  8098. {
  8099. if (start >= end)
  8100. {
  8101. lock.exit();
  8102. return false;
  8103. }
  8104. else if (elementToLookFor == this->elements [start])
  8105. {
  8106. lock.exit();
  8107. return true;
  8108. }
  8109. else
  8110. {
  8111. const int halfway = (start + end) >> 1;
  8112. if (halfway == start)
  8113. {
  8114. lock.exit();
  8115. return false;
  8116. }
  8117. else if (elementToLookFor >= this->elements [halfway])
  8118. start = halfway;
  8119. else
  8120. end = halfway;
  8121. }
  8122. }
  8123. }
  8124. /** Adds a new element to the set, (as long as it's not already in there).
  8125. @param newElement the new object to add to the set
  8126. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8127. */
  8128. void add (const ElementType newElement) throw()
  8129. {
  8130. lock.enter();
  8131. int start = 0;
  8132. int end = numUsed;
  8133. for (;;)
  8134. {
  8135. if (start >= end)
  8136. {
  8137. jassert (start <= end);
  8138. insertInternal (start, newElement);
  8139. break;
  8140. }
  8141. else if (newElement == this->elements [start])
  8142. {
  8143. break;
  8144. }
  8145. else
  8146. {
  8147. const int halfway = (start + end) >> 1;
  8148. if (halfway == start)
  8149. {
  8150. if (newElement >= this->elements [halfway])
  8151. insertInternal (start + 1, newElement);
  8152. else
  8153. insertInternal (start, newElement);
  8154. break;
  8155. }
  8156. else if (newElement >= this->elements [halfway])
  8157. start = halfway;
  8158. else
  8159. end = halfway;
  8160. }
  8161. }
  8162. lock.exit();
  8163. }
  8164. /** Adds elements from an array to this set.
  8165. @param elementsToAdd the array of elements to add
  8166. @param numElementsToAdd how many elements are in this other array
  8167. @see add
  8168. */
  8169. void addArray (const ElementType* elementsToAdd,
  8170. int numElementsToAdd) throw()
  8171. {
  8172. lock.enter();
  8173. while (--numElementsToAdd >= 0)
  8174. add (*elementsToAdd++);
  8175. lock.exit();
  8176. }
  8177. /** Adds elements from another set to this one.
  8178. @param setToAddFrom the set from which to copy the elements
  8179. @param startIndex the first element of the other set to start copying from
  8180. @param numElementsToAdd how many elements to add from the other set. If this
  8181. value is negative or greater than the number of available elements,
  8182. all available elements will be copied.
  8183. @see add
  8184. */
  8185. template <class OtherSetType>
  8186. void addSet (const OtherSetType& setToAddFrom,
  8187. int startIndex = 0,
  8188. int numElementsToAdd = -1) throw()
  8189. {
  8190. setToAddFrom.lockSet();
  8191. lock.enter();
  8192. jassert (this != &setToAddFrom);
  8193. if (this != &setToAddFrom)
  8194. {
  8195. if (startIndex < 0)
  8196. {
  8197. jassertfalse
  8198. startIndex = 0;
  8199. }
  8200. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8201. numElementsToAdd = setToAddFrom.size() - startIndex;
  8202. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8203. }
  8204. lock.exit();
  8205. setToAddFrom.unlockSet();
  8206. }
  8207. /** Removes an element from the set.
  8208. This will remove the element at a given index.
  8209. If the index passed in is out-of-range, nothing will happen.
  8210. @param indexToRemove the index of the element to remove
  8211. @returns the element that has been removed
  8212. @see removeValue, removeRange
  8213. */
  8214. ElementType remove (const int indexToRemove) throw()
  8215. {
  8216. lock.enter();
  8217. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8218. {
  8219. --numUsed;
  8220. ElementType* const e = this->elements + indexToRemove;
  8221. ElementType const removed = *e;
  8222. const int numberToShift = numUsed - indexToRemove;
  8223. if (numberToShift > 0)
  8224. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8225. if ((numUsed << 1) < this->numAllocated)
  8226. minimiseStorageOverheads();
  8227. lock.exit();
  8228. return removed;
  8229. }
  8230. else
  8231. {
  8232. lock.exit();
  8233. return 0;
  8234. }
  8235. }
  8236. /** Removes an item from the set.
  8237. This will remove the given element from the set, if it's there.
  8238. @param valueToRemove the object to try to remove
  8239. @see remove, removeRange
  8240. */
  8241. void removeValue (const ElementType valueToRemove) throw()
  8242. {
  8243. lock.enter();
  8244. remove (indexOf (valueToRemove));
  8245. lock.exit();
  8246. }
  8247. /** Removes any elements which are also in another set.
  8248. @param otherSet the other set in which to look for elements to remove
  8249. @see removeValuesNotIn, remove, removeValue, removeRange
  8250. */
  8251. template <class OtherSetType>
  8252. void removeValuesIn (const OtherSetType& otherSet) throw()
  8253. {
  8254. otherSet.lockSet();
  8255. lock.enter();
  8256. if (this == &otherSet)
  8257. {
  8258. clear();
  8259. }
  8260. else
  8261. {
  8262. if (otherSet.size() > 0)
  8263. {
  8264. for (int i = numUsed; --i >= 0;)
  8265. if (otherSet.contains (this->elements [i]))
  8266. remove (i);
  8267. }
  8268. }
  8269. lock.exit();
  8270. otherSet.unlockSet();
  8271. }
  8272. /** Removes any elements which are not found in another set.
  8273. Only elements which occur in this other set will be retained.
  8274. @param otherSet the set in which to look for elements NOT to remove
  8275. @see removeValuesIn, remove, removeValue, removeRange
  8276. */
  8277. template <class OtherSetType>
  8278. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8279. {
  8280. otherSet.lockSet();
  8281. lock.enter();
  8282. if (this != &otherSet)
  8283. {
  8284. if (otherSet.size() <= 0)
  8285. {
  8286. clear();
  8287. }
  8288. else
  8289. {
  8290. for (int i = numUsed; --i >= 0;)
  8291. if (! otherSet.contains (this->elements [i]))
  8292. remove (i);
  8293. }
  8294. }
  8295. lock.exit();
  8296. otherSet.lockSet();
  8297. }
  8298. /** Reduces the amount of storage being used by the set.
  8299. Sets typically allocate slightly more storage than they need, and after
  8300. removing elements, they may have quite a lot of unused space allocated.
  8301. This method will reduce the amount of allocated storage to a minimum.
  8302. */
  8303. void minimiseStorageOverheads() throw()
  8304. {
  8305. lock.enter();
  8306. if (numUsed == 0)
  8307. {
  8308. this->setAllocatedSize (0);
  8309. }
  8310. else
  8311. {
  8312. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8313. if (newAllocation < this->numAllocated)
  8314. this->setAllocatedSize (newAllocation);
  8315. }
  8316. lock.exit();
  8317. }
  8318. /** Locks the set's CriticalSection.
  8319. Of course if the type of section used is a DummyCriticalSection, this won't
  8320. have any effect.
  8321. @see unlockSet
  8322. */
  8323. void lockSet() const throw()
  8324. {
  8325. lock.enter();
  8326. }
  8327. /** Unlocks the set's CriticalSection.
  8328. Of course if the type of section used is a DummyCriticalSection, this won't
  8329. have any effect.
  8330. @see lockSet
  8331. */
  8332. void unlockSet() const throw()
  8333. {
  8334. lock.exit();
  8335. }
  8336. juce_UseDebuggingNewOperator
  8337. private:
  8338. int numUsed;
  8339. TypeOfCriticalSectionToUse lock;
  8340. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8341. {
  8342. this->ensureAllocatedSize (numUsed + 1);
  8343. ElementType* const insertPos = this->elements + indexToInsertAt;
  8344. const int numberToMove = numUsed - indexToInsertAt;
  8345. if (numberToMove > 0)
  8346. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8347. *insertPos = newElement;
  8348. ++numUsed;
  8349. }
  8350. };
  8351. #if JUCE_MSVC
  8352. #pragma warning (pop)
  8353. #endif
  8354. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8355. /********* End of inlined file: juce_SortedSet.h *********/
  8356. #endif
  8357. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8358. /********* Start of inlined file: juce_SparseSet.h *********/
  8359. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8360. #define __JUCE_SPARSESET_JUCEHEADER__
  8361. /**
  8362. Holds a set of primitive values, storing them as a set of ranges.
  8363. This container acts like a simple BitArray, but can efficiently hold large
  8364. continguous ranges of values. It's quite a specialised class, mostly useful
  8365. for things like keeping the set of selected rows in a listbox.
  8366. The type used as a template paramter must be an integer type, such as int, short,
  8367. int64, etc.
  8368. */
  8369. template <class Type>
  8370. class SparseSet
  8371. {
  8372. public:
  8373. /** Creates a new empty set. */
  8374. SparseSet() throw()
  8375. {
  8376. }
  8377. /** Creates a copy of another SparseSet. */
  8378. SparseSet (const SparseSet<Type>& other) throw()
  8379. : values (other.values)
  8380. {
  8381. }
  8382. /** Destructor. */
  8383. ~SparseSet() throw()
  8384. {
  8385. }
  8386. /** Clears the set. */
  8387. void clear() throw()
  8388. {
  8389. values.clear();
  8390. }
  8391. /** Checks whether the set is empty.
  8392. This is much quicker than using (size() == 0).
  8393. */
  8394. bool isEmpty() const throw()
  8395. {
  8396. return values.size() == 0;
  8397. }
  8398. /** Returns the number of values in the set.
  8399. Because of the way the data is stored, this method can take longer if there
  8400. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8401. are any items.
  8402. */
  8403. Type size() const throw()
  8404. {
  8405. Type num = 0;
  8406. for (int i = 0; i < values.size(); i += 2)
  8407. num += values[i + 1] - values[i];
  8408. return num;
  8409. }
  8410. /** Returns one of the values in the set.
  8411. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8412. @returns the value at this index, or 0 if it's out-of-range
  8413. */
  8414. Type operator[] (int index) const throw()
  8415. {
  8416. for (int i = 0; i < values.size(); i += 2)
  8417. {
  8418. const Type s = values.getUnchecked(i);
  8419. const Type e = values.getUnchecked(i + 1);
  8420. if (index < e - s)
  8421. return s + index;
  8422. index -= e - s;
  8423. }
  8424. return (Type) 0;
  8425. }
  8426. /** Checks whether a particular value is in the set. */
  8427. bool contains (const Type valueToLookFor) const throw()
  8428. {
  8429. bool on = false;
  8430. for (int i = 0; i < values.size(); ++i)
  8431. {
  8432. if (values.getUnchecked(i) > valueToLookFor)
  8433. return on;
  8434. on = ! on;
  8435. }
  8436. return false;
  8437. }
  8438. /** Returns the number of contiguous blocks of values.
  8439. @see getRange
  8440. */
  8441. int getNumRanges() const throw()
  8442. {
  8443. return values.size() >> 1;
  8444. }
  8445. /** Returns one of the contiguous ranges of values stored.
  8446. @param rangeIndex the index of the range to look up, between 0
  8447. and (getNumRanges() - 1)
  8448. @param startValue on return, the value at the start of the range
  8449. @param numValues on return, the number of values in the range
  8450. @see getTotalRange
  8451. */
  8452. bool getRange (const int rangeIndex,
  8453. Type& startValue,
  8454. Type& numValues) const throw()
  8455. {
  8456. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8457. {
  8458. startValue = values [rangeIndex << 1];
  8459. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8460. return true;
  8461. }
  8462. return false;
  8463. }
  8464. /** Returns the lowest and highest values in the set.
  8465. @see getRange
  8466. */
  8467. bool getTotalRange (Type& lowestValue,
  8468. Type& highestValue) const throw()
  8469. {
  8470. if (values.size() > 0)
  8471. {
  8472. lowestValue = values.getUnchecked (0);
  8473. highestValue = values.getUnchecked (values.size() - 1);
  8474. return true;
  8475. }
  8476. return false;
  8477. }
  8478. /** Adds a range of contiguous values to the set.
  8479. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8480. @param firstValue the start of the range of values to add
  8481. @param numValuesToAdd how many values to add
  8482. */
  8483. void addRange (const Type firstValue,
  8484. const Type numValuesToAdd) throw()
  8485. {
  8486. jassert (numValuesToAdd >= 0);
  8487. if (numValuesToAdd > 0)
  8488. {
  8489. removeRange (firstValue, numValuesToAdd);
  8490. IntegerElementComparator<Type> sorter;
  8491. values.addSorted (sorter, firstValue);
  8492. values.addSorted (sorter, firstValue + numValuesToAdd);
  8493. simplify();
  8494. }
  8495. }
  8496. /** Removes a range of values from the set.
  8497. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8498. @param firstValue the start of the range of values to remove
  8499. @param numValuesToRemove how many values to remove
  8500. */
  8501. void removeRange (const Type firstValue,
  8502. const Type numValuesToRemove) throw()
  8503. {
  8504. jassert (numValuesToRemove >= 0);
  8505. if (numValuesToRemove > 0
  8506. && firstValue < values.getLast())
  8507. {
  8508. const bool onAtStart = contains (firstValue - 1);
  8509. Type lastValue = firstValue + numValuesToRemove;
  8510. if (lastValue < firstValue) // possible if the signed arithmetic wraps around
  8511. lastValue = values.getLast();
  8512. const bool onAtEnd = contains (lastValue);
  8513. for (int i = values.size(); --i >= 0;)
  8514. {
  8515. if (values.getUnchecked(i) >= firstValue
  8516. && values.getUnchecked(i) <= lastValue)
  8517. {
  8518. values.remove (i);
  8519. }
  8520. }
  8521. IntegerElementComparator<Type> sorter;
  8522. if (onAtStart)
  8523. values.addSorted (sorter, firstValue);
  8524. if (onAtEnd)
  8525. values.addSorted (sorter, lastValue);
  8526. simplify();
  8527. }
  8528. }
  8529. /** Does an XOR of the values in a given range. */
  8530. void invertRange (const Type firstValue,
  8531. const Type numValues)
  8532. {
  8533. SparseSet newItems;
  8534. newItems.addRange (firstValue, numValues);
  8535. int i;
  8536. for (i = getNumRanges(); --i >= 0;)
  8537. {
  8538. const int start = values [i << 1];
  8539. const int end = values [(i << 1) + 1];
  8540. newItems.removeRange (start, end);
  8541. }
  8542. removeRange (firstValue, numValues);
  8543. for (i = newItems.getNumRanges(); --i >= 0;)
  8544. {
  8545. const int start = newItems.values [i << 1];
  8546. const int end = newItems.values [(i << 1) + 1];
  8547. addRange (start, end);
  8548. }
  8549. }
  8550. /** Checks whether any part of a given range overlaps any part of this one. */
  8551. bool overlapsRange (const Type firstValue,
  8552. const Type numValues) throw()
  8553. {
  8554. jassert (numValues >= 0);
  8555. if (numValues > 0)
  8556. {
  8557. for (int i = getNumRanges(); --i >= 0;)
  8558. {
  8559. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8560. return false;
  8561. if (firstValue + numValues > values.getUnchecked (i << 1))
  8562. return true;
  8563. }
  8564. }
  8565. return false;
  8566. }
  8567. /** Checks whether the whole of a given range is contained within this one. */
  8568. bool containsRange (const Type firstValue,
  8569. const Type numValues) throw()
  8570. {
  8571. jassert (numValues >= 0);
  8572. if (numValues > 0)
  8573. {
  8574. for (int i = getNumRanges(); --i >= 0;)
  8575. {
  8576. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8577. return false;
  8578. if (firstValue >= values.getUnchecked (i << 1)
  8579. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8580. return true;
  8581. }
  8582. }
  8583. return false;
  8584. }
  8585. bool operator== (const SparseSet<Type>& other) throw()
  8586. {
  8587. return values == other.values;
  8588. }
  8589. bool operator!= (const SparseSet<Type>& other) throw()
  8590. {
  8591. return values != other.values;
  8592. }
  8593. juce_UseDebuggingNewOperator
  8594. private:
  8595. // alternating start/end values of ranges of values that are present.
  8596. Array<Type> values;
  8597. void simplify() throw()
  8598. {
  8599. jassert ((values.size() & 1) == 0);
  8600. for (int i = values.size(); --i > 0;)
  8601. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8602. values.removeRange (i - 1, 2);
  8603. }
  8604. };
  8605. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8606. /********* End of inlined file: juce_SparseSet.h *********/
  8607. #endif
  8608. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  8609. #endif
  8610. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  8611. #endif
  8612. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  8613. #endif
  8614. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8615. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  8616. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8617. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8618. /**
  8619. Searches through a the files in a directory, returning each file that is found.
  8620. A DirectoryIterator will search through a directory and its subdirectories using
  8621. a wildcard filepattern match.
  8622. If you may be finding a large number of files, this is better than
  8623. using File::findChildFiles() because it doesn't block while it finds them
  8624. all, and this is more memory-efficient.
  8625. It can also guess how far it's got using a wildly inaccurate algorithm.
  8626. */
  8627. class JUCE_API DirectoryIterator
  8628. {
  8629. public:
  8630. /** Creates a DirectoryIterator for a given directory.
  8631. After creating one of these, call its next() method to get the
  8632. first file - e.g. @code
  8633. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  8634. while (iter.next())
  8635. {
  8636. File theFileItFound (iter.getFile());
  8637. ... etc
  8638. }
  8639. @endcode
  8640. @param directory the directory to search in
  8641. @param isRecursive whether all the subdirectories should also be searched
  8642. @param wildCard the file pattern to match
  8643. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  8644. whether to look for files, directories, or both.
  8645. */
  8646. DirectoryIterator (const File& directory,
  8647. bool isRecursive,
  8648. const String& wildCard = JUCE_T("*"),
  8649. const int whatToLookFor = File::findFiles) throw();
  8650. /** Destructor. */
  8651. ~DirectoryIterator() throw();
  8652. /** Call this to move the iterator along to the next file.
  8653. @returns true if a file was found (you can then use getFile() to see what it was) - or
  8654. false if there are no more matching files.
  8655. */
  8656. bool next() throw();
  8657. /** Returns the file that the iterator is currently pointing at.
  8658. The result of this call is only valid after a call to next() has returned true.
  8659. */
  8660. const File getFile() const throw();
  8661. /** Returns a guess of how far through the search the iterator has got.
  8662. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  8663. very accurate.
  8664. */
  8665. float getEstimatedProgress() const throw();
  8666. juce_UseDebuggingNewOperator
  8667. private:
  8668. OwnedArray <File> filesFound;
  8669. OwnedArray <File> dirsFound;
  8670. String wildCard;
  8671. int index;
  8672. const int whatToLookFor;
  8673. DirectoryIterator* subIterator;
  8674. DirectoryIterator (const DirectoryIterator&);
  8675. const DirectoryIterator& operator= (const DirectoryIterator&);
  8676. };
  8677. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8678. /********* End of inlined file: juce_DirectoryIterator.h *********/
  8679. #endif
  8680. #ifndef __JUCE_FILE_JUCEHEADER__
  8681. #endif
  8682. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8683. /********* Start of inlined file: juce_FileInputStream.h *********/
  8684. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8685. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8686. /**
  8687. An input stream that reads from a local file.
  8688. @see InputStream, FileOutputStream, File::createInputStream
  8689. */
  8690. class JUCE_API FileInputStream : public InputStream
  8691. {
  8692. public:
  8693. /** Creates a FileInputStream.
  8694. @param fileToRead the file to read from - if the file can't be accessed for some
  8695. reason, then the stream will just contain no data
  8696. */
  8697. FileInputStream (const File& fileToRead);
  8698. /** Destructor. */
  8699. ~FileInputStream();
  8700. const File& getFile() const throw() { return file; }
  8701. int64 getTotalLength();
  8702. int read (void* destBuffer, int maxBytesToRead);
  8703. bool isExhausted();
  8704. int64 getPosition();
  8705. bool setPosition (int64 pos);
  8706. juce_UseDebuggingNewOperator
  8707. private:
  8708. File file;
  8709. void* fileHandle;
  8710. int64 currentPosition, totalSize;
  8711. bool needToSeek;
  8712. };
  8713. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8714. /********* End of inlined file: juce_FileInputStream.h *********/
  8715. #endif
  8716. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8717. /********* Start of inlined file: juce_FileOutputStream.h *********/
  8718. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8719. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8720. /**
  8721. An output stream that writes into a local file.
  8722. @see OutputStream, FileInputStream, File::createOutputStream
  8723. */
  8724. class JUCE_API FileOutputStream : public OutputStream
  8725. {
  8726. public:
  8727. /** Creates a FileOutputStream.
  8728. If the file doesn't exist, it will first be created. If the file can't be
  8729. created or opened, the failedToOpen() method will return
  8730. true.
  8731. If the file already exists when opened, the stream's write-postion will
  8732. be set to the end of the file. To overwrite an existing file,
  8733. use File::deleteFile() before opening the stream, or use setPosition(0)
  8734. after it's opened (although this won't truncate the file).
  8735. It's better to use File::createOutputStream() to create one of these, rather
  8736. than using the class directly.
  8737. */
  8738. FileOutputStream (const File& fileToWriteTo,
  8739. const int bufferSizeToUse = 16384);
  8740. /** Destructor. */
  8741. ~FileOutputStream();
  8742. /** Returns the file that this stream is writing to.
  8743. */
  8744. const File& getFile() const throw() { return file; }
  8745. /** Returns true if the stream couldn't be opened for some reason.
  8746. */
  8747. bool failedToOpen() const throw() { return fileHandle == 0; }
  8748. void flush();
  8749. int64 getPosition();
  8750. bool setPosition (int64 pos);
  8751. bool write (const void* data, int numBytes);
  8752. juce_UseDebuggingNewOperator
  8753. private:
  8754. File file;
  8755. void* fileHandle;
  8756. int64 currentPosition;
  8757. int bufferSize, bytesInBuffer;
  8758. char* buffer;
  8759. };
  8760. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8761. /********* End of inlined file: juce_FileOutputStream.h *********/
  8762. #endif
  8763. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8764. /********* Start of inlined file: juce_FileSearchPath.h *********/
  8765. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8766. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  8767. /**
  8768. Encapsulates a set of folders that make up a search path.
  8769. @see File
  8770. */
  8771. class JUCE_API FileSearchPath
  8772. {
  8773. public:
  8774. /** Creates an empty search path. */
  8775. FileSearchPath();
  8776. /** Creates a search path from a string of pathnames.
  8777. The path can be semicolon- or comma-separated, e.g.
  8778. "/foo/bar;/foo/moose;/fish/moose"
  8779. The separate folders are tokenised and added to the search path.
  8780. */
  8781. FileSearchPath (const String& path);
  8782. /** Creates a copy of another search path. */
  8783. FileSearchPath (const FileSearchPath& other);
  8784. /** Destructor. */
  8785. ~FileSearchPath();
  8786. /** Uses a string containing a list of pathnames to re-initialise this list.
  8787. This search path is cleared and the semicolon- or comma-separated folders
  8788. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  8789. */
  8790. const FileSearchPath& operator= (const String& path);
  8791. /** Returns the number of folders in this search path.
  8792. @see operator[]
  8793. */
  8794. int getNumPaths() const;
  8795. /** Returns one of the folders in this search path.
  8796. The file returned isn't guaranteed to actually be a valid directory.
  8797. @see getNumPaths
  8798. */
  8799. const File operator[] (const int index) const;
  8800. /** Returns the search path as a semicolon-separated list of directories. */
  8801. const String toString() const;
  8802. /** Adds a new directory to the search path.
  8803. The new directory is added to the end of the list if the insertIndex parameter is
  8804. less than zero, otherwise it is inserted at the given index.
  8805. */
  8806. void add (const File& directoryToAdd,
  8807. const int insertIndex = -1);
  8808. /** Adds a new directory to the search path if it's not already in there. */
  8809. void addIfNotAlreadyThere (const File& directoryToAdd);
  8810. /** Removes a directory from the search path. */
  8811. void remove (const int indexToRemove);
  8812. /** Merges another search path into this one.
  8813. This will remove any duplicate directories.
  8814. */
  8815. void addPath (const FileSearchPath& other);
  8816. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  8817. If the search is intended to be recursive, there's no point having nested folders in the search
  8818. path, because they'll just get searched twice and you'll get duplicate results.
  8819. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  8820. */
  8821. void removeRedundantPaths();
  8822. /** Removes any directories that don't actually exist. */
  8823. void removeNonExistentPaths();
  8824. /** Searches the path for a wildcard.
  8825. This will search all the directories in the search path in order, adding any
  8826. matching files to the results array.
  8827. @param results an array to append the results to
  8828. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  8829. return files, directories, or both.
  8830. @param searchRecursively whether to recursively search the subdirectories too
  8831. @param wildCardPattern a pattern to match against the filenames
  8832. @returns the number of files added to the array
  8833. @see File::findChildFiles
  8834. */
  8835. int findChildFiles (OwnedArray<File>& results,
  8836. const int whatToLookFor,
  8837. const bool searchRecursively,
  8838. const String& wildCardPattern = JUCE_T("*")) const;
  8839. /** Finds out whether a file is inside one of the path's directories.
  8840. This will return true if the specified file is a child of one of the
  8841. directories specified by this path. Note that this doesn't actually do any
  8842. searching or check that the files exist - it just looks at the pathnames
  8843. to work out whether the file would be inside a directory.
  8844. @param fileToCheck the file to look for
  8845. @param checkRecursively if true, then this will return true if the file is inside a
  8846. subfolder of one of the path's directories (at any depth). If false
  8847. it will only return true if the file is actually a direct child
  8848. of one of the directories.
  8849. @see File::isAChildOf
  8850. */
  8851. bool isFileInPath (const File& fileToCheck,
  8852. const bool checkRecursively) const;
  8853. juce_UseDebuggingNewOperator
  8854. private:
  8855. StringArray directories;
  8856. void init (const String& path);
  8857. };
  8858. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  8859. /********* End of inlined file: juce_FileSearchPath.h *********/
  8860. #endif
  8861. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8862. /********* Start of inlined file: juce_NamedPipe.h *********/
  8863. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8864. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  8865. /**
  8866. A cross-process pipe that can have data written to and read from it.
  8867. Two or more processes can use these for inter-process communication.
  8868. @see InterprocessConnection
  8869. */
  8870. class JUCE_API NamedPipe
  8871. {
  8872. public:
  8873. /** Creates a NamedPipe. */
  8874. NamedPipe();
  8875. /** Destructor. */
  8876. ~NamedPipe();
  8877. /** Tries to open a pipe that already exists.
  8878. Returns true if it succeeds.
  8879. */
  8880. bool openExisting (const String& pipeName);
  8881. /** Tries to create a new pipe.
  8882. Returns true if it succeeds.
  8883. */
  8884. bool createNewPipe (const String& pipeName);
  8885. /** Closes the pipe, if it's open. */
  8886. void close();
  8887. /** True if the pipe is currently open. */
  8888. bool isOpen() const throw();
  8889. /** Returns the last name that was used to try to open this pipe. */
  8890. const String getName() const throw();
  8891. /** Reads data from the pipe.
  8892. This will block until another thread has written enough data into the pipe to fill
  8893. the number of bytes specified, or until another thread calls the cancelPendingReads()
  8894. method.
  8895. If the operation fails, it returns -1, otherwise, it will return the number of
  8896. bytes read.
  8897. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  8898. this is a maximum timeout for reading from the pipe.
  8899. */
  8900. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  8901. /** Writes some data to the pipe.
  8902. If the operation fails, it returns -1, otherwise, it will return the number of
  8903. bytes written.
  8904. */
  8905. int write (const void* sourceBuffer, int numBytesToWrite,
  8906. int timeOutMilliseconds = 2000);
  8907. /** If any threads are currently blocked on a read operation, this tells them to abort.
  8908. */
  8909. void cancelPendingReads();
  8910. juce_UseDebuggingNewOperator
  8911. private:
  8912. void* internal;
  8913. String currentPipeName;
  8914. NamedPipe (const NamedPipe&);
  8915. const NamedPipe& operator= (const NamedPipe&);
  8916. bool openInternal (const String& pipeName, const bool createPipe);
  8917. };
  8918. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  8919. /********* End of inlined file: juce_NamedPipe.h *********/
  8920. #endif
  8921. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8922. /********* Start of inlined file: juce_BlowFish.h *********/
  8923. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8924. #define __JUCE_BLOWFISH_JUCEHEADER__
  8925. /**
  8926. BlowFish encryption class.
  8927. */
  8928. class JUCE_API BlowFish
  8929. {
  8930. public:
  8931. /** Creates an object that can encode/decode based on the specified key.
  8932. The key data can be up to 72 bytes long.
  8933. */
  8934. BlowFish (const uint8* keyData, int keyBytes);
  8935. /** Creates a copy of another blowfish object. */
  8936. BlowFish (const BlowFish& other);
  8937. /** Copies another blowfish object. */
  8938. const BlowFish& operator= (const BlowFish& other);
  8939. /** Destructor. */
  8940. ~BlowFish();
  8941. /** Encrypts a pair of 32-bit integers. */
  8942. void encrypt (uint32& data1, uint32& data2) const;
  8943. /** Decrypts a pair of 32-bit integers. */
  8944. void decrypt (uint32& data1, uint32& data2) const;
  8945. juce_UseDebuggingNewOperator
  8946. private:
  8947. uint32 p[18];
  8948. uint32* s[4];
  8949. uint32 F (uint32 x) const;
  8950. };
  8951. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  8952. /********* End of inlined file: juce_BlowFish.h *********/
  8953. #endif
  8954. #ifndef __JUCE_MD5_JUCEHEADER__
  8955. /********* Start of inlined file: juce_MD5.h *********/
  8956. #ifndef __JUCE_MD5_JUCEHEADER__
  8957. #define __JUCE_MD5_JUCEHEADER__
  8958. /**
  8959. MD5 checksum class.
  8960. Create one of these with a block of source data or a string, and it calculates the
  8961. MD5 checksum of that data.
  8962. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  8963. */
  8964. class JUCE_API MD5
  8965. {
  8966. public:
  8967. /** Creates a null MD5 object. */
  8968. MD5();
  8969. /** Creates a copy of another MD5. */
  8970. MD5 (const MD5& other);
  8971. /** Copies another MD5. */
  8972. const MD5& operator= (const MD5& other);
  8973. /** Creates a checksum for a block of binary data. */
  8974. MD5 (const MemoryBlock& data);
  8975. /** Creates a checksum for a block of binary data. */
  8976. MD5 (const char* data, const int numBytes);
  8977. /** Creates a checksum for a string. */
  8978. MD5 (const String& text);
  8979. /** Creates a checksum for the input from a stream.
  8980. This will read up to the given number of bytes from the stream, and produce the
  8981. checksum of that. If the number of bytes to read is negative, it'll read
  8982. until the stream is exhausted.
  8983. */
  8984. MD5 (InputStream& input, int numBytesToRead = -1);
  8985. /** Creates a checksum for a file. */
  8986. MD5 (const File& file);
  8987. /** Destructor. */
  8988. ~MD5();
  8989. /** Returns the checksum as a 16-byte block of data. */
  8990. const MemoryBlock getRawChecksumData() const;
  8991. /** Returns the checksum as a 32-digit hex string. */
  8992. const String toHexString() const;
  8993. /** Compares this to another MD5. */
  8994. bool operator== (const MD5& other) const;
  8995. /** Compares this to another MD5. */
  8996. bool operator!= (const MD5& other) const;
  8997. juce_UseDebuggingNewOperator
  8998. private:
  8999. uint8 result [16];
  9000. struct ProcessContext
  9001. {
  9002. uint8 buffer [64];
  9003. uint32 state [4];
  9004. uint32 count [2];
  9005. ProcessContext();
  9006. void processBlock (const uint8* const data, int dataSize);
  9007. void transform (const uint8* const buffer);
  9008. void finish (uint8* const result);
  9009. };
  9010. void processStream (InputStream& input, int numBytesToRead);
  9011. };
  9012. #endif // __JUCE_MD5_JUCEHEADER__
  9013. /********* End of inlined file: juce_MD5.h *********/
  9014. #endif
  9015. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9016. /********* Start of inlined file: juce_Primes.h *********/
  9017. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9018. #define __JUCE_PRIMES_JUCEHEADER__
  9019. /**
  9020. Prime number creation class.
  9021. This class contains static methods for generating and testing prime numbers.
  9022. @see BitArray
  9023. */
  9024. class JUCE_API Primes
  9025. {
  9026. public:
  9027. /** Creates a random prime number with a given bit-length.
  9028. The certainty parameter specifies how many iterations to use when testing
  9029. for primality. A safe value might be anything over about 20-30.
  9030. The randomSeeds parameter lets you optionally pass it a set of values with
  9031. which to seed the random number generation, improving the security of the
  9032. keys generated.
  9033. */
  9034. static const BitArray createProbablePrime (int bitLength,
  9035. int certainty,
  9036. const int* randomSeeds = 0,
  9037. int numRandomSeeds = 0) throw();
  9038. /** Tests a number to see if it's prime.
  9039. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9040. whether the number is prime.
  9041. The certainty parameter specifies how many iterations to use when testing - a
  9042. safe value might be anything over about 20-30.
  9043. */
  9044. static bool isProbablyPrime (const BitArray& number,
  9045. int certainty) throw();
  9046. };
  9047. #endif // __JUCE_PRIMES_JUCEHEADER__
  9048. /********* End of inlined file: juce_Primes.h *********/
  9049. #endif
  9050. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9051. /********* Start of inlined file: juce_RSAKey.h *********/
  9052. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9053. #define __JUCE_RSAKEY_JUCEHEADER__
  9054. /**
  9055. RSA public/private key-pair encryption class.
  9056. An object of this type makes up one half of a public/private RSA key pair. Use the
  9057. createKeyPair() method to create a matching pair for encoding/decoding.
  9058. */
  9059. class JUCE_API RSAKey
  9060. {
  9061. public:
  9062. /** Creates a null key object.
  9063. Initialise a pair of objects for use with the createKeyPair() method.
  9064. */
  9065. RSAKey() throw();
  9066. /** Loads a key from an encoded string representation.
  9067. This reloads a key from a string created by the toString() method.
  9068. */
  9069. RSAKey (const String& stringRepresentation) throw();
  9070. /** Destructor. */
  9071. ~RSAKey() throw();
  9072. /** Turns the key into a string representation.
  9073. This can be reloaded using the constructor that takes a string.
  9074. */
  9075. const String toString() const throw();
  9076. /** Encodes or decodes a value.
  9077. Call this on the public key object to encode some data, then use the matching
  9078. private key object to decode it.
  9079. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9080. */
  9081. bool applyToValue (BitArray& value) const throw();
  9082. /** Creates a public/private key-pair.
  9083. Each key will perform one-way encryption that can only be reversed by
  9084. using the other key.
  9085. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9086. sizes are more secure, but this method will take longer to execute.
  9087. The randomSeeds parameter lets you optionally pass it a set of values with
  9088. which to seed the random number generation, improving the security of the
  9089. keys generated.
  9090. */
  9091. static void createKeyPair (RSAKey& publicKey,
  9092. RSAKey& privateKey,
  9093. const int numBits,
  9094. const int* randomSeeds = 0,
  9095. const int numRandomSeeds = 0) throw();
  9096. juce_UseDebuggingNewOperator
  9097. protected:
  9098. BitArray part1, part2;
  9099. };
  9100. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9101. /********* End of inlined file: juce_RSAKey.h *********/
  9102. #endif
  9103. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9104. /********* Start of inlined file: juce_Socket.h *********/
  9105. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9106. #define __JUCE_SOCKET_JUCEHEADER__
  9107. /**
  9108. A wrapper for a streaming (TCP) socket.
  9109. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9110. sockets, you could also try the InterprocessConnection class.
  9111. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9112. */
  9113. class JUCE_API StreamingSocket
  9114. {
  9115. public:
  9116. /** Creates an uninitialised socket.
  9117. To connect it, use the connect() method, after which you can read() or write()
  9118. to it.
  9119. To wait for other sockets to connect to this one, the createListener() method
  9120. enters "listener" mode, and can be used to spawn new sockets for each connection
  9121. that comes along.
  9122. */
  9123. StreamingSocket();
  9124. /** Destructor. */
  9125. ~StreamingSocket();
  9126. /** Binds the socket to the specified local port.
  9127. @returns true on success; false may indicate that another socket is already bound
  9128. on the same port
  9129. */
  9130. bool bindToPort (const int localPortNumber);
  9131. /** Tries to connect the socket to hostname:port.
  9132. If timeOutMillisecs is 0, then this method will block until the operating system
  9133. rejects the connection (which could take a long time).
  9134. @returns true if it succeeds.
  9135. @see isConnected
  9136. */
  9137. bool connect (const String& remoteHostname,
  9138. const int remotePortNumber,
  9139. const int timeOutMillisecs = 3000);
  9140. /** True if the socket is currently connected. */
  9141. bool isConnected() const throw() { return connected; }
  9142. /** Closes the connection. */
  9143. void close();
  9144. /** Returns the name of the currently connected host. */
  9145. const String& getHostName() const throw() { return hostName; }
  9146. /** Returns the port number that's currently open. */
  9147. int getPort() const throw() { return portNumber; }
  9148. /** True if the socket is connected to this machine rather than over the network. */
  9149. bool isLocal() const throw();
  9150. /** Waits until the socket is ready for reading or writing.
  9151. If readyForReading is true, it will wait until the socket is ready for
  9152. reading; if false, it will wait until it's ready for writing.
  9153. If the timeout is < 0, it will wait forever, or else will give up after
  9154. the specified time.
  9155. If the socket is ready on return, this returns 1. If it times-out before
  9156. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9157. */
  9158. int waitUntilReady (const bool readyForReading,
  9159. const int timeoutMsecs) const;
  9160. /** Reads bytes from the socket (blocking).
  9161. Note that this method will block unless you have checked the socket is ready
  9162. for reading before calling it (see the waitUntilReady() method).
  9163. @returns the number of bytes read, or -1 if there was an error.
  9164. */
  9165. int read (void* destBuffer, const int maxBytesToRead);
  9166. /** Writes bytes to the socket from a buffer.
  9167. Note that this method will block unless you have checked the socket is ready
  9168. for writing before calling it (see the waitUntilReady() method).
  9169. @returns the number of bytes written, or -1 if there was an error.
  9170. */
  9171. int write (const void* sourceBuffer, const int numBytesToWrite);
  9172. /** Puts this socket into "listener" mode.
  9173. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9174. which will spawn new sockets for each new connection, so that these can
  9175. be handled in parallel by other threads.
  9176. This returns true if it manages to open the socket successfully.
  9177. @see waitForNextConnection
  9178. */
  9179. bool createListener (const int portNumber);
  9180. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9181. socket.
  9182. The object that gets returned will be owned by the caller.
  9183. This method can only be called after using createListener().
  9184. @see createListener
  9185. */
  9186. StreamingSocket* waitForNextConnection() const;
  9187. juce_UseDebuggingNewOperator
  9188. private:
  9189. String hostName;
  9190. int volatile portNumber, handle;
  9191. bool connected, isListener;
  9192. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9193. StreamingSocket (const StreamingSocket&);
  9194. const StreamingSocket& operator= (const StreamingSocket&);
  9195. };
  9196. /**
  9197. A wrapper for a datagram (UDP) socket.
  9198. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9199. sockets, you could also try the InterprocessConnection class.
  9200. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9201. */
  9202. class JUCE_API DatagramSocket
  9203. {
  9204. public:
  9205. /**
  9206. Creates an (uninitialised) datagram socket.
  9207. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9208. the port number is assigned by the operating system.
  9209. To use the socket for sending, call the connect() method. This will not immediately
  9210. make a connection, but will save the destination you've provided. After this, you can
  9211. call read() or write().
  9212. To wait for other sockets to connect to this one, call waitForNextConnection().
  9213. */
  9214. DatagramSocket (const int localPortNumber);
  9215. /** Destructor. */
  9216. ~DatagramSocket();
  9217. /** Binds the socket to the specified local port.
  9218. @returns true on success; false may indicate that another socket is already bound
  9219. on the same port
  9220. */
  9221. bool bindToPort (const int localPortNumber);
  9222. /** Tries to connect the socket to hostname:port.
  9223. If timeOutMillisecs is 0, then this method will block until the operating system
  9224. rejects the connection (which could take a long time).
  9225. @returns true if it succeeds.
  9226. @see isConnected
  9227. */
  9228. bool connect (const String& remoteHostname,
  9229. const int remotePortNumber,
  9230. const int timeOutMillisecs = 3000);
  9231. /** True if the socket is currently connected. */
  9232. bool isConnected() const throw() { return connected; }
  9233. /** Closes the connection. */
  9234. void close();
  9235. /** Returns the name of the currently connected host. */
  9236. const String& getHostName() const throw() { return hostName; }
  9237. /** Returns the port number that's currently open. */
  9238. int getPort() const throw() { return portNumber; }
  9239. /** True if the socket is connected to this machine rather than over the network. */
  9240. bool isLocal() const throw();
  9241. /** Waits until the socket is ready for reading or writing.
  9242. If readyForReading is true, it will wait until the socket is ready for
  9243. reading; if false, it will wait until it's ready for writing.
  9244. If the timeout is < 0, it will wait forever, or else will give up after
  9245. the specified time.
  9246. If the socket is ready on return, this returns 1. If it times-out before
  9247. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9248. */
  9249. int waitUntilReady (const bool readyForReading,
  9250. const int timeoutMsecs) const;
  9251. /** Reads bytes from the socket (blocking).
  9252. Note that this method will block unless you have checked the socket is ready
  9253. for reading before calling it (see the waitUntilReady() method).
  9254. @returns the number of bytes read, or -1 if there was an error.
  9255. */
  9256. int read (void* destBuffer, const int maxBytesToRead);
  9257. /** Writes bytes to the socket from a buffer.
  9258. Note that this method will block unless you have checked the socket is ready
  9259. for writing before calling it (see the waitUntilReady() method).
  9260. @returns the number of bytes written, or -1 if there was an error.
  9261. */
  9262. int write (const void* sourceBuffer, const int numBytesToWrite);
  9263. /** This waits for incoming data to be sent, and returns a socket that can be used
  9264. to read it.
  9265. The object that gets returned is owned by the caller, and can't be used for
  9266. sending, but can be used to read the data.
  9267. */
  9268. DatagramSocket* waitForNextConnection() const;
  9269. juce_UseDebuggingNewOperator
  9270. private:
  9271. String hostName;
  9272. int volatile portNumber, handle;
  9273. bool connected;
  9274. void* serverAddress;
  9275. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9276. DatagramSocket (const DatagramSocket&);
  9277. const DatagramSocket& operator= (const DatagramSocket&);
  9278. };
  9279. #endif // __JUCE_SOCKET_JUCEHEADER__
  9280. /********* End of inlined file: juce_Socket.h *********/
  9281. #endif
  9282. #ifndef __JUCE_URL_JUCEHEADER__
  9283. /********* Start of inlined file: juce_URL.h *********/
  9284. #ifndef __JUCE_URL_JUCEHEADER__
  9285. #define __JUCE_URL_JUCEHEADER__
  9286. /**
  9287. Represents a URL and has a bunch of useful functions to manipulate it.
  9288. This class can be used to launch URLs in browsers, and also to create
  9289. InputStreams that can read from remote http or ftp sources.
  9290. */
  9291. class JUCE_API URL
  9292. {
  9293. public:
  9294. /** Creates an empty URL. */
  9295. URL() throw();
  9296. /** Creates a URL from a string. */
  9297. URL (const String& url);
  9298. /** Creates a copy of another URL. */
  9299. URL (const URL& other);
  9300. /** Destructor. */
  9301. ~URL() throw();
  9302. /** Copies this URL from another one. */
  9303. const URL& operator= (const URL& other);
  9304. /** Returns a string version of the URL.
  9305. If includeGetParameters is true and any parameters have been set with the
  9306. withParameter() method, then the string will have these appended on the
  9307. end and url-encoded.
  9308. */
  9309. const String toString (const bool includeGetParameters) const;
  9310. /** True if it seems to be valid. */
  9311. bool isWellFormed() const;
  9312. /** Returns a copy of this URL, with a GET parameter added to the end.
  9313. Any control characters in the value will be encoded.
  9314. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  9315. would produce a new url whose toString(true) method would return
  9316. "www.fish.com?amount=some+fish".
  9317. */
  9318. const URL withParameter (const String& parameterName,
  9319. const String& parameterValue) const;
  9320. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  9321. When performing a POST where one of your parameters is a binary file, this
  9322. lets you specify the file.
  9323. Note that the filename is stored, but the file itself won't actually be read
  9324. until this URL is later used to create a network input stream.
  9325. */
  9326. const URL withFileToUpload (const String& parameterName,
  9327. const File& fileToUpload,
  9328. const String& mimeType) const;
  9329. /** Returns a set of all the parameters encoded into the url.
  9330. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  9331. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  9332. The values returned will have been cleaned up to remove any escape characters.
  9333. @see getNamedParameter, withParameter
  9334. */
  9335. const StringPairArray& getParameters() const throw();
  9336. /** Returns the set of files that should be uploaded as part of a POST operation.
  9337. This is the set of files that were added to the URL with the withFileToUpload()
  9338. method.
  9339. */
  9340. const StringPairArray& getFilesToUpload() const throw();
  9341. /** Returns the set of mime types associated with each of the upload files.
  9342. */
  9343. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  9344. /** Tries to launch the system's default browser to open the URL.
  9345. Returns true if this seems to have worked.
  9346. */
  9347. bool launchInDefaultBrowser() const;
  9348. /** Takes a guess as to whether a string might be a valid website address.
  9349. This isn't foolproof!
  9350. */
  9351. static bool isProbablyAWebsiteURL (const String& possibleURL);
  9352. /** Takes a guess as to whether a string might be a valid email address.
  9353. This isn't foolproof!
  9354. */
  9355. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  9356. /** This callback function can be used by the createInputStream() method.
  9357. It allows your app to receive progress updates during a lengthy POST operation. If you
  9358. want to continue the operation, this should return true, or false to abort.
  9359. */
  9360. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  9361. /** Attempts to open a stream that can read from this URL.
  9362. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  9363. the paramters, otherwise it'll encode them into the
  9364. URL and do a 'GET'.
  9365. @param progressCallback if this is non-zero, it lets you supply a callback function
  9366. to keep track of the operation's progress. This can be useful
  9367. for lengthy POST operations, so that you can provide user feedback.
  9368. @param progressCallbackContext if a callback is specified, this value will be passed to
  9369. the function
  9370. @param extraHeaders if not empty, this string is appended onto the headers that
  9371. are used for the request. It must therefore be a valid set of HTML
  9372. header directives, separated by newlines.
  9373. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  9374. a negative number, it will be infinite. Otherwise it specifies a
  9375. time in milliseconds.
  9376. */
  9377. InputStream* createInputStream (const bool usePostCommand,
  9378. OpenStreamProgressCallback* const progressCallback = 0,
  9379. void* const progressCallbackContext = 0,
  9380. const String& extraHeaders = String::empty,
  9381. const int connectionTimeOutMs = 0) const;
  9382. /** Tries to download the entire contents of this URL into a binary data block.
  9383. If it succeeds, this will return true and append the data it read onto the end
  9384. of the memory block.
  9385. @param destData the memory block to append the new data to
  9386. @param usePostCommand whether to use a POST command to get the data (uses
  9387. a GET command if this is false)
  9388. @see readEntireTextStream, readEntireXmlStream
  9389. */
  9390. bool readEntireBinaryStream (MemoryBlock& destData,
  9391. const bool usePostCommand = false) const;
  9392. /** Tries to download the entire contents of this URL as a string.
  9393. If it fails, this will return an empty string, otherwise it will return the
  9394. contents of the downloaded file. If you need to distinguish between a read
  9395. operation that fails and one that returns an empty string, you'll need to use
  9396. a different method, such as readEntireBinaryStream().
  9397. @param usePostCommand whether to use a POST command to get the data (uses
  9398. a GET command if this is false)
  9399. @see readEntireBinaryStream, readEntireXmlStream
  9400. */
  9401. const String readEntireTextStream (const bool usePostCommand = false) const;
  9402. /** Tries to download the entire contents of this URL and parse it as XML.
  9403. If it fails, or if the text that it reads can't be parsed as XML, this will
  9404. return 0.
  9405. When it returns a valid XmlElement object, the caller is responsibile for deleting
  9406. this object when no longer needed.
  9407. @param usePostCommand whether to use a POST command to get the data (uses
  9408. a GET command if this is false)
  9409. @see readEntireBinaryStream, readEntireTextStream
  9410. */
  9411. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  9412. /** Adds escape sequences to a string to encode any characters that aren't
  9413. legal in a URL.
  9414. E.g. any spaces will be replaced with "%20".
  9415. This is the opposite of removeEscapeChars().
  9416. If isParameter is true, it means that the string is going to be used
  9417. as a parameter, so it also encodes '$' and ',' (which would otherwise
  9418. be legal in a URL.
  9419. @see removeEscapeChars
  9420. */
  9421. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  9422. const bool isParameter);
  9423. /** Replaces any escape character sequences in a string with their original
  9424. character codes.
  9425. E.g. any instances of "%20" will be replaced by a space.
  9426. This is the opposite of addEscapeChars().
  9427. @see addEscapeChars
  9428. */
  9429. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  9430. juce_UseDebuggingNewOperator
  9431. private:
  9432. String url;
  9433. StringPairArray parameters, filesToUpload, mimeTypes;
  9434. };
  9435. #endif // __JUCE_URL_JUCEHEADER__
  9436. /********* End of inlined file: juce_URL.h *********/
  9437. #endif
  9438. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9439. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9440. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9441. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9442. /** Wraps another input stream, and reads from it using an intermediate buffer
  9443. If you're using an input stream such as a file input stream, and making lots of
  9444. small read accesses to it, it's probably sensible to wrap it in one of these,
  9445. so that the source stream gets accessed in larger chunk sizes, meaning less
  9446. work for the underlying stream.
  9447. */
  9448. class JUCE_API BufferedInputStream : public InputStream
  9449. {
  9450. public:
  9451. /** Creates a BufferedInputStream from an input source.
  9452. @param sourceStream the source stream to read from
  9453. @param bufferSize the size of reservoir to use to buffer the source
  9454. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9455. deleted by this object when it is itself deleted.
  9456. */
  9457. BufferedInputStream (InputStream* const sourceStream,
  9458. const int bufferSize,
  9459. const bool deleteSourceWhenDestroyed) throw();
  9460. /** Destructor.
  9461. This may also delete the source stream, if that option was chosen when the
  9462. buffered stream was created.
  9463. */
  9464. ~BufferedInputStream() throw();
  9465. int64 getTotalLength();
  9466. int64 getPosition();
  9467. bool setPosition (int64 newPosition);
  9468. int read (void* destBuffer, int maxBytesToRead);
  9469. const String readString();
  9470. bool isExhausted();
  9471. juce_UseDebuggingNewOperator
  9472. private:
  9473. InputStream* const source;
  9474. const bool deleteSourceWhenDestroyed;
  9475. int bufferSize;
  9476. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9477. char* buffer;
  9478. void ensureBuffered();
  9479. BufferedInputStream (const BufferedInputStream&);
  9480. const BufferedInputStream& operator= (const BufferedInputStream&);
  9481. };
  9482. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9483. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9484. #endif
  9485. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9486. /********* Start of inlined file: juce_FileInputSource.h *********/
  9487. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9488. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9489. /********* Start of inlined file: juce_InputSource.h *********/
  9490. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9491. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9492. /**
  9493. A lightweight object that can create a stream to read some kind of resource.
  9494. This may be used to refer to a file, or some other kind of source, allowing a
  9495. caller to create an input stream that can read from it when required.
  9496. @see FileInputSource
  9497. */
  9498. class JUCE_API InputSource
  9499. {
  9500. public:
  9501. InputSource() throw() {}
  9502. /** Destructor. */
  9503. virtual ~InputSource() {}
  9504. /** Returns a new InputStream to read this item.
  9505. @returns an inputstream that the caller will delete, or 0 if
  9506. the filename isn't found.
  9507. */
  9508. virtual InputStream* createInputStream() = 0;
  9509. /** Returns a new InputStream to read an item, relative.
  9510. @param relatedItemPath the relative pathname of the resource that is required
  9511. @returns an inputstream that the caller will delete, or 0 if
  9512. the item isn't found.
  9513. */
  9514. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9515. /** Returns a hash code that uniquely represents this item.
  9516. */
  9517. virtual int64 hashCode() const = 0;
  9518. juce_UseDebuggingNewOperator
  9519. };
  9520. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9521. /********* End of inlined file: juce_InputSource.h *********/
  9522. /**
  9523. A type of InputSource that represents a normal file.
  9524. @see InputSource
  9525. */
  9526. class JUCE_API FileInputSource : public InputSource
  9527. {
  9528. public:
  9529. FileInputSource (const File& file) throw();
  9530. ~FileInputSource();
  9531. InputStream* createInputStream();
  9532. InputStream* createInputStreamFor (const String& relatedItemPath);
  9533. int64 hashCode() const;
  9534. juce_UseDebuggingNewOperator
  9535. private:
  9536. const File file;
  9537. FileInputSource (const FileInputSource&);
  9538. const FileInputSource& operator= (const FileInputSource&);
  9539. };
  9540. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9541. /********* End of inlined file: juce_FileInputSource.h *********/
  9542. #endif
  9543. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9544. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9545. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9546. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9547. /**
  9548. A stream which uses zlib to compress the data written into it.
  9549. @see GZIPDecompressorInputStream
  9550. */
  9551. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9552. {
  9553. public:
  9554. /** Creates a compression stream.
  9555. @param destStream the stream into which the compressed data should
  9556. be written
  9557. @param compressionLevel how much to compress the data, between 1 and 9, where
  9558. 1 is the fastest/lowest compression, and 9 is the
  9559. slowest/highest compression. Any value outside this range
  9560. indicates that a default compression level should be used.
  9561. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9562. this stream is destroyed
  9563. @param noWrap this is used internally by the ZipFile class
  9564. and should be ignored by user applications
  9565. */
  9566. GZIPCompressorOutputStream (OutputStream* const destStream,
  9567. int compressionLevel = 0,
  9568. const bool deleteDestStreamWhenDestroyed = false,
  9569. const bool noWrap = false);
  9570. /** Destructor. */
  9571. ~GZIPCompressorOutputStream();
  9572. void flush();
  9573. int64 getPosition();
  9574. bool setPosition (int64 newPosition);
  9575. bool write (const void* destBuffer, int howMany);
  9576. juce_UseDebuggingNewOperator
  9577. private:
  9578. OutputStream* const destStream;
  9579. const bool deleteDestStream;
  9580. uint8* buffer;
  9581. void* helper;
  9582. bool doNextBlock();
  9583. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9584. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9585. };
  9586. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9587. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9588. #endif
  9589. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9590. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9591. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9592. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9593. /**
  9594. This stream will decompress a source-stream using zlib.
  9595. Tip: if you're reading lots of small items from one of these streams, you
  9596. can increase the performance enormously by passing it through a
  9597. BufferedInputStream, so that it has to read larger blocks less often.
  9598. @see GZIPCompressorOutputStream
  9599. */
  9600. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9601. {
  9602. public:
  9603. /** Creates a decompressor stream.
  9604. @param sourceStream the stream to read from
  9605. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9606. when this object is destroyed
  9607. @param noWrap this is used internally by the ZipFile class
  9608. and should be ignored by user applications
  9609. @param uncompressedStreamLength if the creator knows the length that the
  9610. uncompressed stream will be, then it can supply this
  9611. value, which will be returned by getTotalLength()
  9612. */
  9613. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9614. const bool deleteSourceWhenDestroyed,
  9615. const bool noWrap = false,
  9616. const int64 uncompressedStreamLength = -1);
  9617. /** Destructor. */
  9618. ~GZIPDecompressorInputStream();
  9619. int64 getPosition();
  9620. bool setPosition (int64 pos);
  9621. int64 getTotalLength();
  9622. bool isExhausted();
  9623. int read (void* destBuffer, int maxBytesToRead);
  9624. juce_UseDebuggingNewOperator
  9625. private:
  9626. InputStream* const sourceStream;
  9627. const int64 uncompressedStreamLength;
  9628. const bool deleteSourceWhenDestroyed, noWrap;
  9629. bool isEof;
  9630. int activeBufferSize;
  9631. int64 originalSourcePos, currentPos;
  9632. uint8* buffer;
  9633. void* helper;
  9634. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9635. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9636. };
  9637. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9638. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9639. #endif
  9640. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9641. #endif
  9642. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9643. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9644. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9645. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9646. /**
  9647. Allows a block of data and to be accessed as a stream.
  9648. This can either be used to refer to a shared block of memory, or can make its
  9649. own internal copy of the data when the MemoryInputStream is created.
  9650. */
  9651. class JUCE_API MemoryInputStream : public InputStream
  9652. {
  9653. public:
  9654. /** Creates a MemoryInputStream.
  9655. @param sourceData the block of data to use as the stream's source
  9656. @param sourceDataSize the number of bytes in the source data block
  9657. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9658. the source data, so this data shouldn't be changed
  9659. for the lifetime of the stream; if this parameter is
  9660. true, the stream will make its own copy of the
  9661. data and use that.
  9662. */
  9663. MemoryInputStream (const void* const sourceData,
  9664. const int sourceDataSize,
  9665. const bool keepInternalCopyOfData) throw();
  9666. /** Destructor. */
  9667. ~MemoryInputStream() throw();
  9668. int64 getPosition();
  9669. bool setPosition (int64 pos);
  9670. int64 getTotalLength();
  9671. bool isExhausted();
  9672. int read (void* destBuffer, int maxBytesToRead);
  9673. juce_UseDebuggingNewOperator
  9674. private:
  9675. const char* data;
  9676. int dataSize, position;
  9677. MemoryBlock internalCopy;
  9678. };
  9679. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9680. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9681. #endif
  9682. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9683. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9684. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9685. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9686. /** Writes data to an internal memory buffer, which grows as required.
  9687. The data that was written into the stream can then be accessed later as
  9688. a contiguous block of memory.
  9689. */
  9690. class JUCE_API MemoryOutputStream : public OutputStream
  9691. {
  9692. public:
  9693. /** Creates a memory stream ready for writing into.
  9694. @param initialSize the intial amount of space to allocate for writing into
  9695. @param granularity the increments by which the internal storage will be increased
  9696. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9697. place that the data gets stored. If it's zero, the stream
  9698. will allocate its own storage internally, which you can
  9699. access using getData() and getDataSize()
  9700. */
  9701. MemoryOutputStream (const int initialSize = 256,
  9702. const int granularity = 256,
  9703. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9704. /** Destructor.
  9705. This will free any data that was written to it.
  9706. */
  9707. ~MemoryOutputStream() throw();
  9708. /** Returns a pointer to the data that has been written to the stream.
  9709. @see getDataSize
  9710. */
  9711. const char* getData() throw();
  9712. /** Returns the number of bytes of data that have been written to the stream.
  9713. @see getData
  9714. */
  9715. int getDataSize() const throw();
  9716. /** Resets the stream, clearing any data that has been written to it so far. */
  9717. void reset() throw();
  9718. void flush();
  9719. bool write (const void* buffer, int howMany);
  9720. int64 getPosition();
  9721. bool setPosition (int64 newPosition);
  9722. juce_UseDebuggingNewOperator
  9723. private:
  9724. MemoryBlock* data;
  9725. int position, size, blockSize;
  9726. bool ownsMemoryBlock;
  9727. };
  9728. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9729. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9730. #endif
  9731. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9732. /********* Start of inlined file: juce_SubregionStream.h *********/
  9733. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9734. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9735. /** Wraps another input stream, and reads from a specific part of it.
  9736. This lets you take a subsection of a stream and present it as an entire
  9737. stream in its own right.
  9738. */
  9739. class JUCE_API SubregionStream : public InputStream
  9740. {
  9741. public:
  9742. /** Creates a SubregionStream from an input source.
  9743. @param sourceStream the source stream to read from
  9744. @param startPositionInSourceStream this is the position in the source stream that
  9745. corresponds to position 0 in this stream
  9746. @param lengthOfSourceStream this specifies the maximum number of bytes
  9747. from the source stream that will be passed through
  9748. by this stream. When the position of this stream
  9749. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9750. If the length passed in here is greater than the length
  9751. of the source stream (as returned by getTotalLength()),
  9752. then the smaller value will be used.
  9753. Passing a negative value for this parameter means it
  9754. will keep reading until the source's end-of-stream.
  9755. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9756. deleted by this object when it is itself deleted.
  9757. */
  9758. SubregionStream (InputStream* const sourceStream,
  9759. const int64 startPositionInSourceStream,
  9760. const int64 lengthOfSourceStream,
  9761. const bool deleteSourceWhenDestroyed) throw();
  9762. /** Destructor.
  9763. This may also delete the source stream, if that option was chosen when the
  9764. buffered stream was created.
  9765. */
  9766. ~SubregionStream() throw();
  9767. int64 getTotalLength();
  9768. int64 getPosition();
  9769. bool setPosition (int64 newPosition);
  9770. int read (void* destBuffer, int maxBytesToRead);
  9771. bool isExhausted();
  9772. juce_UseDebuggingNewOperator
  9773. private:
  9774. InputStream* const source;
  9775. const bool deleteSourceWhenDestroyed;
  9776. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9777. SubregionStream (const SubregionStream&);
  9778. const SubregionStream& operator= (const SubregionStream&);
  9779. };
  9780. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9781. /********* End of inlined file: juce_SubregionStream.h *********/
  9782. #endif
  9783. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9784. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9785. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9786. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9787. /** A timer for measuring performance of code and dumping the results to a file.
  9788. e.g. @code
  9789. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9790. for (;;)
  9791. {
  9792. pc.start();
  9793. doSomethingFishy();
  9794. pc.stop();
  9795. }
  9796. @endcode
  9797. In this example, the time of each period between calling start/stop will be
  9798. measured and averaged over 50 runs, and the results printed to a file
  9799. every 50 times round the loop.
  9800. */
  9801. class JUCE_API PerformanceCounter
  9802. {
  9803. public:
  9804. /** Creates a PerformanceCounter object.
  9805. @param counterName the name used when printing out the statistics
  9806. @param runsPerPrintout the number of start/stop iterations before calling
  9807. printStatistics()
  9808. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9809. the results are just written to the debugger output
  9810. */
  9811. PerformanceCounter (const String& counterName,
  9812. int runsPerPrintout = 100,
  9813. const File& loggingFile = File::nonexistent);
  9814. /** Destructor. */
  9815. ~PerformanceCounter();
  9816. /** Starts timing.
  9817. @see stop
  9818. */
  9819. void start();
  9820. /** Stops timing and prints out the results.
  9821. The number of iterations before doing a printout of the
  9822. results is set in the constructor.
  9823. @see start
  9824. */
  9825. void stop();
  9826. /** Dumps the current metrics to the debugger output and to a file.
  9827. As well as using Logger::outputDebugString to print the results,
  9828. this will write then to the file specified in the constructor (if
  9829. this was valid).
  9830. */
  9831. void printStatistics();
  9832. juce_UseDebuggingNewOperator
  9833. private:
  9834. String name;
  9835. int numRuns, runsPerPrint;
  9836. double totalTime;
  9837. int64 started;
  9838. File outputFile;
  9839. };
  9840. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9841. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9842. #endif
  9843. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9844. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9845. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9846. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9847. /**
  9848. A collection of miscellaneous platform-specific utilities.
  9849. */
  9850. class JUCE_API PlatformUtilities
  9851. {
  9852. public:
  9853. /** Plays the operating system's default alert 'beep' sound. */
  9854. static void beep();
  9855. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9856. const String& emailSubject,
  9857. const String& bodyText,
  9858. const StringArray& filesToAttach);
  9859. #if JUCE_MAC || DOXYGEN
  9860. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9861. static const String cfStringToJuceString (CFStringRef cfString);
  9862. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9863. static CFStringRef juceStringToCFString (const String& s);
  9864. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9865. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9866. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9867. static const String makePathFromFSRef (FSRef* file);
  9868. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9869. their precomposed equivalents.
  9870. */
  9871. static const String convertToPrecomposedUnicode (const String& s);
  9872. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9873. static OSType getTypeOfFile (const String& filename);
  9874. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9875. static bool isBundle (const String& filename);
  9876. #endif
  9877. #if JUCE_WIN32 || DOXYGEN
  9878. // Some registry helper functions:
  9879. /** WIN32 ONLY - Returns a string from the registry.
  9880. The path is a string for the entire path of a value in the registry,
  9881. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9882. */
  9883. static const String getRegistryValue (const String& regValuePath,
  9884. const String& defaultValue = String::empty);
  9885. /** WIN32 ONLY - Sets a registry value as a string.
  9886. This will take care of creating any groups needed to get to the given
  9887. registry value.
  9888. */
  9889. static void setRegistryValue (const String& regValuePath,
  9890. const String& value);
  9891. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9892. static bool registryValueExists (const String& regValuePath);
  9893. /** WIN32 ONLY - Deletes a registry value. */
  9894. static void deleteRegistryValue (const String& regValuePath);
  9895. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9896. static void deleteRegistryKey (const String& regKeyPath);
  9897. /** WIN32 ONLY - Creates a file association in the registry.
  9898. This lets you set the exe that should be launched by a given file extension.
  9899. @param fileExtension the file extension to associate, including the
  9900. initial dot, e.g. ".txt"
  9901. @param symbolicDescription a space-free short token to identify the file type
  9902. @param fullDescription a human-readable description of the file type
  9903. @param targetExecutable the executable that should be launched
  9904. @param iconResourceNumber the icon that gets displayed for the file type will be
  9905. found by looking up this resource number in the
  9906. executable. Pass 0 here to not use an icon
  9907. */
  9908. static void registerFileAssociation (const String& fileExtension,
  9909. const String& symbolicDescription,
  9910. const String& fullDescription,
  9911. const File& targetExecutable,
  9912. int iconResourceNumber);
  9913. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9914. In a normal Juce application this will be set to the module handle
  9915. of the application executable.
  9916. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9917. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9918. to set the correct module handle in your DllMain() function, because
  9919. the win32 system relies on the correct instance handle when opening windows.
  9920. */
  9921. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9922. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9923. @see getCurrentModuleInstanceHandle()
  9924. */
  9925. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  9926. /** WIN32 ONLY - Gets the command-line params as a string.
  9927. This is needed to avoid unicode problems with the argc type params.
  9928. */
  9929. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  9930. #endif
  9931. /** Clears the floating point unit's flags.
  9932. Only has an effect under win32, currently.
  9933. */
  9934. static void fpuReset();
  9935. #if JUCE_LINUX || JUCE_WIN32
  9936. /** Loads a dynamically-linked library into the process's address space.
  9937. @param pathOrFilename the platform-dependent name and search path
  9938. @returns a handle which can be used by getProcedureEntryPoint(), or
  9939. zero if it fails.
  9940. @see freeDynamicLibrary, getProcedureEntryPoint
  9941. */
  9942. static void* loadDynamicLibrary (const String& pathOrFilename);
  9943. /** Frees a dynamically-linked library.
  9944. @param libraryHandle a handle created by loadDynamicLibrary
  9945. @see loadDynamicLibrary, getProcedureEntryPoint
  9946. */
  9947. static void freeDynamicLibrary (void* libraryHandle);
  9948. /** Finds a procedure call in a dynamically-linked library.
  9949. @param libraryHandle a library handle returned by loadDynamicLibrary
  9950. @param procedureName the name of the procedure call to try to load
  9951. @returns a pointer to the function if found, or 0 if it fails
  9952. @see loadDynamicLibrary
  9953. */
  9954. static void* getProcedureEntryPoint (void* libraryHandle,
  9955. const String& procedureName);
  9956. #endif
  9957. #if JUCE_LINUX || DOXYGEN
  9958. #endif
  9959. };
  9960. #if JUCE_MAC
  9961. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  9962. using RAII.
  9963. */
  9964. class ScopedAutoReleasePool
  9965. {
  9966. public:
  9967. ScopedAutoReleasePool();
  9968. ~ScopedAutoReleasePool();
  9969. private:
  9970. void* pool;
  9971. };
  9972. /**
  9973. A wrapper class for picking up events from an Apple IR remote control device.
  9974. To use it, just create a subclass of this class, implementing the buttonPressed()
  9975. callback, then call start() and stop() to start or stop receiving events.
  9976. */
  9977. class JUCE_API AppleRemoteDevice
  9978. {
  9979. public:
  9980. AppleRemoteDevice();
  9981. virtual ~AppleRemoteDevice();
  9982. /** The set of buttons that may be pressed.
  9983. @see buttonPressed
  9984. */
  9985. enum ButtonType
  9986. {
  9987. menuButton = 0, /**< The menu button (if it's held for a short time). */
  9988. playButton, /**< The play button. */
  9989. plusButton, /**< The plus or volume-up button. */
  9990. minusButton, /**< The minus or volume-down button. */
  9991. rightButton, /**< The right button (if it's held for a short time). */
  9992. leftButton, /**< The left button (if it's held for a short time). */
  9993. rightButton_Long, /**< The right button (if it's held for a long time). */
  9994. leftButton_Long, /**< The menu button (if it's held for a long time). */
  9995. menuButton_Long, /**< The menu button (if it's held for a long time). */
  9996. playButtonSleepMode,
  9997. switched
  9998. };
  9999. /** Override this method to receive the callback about a button press.
  10000. The callback will happen on the application's message thread.
  10001. Some buttons trigger matching up and down events, in which the isDown parameter
  10002. will be true and then false. Others only send a single event when the
  10003. button is pressed.
  10004. */
  10005. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10006. /** Starts the device running and responding to events.
  10007. Returns true if it managed to open the device.
  10008. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10009. and will not be available to any other part of the system. If
  10010. false, it will be shared with other apps.
  10011. @see stop
  10012. */
  10013. bool start (const bool inExclusiveMode) throw();
  10014. /** Stops the device running.
  10015. @see start
  10016. */
  10017. void stop() throw();
  10018. /** Returns true if the device has been started successfully.
  10019. */
  10020. bool isActive() const throw();
  10021. /** Returns the ID number of the remote, if it has sent one.
  10022. */
  10023. int getRemoteId() const throw() { return remoteId; }
  10024. juce_UseDebuggingNewOperator
  10025. /** @internal */
  10026. void handleCallbackInternal();
  10027. private:
  10028. void* device;
  10029. void* queue;
  10030. int remoteId;
  10031. bool open (const bool openInExclusiveMode) throw();
  10032. };
  10033. #endif
  10034. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10035. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10036. #endif
  10037. #ifndef __JUCE_UUID_JUCEHEADER__
  10038. /********* Start of inlined file: juce_Uuid.h *********/
  10039. #ifndef __JUCE_UUID_JUCEHEADER__
  10040. #define __JUCE_UUID_JUCEHEADER__
  10041. /**
  10042. A universally unique 128-bit identifier.
  10043. This class generates very random unique numbers based on the system time
  10044. and MAC addresses if any are available. It's extremely unlikely that two identical
  10045. UUIDs would ever be created by chance.
  10046. The class includes methods for saving the ID as a string or as raw binary data.
  10047. */
  10048. class JUCE_API Uuid
  10049. {
  10050. public:
  10051. /** Creates a new unique ID. */
  10052. Uuid();
  10053. /** Destructor. */
  10054. ~Uuid() throw();
  10055. /** Creates a copy of another UUID. */
  10056. Uuid (const Uuid& other);
  10057. /** Copies another UUID. */
  10058. Uuid& operator= (const Uuid& other);
  10059. /** Returns true if the ID is zero. */
  10060. bool isNull() const throw();
  10061. /** Compares two UUIDs. */
  10062. bool operator== (const Uuid& other) const;
  10063. /** Compares two UUIDs. */
  10064. bool operator!= (const Uuid& other) const;
  10065. /** Returns a stringified version of this UUID.
  10066. A Uuid object can later be reconstructed from this string using operator= or
  10067. the constructor that takes a string parameter.
  10068. @returns a 32 character hex string.
  10069. */
  10070. const String toString() const;
  10071. /** Creates an ID from an encoded string version.
  10072. @see toString
  10073. */
  10074. Uuid (const String& uuidString);
  10075. /** Copies from a stringified UUID.
  10076. The string passed in should be one that was created with the toString() method.
  10077. */
  10078. Uuid& operator= (const String& uuidString);
  10079. /** Returns a pointer to the internal binary representation of the ID.
  10080. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10081. the constructor or operator= method that takes an array of uint8s.
  10082. */
  10083. const uint8* getRawData() const throw() { return value.asBytes; }
  10084. /** Creates a UUID from a 16-byte array.
  10085. @see getRawData
  10086. */
  10087. Uuid (const uint8* const rawData);
  10088. /** Sets this UUID from 16-bytes of raw data. */
  10089. Uuid& operator= (const uint8* const rawData);
  10090. juce_UseDebuggingNewOperator
  10091. private:
  10092. union
  10093. {
  10094. uint8 asBytes [16];
  10095. int asInt[4];
  10096. int64 asInt64[2];
  10097. } value;
  10098. };
  10099. #endif // __JUCE_UUID_JUCEHEADER__
  10100. /********* End of inlined file: juce_Uuid.h *********/
  10101. #endif
  10102. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10103. /********* Start of inlined file: juce_ZipFile.h *********/
  10104. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10105. #define __JUCE_ZIPFILE_JUCEHEADER__
  10106. /**
  10107. Decodes a ZIP file from a stream.
  10108. This can enumerate the items in a ZIP file and can create suitable stream objects
  10109. to read each one.
  10110. */
  10111. class JUCE_API ZipFile
  10112. {
  10113. public:
  10114. /** Creates a ZipFile for a given stream.
  10115. @param inputStream the stream to read from
  10116. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10117. will be deleted when this ZipFile object is deleted
  10118. */
  10119. ZipFile (InputStream* const inputStream,
  10120. const bool deleteStreamWhenDestroyed) throw();
  10121. /** Creates a ZipFile based for a file. */
  10122. ZipFile (const File& file);
  10123. /** Creates a ZipFile for an input source.
  10124. The inputSource object will be owned by the zip file, which will delete
  10125. it later when not needed.
  10126. */
  10127. ZipFile (InputSource* const inputSource);
  10128. /** Destructor. */
  10129. ~ZipFile() throw();
  10130. /**
  10131. Contains information about one of the entries in a ZipFile.
  10132. @see ZipFile::getEntry
  10133. */
  10134. struct ZipEntry
  10135. {
  10136. /** The name of the file, which may also include a partial pathname. */
  10137. String filename;
  10138. /** The file's original size. */
  10139. unsigned int uncompressedSize;
  10140. /** The last time the file was modified. */
  10141. Time fileTime;
  10142. };
  10143. /** Returns the number of items in the zip file. */
  10144. int getNumEntries() const throw();
  10145. /** Returns a structure that describes one of the entries in the zip file.
  10146. This may return zero if the index is out of range.
  10147. @see ZipFile::ZipEntry
  10148. */
  10149. const ZipEntry* getEntry (const int index) const throw();
  10150. /** Returns the index of the first entry with a given filename.
  10151. This uses a case-sensitive comparison to look for a filename in the
  10152. list of entries. It might return -1 if no match is found.
  10153. @see ZipFile::ZipEntry
  10154. */
  10155. int getIndexOfFileName (const String& fileName) const throw();
  10156. /** Returns a structure that describes one of the entries in the zip file.
  10157. This uses a case-sensitive comparison to look for a filename in the
  10158. list of entries. It might return 0 if no match is found.
  10159. @see ZipFile::ZipEntry
  10160. */
  10161. const ZipEntry* getEntry (const String& fileName) const throw();
  10162. /** Sorts the list of entries, based on the filename.
  10163. */
  10164. void sortEntriesByFilename();
  10165. /** Creates a stream that can read from one of the zip file's entries.
  10166. The stream that is returned must be deleted by the caller (and
  10167. zero might be returned if a stream can't be opened for some reason).
  10168. The stream must not be used after the ZipFile object that created
  10169. has been deleted.
  10170. */
  10171. InputStream* createStreamForEntry (const int index);
  10172. /** Uncompresses all of the files in the zip file.
  10173. This will expand all the entires into a target directory. The relative
  10174. paths of the entries are used.
  10175. @param targetDirectory the root folder to uncompress to
  10176. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10177. */
  10178. void uncompressTo (const File& targetDirectory,
  10179. const bool shouldOverwriteFiles = true);
  10180. juce_UseDebuggingNewOperator
  10181. private:
  10182. VoidArray entries;
  10183. friend class ZipInputStream;
  10184. CriticalSection lock;
  10185. InputStream* inputStream;
  10186. InputSource* inputSource;
  10187. bool deleteStreamWhenDestroyed;
  10188. int numEntries, centralRecStart;
  10189. #ifdef JUCE_DEBUG
  10190. int numOpenStreams;
  10191. #endif
  10192. void init();
  10193. int findEndOfZipEntryTable (InputStream* in);
  10194. ZipFile (const ZipFile&);
  10195. const ZipFile& operator= (const ZipFile&);
  10196. };
  10197. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10198. /********* End of inlined file: juce_ZipFile.h *********/
  10199. #endif
  10200. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10201. #endif
  10202. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10203. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10204. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10205. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10206. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10207. string into a localised version using the LocalisedStrings class.
  10208. @see LocalisedStrings
  10209. */
  10210. #define TRANS(stringLiteral) \
  10211. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10212. /**
  10213. Used to convert strings to localised foreign-language versions.
  10214. This is basically a look-up table of strings and their translated equivalents.
  10215. It can be loaded from a text file, so that you can supply a set of localised
  10216. versions of strings that you use in your app.
  10217. To use it in your code, simply call the translate() method on each string that
  10218. might have foreign versions, and if none is found, the method will just return
  10219. the original string.
  10220. The translation file should start with some lines specifying a description of
  10221. the language it contains, and also a list of ISO country codes where it might
  10222. be appropriate to use the file. After that, each line of the file should contain
  10223. a pair of quoted strings with an '=' sign.
  10224. E.g. for a french translation, the file might be:
  10225. @code
  10226. language: French
  10227. countries: fr be mc ch lu
  10228. "hello" = "bonjour"
  10229. "goodbye" = "au revoir"
  10230. @endcode
  10231. If the strings need to contain a quote character, they can use '\"' instead, and
  10232. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10233. (you can use this to add comments).
  10234. Note that this is a singleton class, so don't create or destroy the object directly.
  10235. There's also a TRANS(text) macro defined to make it easy to use the this.
  10236. E.g. @code
  10237. printSomething (TRANS("hello"));
  10238. @endcode
  10239. This macro is used in the Juce classes themselves, so your application has a chance to
  10240. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10241. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10242. code).
  10243. */
  10244. class JUCE_API LocalisedStrings
  10245. {
  10246. public:
  10247. /** Creates a set of translations from the text of a translation file.
  10248. When you create one of these, you can call setCurrentMappings() to make it
  10249. the set of mappings that the system's using.
  10250. */
  10251. LocalisedStrings (const String& fileContents) throw();
  10252. /** Creates a set of translations from a file.
  10253. When you create one of these, you can call setCurrentMappings() to make it
  10254. the set of mappings that the system's using.
  10255. */
  10256. LocalisedStrings (const File& fileToLoad) throw();
  10257. /** Destructor. */
  10258. ~LocalisedStrings() throw();
  10259. /** Selects the current set of mappings to be used by the system.
  10260. The object you pass in will be automatically deleted when no longer needed, so
  10261. don't keep a pointer to it. You can also pass in zero to remove the current
  10262. mappings.
  10263. See also the TRANS() macro, which uses the current set to do its translation.
  10264. @see translateWithCurrentMappings
  10265. */
  10266. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10267. /** Returns the currently selected set of mappings.
  10268. This is the object that was last passed to setCurrentMappings(). It may
  10269. be 0 if none has been created.
  10270. */
  10271. static LocalisedStrings* getCurrentMappings() throw();
  10272. /** Tries to translate a string using the currently selected set of mappings.
  10273. If no mapping has been set, or if the mapping doesn't contain a translation
  10274. for the string, this will just return the original string.
  10275. See also the TRANS() macro, which uses this method to do its translation.
  10276. @see setCurrentMappings, getCurrentMappings
  10277. */
  10278. static const String translateWithCurrentMappings (const String& text) throw();
  10279. /** Tries to translate a string using the currently selected set of mappings.
  10280. If no mapping has been set, or if the mapping doesn't contain a translation
  10281. for the string, this will just return the original string.
  10282. See also the TRANS() macro, which uses this method to do its translation.
  10283. @see setCurrentMappings, getCurrentMappings
  10284. */
  10285. static const String translateWithCurrentMappings (const char* text) throw();
  10286. /** Attempts to look up a string and return its localised version.
  10287. If the string isn't found in the list, the original string will be returned.
  10288. */
  10289. const String translate (const String& text) const throw();
  10290. /** Returns the name of the language specified in the translation file.
  10291. This is specified in the file using a line starting with "language:", e.g.
  10292. @code
  10293. language: german
  10294. @endcode
  10295. */
  10296. const String getLanguageName() const throw() { return languageName; }
  10297. /** Returns the list of suitable country codes listed in the translation file.
  10298. These is specified in the file using a line starting with "countries:", e.g.
  10299. @code
  10300. countries: fr be mc ch lu
  10301. @endcode
  10302. The country codes are supposed to be 2-character ISO complient codes.
  10303. */
  10304. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10305. juce_UseDebuggingNewOperator
  10306. private:
  10307. String languageName;
  10308. StringArray countryCodes;
  10309. StringPairArray translations;
  10310. void loadFromText (const String& fileContents) throw();
  10311. };
  10312. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10313. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10314. #endif
  10315. #ifndef __JUCE_STRING_JUCEHEADER__
  10316. #endif
  10317. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10318. #endif
  10319. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10320. #endif
  10321. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10322. /********* Start of inlined file: juce_XmlDocument.h *********/
  10323. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10324. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10325. /**
  10326. Parses a text-based XML document and creates an XmlElement object from it.
  10327. The parser will parse DTDs to load external entities but won't
  10328. check the document for validity against the DTD.
  10329. e.g.
  10330. @code
  10331. XmlDocument myDocument (File ("myfile.xml"));
  10332. XmlElement* mainElement = myDocument.getDocumentElement();
  10333. if (mainElement == 0)
  10334. {
  10335. String error = myDocument.getLastParseError();
  10336. }
  10337. else
  10338. {
  10339. ..use the element
  10340. }
  10341. @endcode
  10342. @see XmlElement
  10343. */
  10344. class JUCE_API XmlDocument
  10345. {
  10346. public:
  10347. /** Creates an XmlDocument from the xml text.
  10348. The text doesn't actually get parsed until the getDocumentElement() method is
  10349. called.
  10350. */
  10351. XmlDocument (const String& documentText) throw();
  10352. /** Creates an XmlDocument from a file.
  10353. The text doesn't actually get parsed until the getDocumentElement() method is
  10354. called.
  10355. */
  10356. XmlDocument (const File& file);
  10357. /** Destructor. */
  10358. ~XmlDocument() throw();
  10359. /** Creates an XmlElement object to represent the main document node.
  10360. This method will do the actual parsing of the text, and if there's a
  10361. parse error, it may returns 0 (and you can find out the error using
  10362. the getLastParseError() method).
  10363. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10364. first section of the file, and will only
  10365. return the outer document element - this
  10366. allows quick checking of large files to
  10367. see if they contain the correct type of
  10368. tag, without having to parse the entire file
  10369. @returns a new XmlElement which the caller will need to delete, or null if
  10370. there was an error.
  10371. @see getLastParseError
  10372. */
  10373. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10374. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10375. @returns the error, or an empty string if there was no error.
  10376. */
  10377. const String& getLastParseError() const throw();
  10378. /** Sets an input source object to use for parsing documents that reference external entities.
  10379. If the document has been created from a file, this probably won't be needed, but
  10380. if you're parsing some text and there might be a DTD that references external
  10381. files, you may need to create a custom input source that can retrieve the
  10382. other files it needs.
  10383. The object that is passed-in will be deleted automatically when no longer needed.
  10384. @see InputSource
  10385. */
  10386. void setInputSource (InputSource* const newSource) throw();
  10387. juce_UseDebuggingNewOperator
  10388. private:
  10389. String originalText;
  10390. const tchar* input;
  10391. bool outOfData, errorOccurred;
  10392. bool identifierLookupTable [128];
  10393. String lastError, dtdText;
  10394. StringArray tokenisedDTD;
  10395. bool needToLoadDTD;
  10396. InputSource* inputSource;
  10397. void setLastError (const String& desc, const bool carryOn) throw();
  10398. void skipHeader() throw();
  10399. void skipNextWhiteSpace() throw();
  10400. tchar readNextChar() throw();
  10401. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10402. void readChildElements (XmlElement* parent) throw();
  10403. int findNextTokenLength() throw();
  10404. void readQuotedString (String& result) throw();
  10405. void readEntity (String& result) throw();
  10406. const String getFileContents (const String& filename) const;
  10407. const String expandEntity (const String& entity);
  10408. const String expandExternalEntity (const String& entity);
  10409. const String getParameterEntity (const String& entity);
  10410. };
  10411. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10412. /********* End of inlined file: juce_XmlDocument.h *********/
  10413. #endif
  10414. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10415. #endif
  10416. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10417. #endif
  10418. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10419. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10420. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10421. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10422. /**
  10423. Acts as a critical section which processes can use to block each other.
  10424. @see CriticalSection
  10425. */
  10426. class JUCE_API InterProcessLock
  10427. {
  10428. public:
  10429. /** Creates a lock object.
  10430. @param name a name that processes will use to identify this lock object
  10431. */
  10432. InterProcessLock (const String& name) throw();
  10433. /** Destructor.
  10434. This will also release the lock if it's currently held by this process.
  10435. */
  10436. ~InterProcessLock() throw();
  10437. /** Attempts to lock the critical section.
  10438. @param timeOutMillisecs how many milliseconds to wait if the lock
  10439. is already held by another process - a value of
  10440. 0 will return immediately, negative values will wait
  10441. forever
  10442. @returns true if the lock could be gained within the timeout period, or
  10443. false if the timeout expired.
  10444. */
  10445. bool enter (int timeOutMillisecs = -1) throw();
  10446. /** Releases the lock if it's currently held by this process.
  10447. */
  10448. void exit() throw();
  10449. juce_UseDebuggingNewOperator
  10450. private:
  10451. void* internal;
  10452. String name;
  10453. int reentrancyLevel;
  10454. InterProcessLock (const InterProcessLock&);
  10455. const InterProcessLock& operator= (const InterProcessLock&);
  10456. };
  10457. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10458. /********* End of inlined file: juce_InterProcessLock.h *********/
  10459. #endif
  10460. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10461. /********* Start of inlined file: juce_Process.h *********/
  10462. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10463. #define __JUCE_PROCESS_JUCEHEADER__
  10464. /** Represents the current executable's process.
  10465. This contains methods for controlling the current application at the
  10466. process-level.
  10467. @see Thread, JUCEApplication
  10468. */
  10469. class JUCE_API Process
  10470. {
  10471. public:
  10472. enum ProcessPriority
  10473. {
  10474. LowPriority = 0,
  10475. NormalPriority = 1,
  10476. HighPriority = 2,
  10477. RealtimePriority = 3
  10478. };
  10479. /** Changes the current process's priority.
  10480. @param priority the process priority, where
  10481. 0=low, 1=normal, 2=high, 3=realtime
  10482. */
  10483. static void setPriority (const ProcessPriority priority);
  10484. /** Kills the current process immediately.
  10485. This is an emergency process terminator that kills the application
  10486. immediately - it's intended only for use only when something goes
  10487. horribly wrong.
  10488. @see JUCEApplication::quit
  10489. */
  10490. static void terminate();
  10491. /** Returns true if this application process is the one that the user is
  10492. currently using.
  10493. */
  10494. static bool isForegroundProcess() throw();
  10495. /** Raises the current process's privilege level.
  10496. Does nothing if this isn't supported by the current OS, or if process
  10497. privilege level is fixed.
  10498. */
  10499. static void raisePrivilege();
  10500. /** Lowers the current process's privilege level.
  10501. Does nothing if this isn't supported by the current OS, or if process
  10502. privilege level is fixed.
  10503. */
  10504. static void lowerPrivilege();
  10505. /** Returns true if this process is being hosted by a debugger.
  10506. */
  10507. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10508. };
  10509. #endif // __JUCE_PROCESS_JUCEHEADER__
  10510. /********* End of inlined file: juce_Process.h *********/
  10511. #endif
  10512. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10513. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10514. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10515. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10516. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10517. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10518. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10519. /**
  10520. Allows threads to wait for events triggered by other threads.
  10521. A thread can call wait() on a WaitableObject, and this will suspend the
  10522. calling thread until another thread wakes it up by calling the signal()
  10523. method.
  10524. */
  10525. class JUCE_API WaitableEvent
  10526. {
  10527. public:
  10528. /** Creates a WaitableEvent object. */
  10529. WaitableEvent() throw();
  10530. /** Destructor.
  10531. If other threads are waiting on this object when it gets deleted, this
  10532. can cause nasty errors, so be careful!
  10533. */
  10534. ~WaitableEvent() throw();
  10535. /** Suspends the calling thread until the event has been signalled.
  10536. This will wait until the object's signal() method is called by another thread,
  10537. or until the timeout expires.
  10538. After the event has been signalled, this method will return true and reset
  10539. the event.
  10540. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10541. value will cause it to wait forever.
  10542. @returns true if the object has been signalled, false if the timeout expires first.
  10543. @see signal, reset
  10544. */
  10545. bool wait (const int timeOutMilliseconds = -1) const throw();
  10546. /** Wakes up any threads that are currently waiting on this object.
  10547. If signal() is called when nothing is waiting, the next thread to call wait()
  10548. will return immediately and reset the signal.
  10549. @see wait, reset
  10550. */
  10551. void signal() const throw();
  10552. /** Resets the event to an unsignalled state.
  10553. If it's not already signalled, this does nothing.
  10554. */
  10555. void reset() const throw();
  10556. juce_UseDebuggingNewOperator
  10557. private:
  10558. void* internal;
  10559. WaitableEvent (const WaitableEvent&);
  10560. const WaitableEvent& operator= (const WaitableEvent&);
  10561. };
  10562. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10563. /********* End of inlined file: juce_WaitableEvent.h *********/
  10564. /********* Start of inlined file: juce_Thread.h *********/
  10565. #ifndef __JUCE_THREAD_JUCEHEADER__
  10566. #define __JUCE_THREAD_JUCEHEADER__
  10567. /**
  10568. Encapsulates a thread.
  10569. Subclasses derive from Thread and implement the run() method, in which they
  10570. do their business. The thread can then be started with the startThread() method
  10571. and controlled with various other methods.
  10572. This class also contains some thread-related static methods, such
  10573. as sleep(), yield(), getCurrentThreadId() etc.
  10574. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10575. MessageManagerLock
  10576. */
  10577. class JUCE_API Thread
  10578. {
  10579. public:
  10580. /**
  10581. Creates a thread.
  10582. When first created, the thread is not running. Use the startThread()
  10583. method to start it.
  10584. */
  10585. Thread (const String& threadName);
  10586. /** Destructor.
  10587. Deleting a Thread object that is running will only give the thread a
  10588. brief opportunity to stop itself cleanly, so it's recommended that you
  10589. should always call stopThread() with a decent timeout before deleting,
  10590. to avoid the thread being forcibly killed (which is a Bad Thing).
  10591. */
  10592. virtual ~Thread();
  10593. /** Must be implemented to perform the thread's actual code.
  10594. Remember that the thread must regularly check the threadShouldExit()
  10595. method whilst running, and if this returns true it should return from
  10596. the run() method as soon as possible to avoid being forcibly killed.
  10597. @see threadShouldExit, startThread
  10598. */
  10599. virtual void run() = 0;
  10600. // Thread control functions..
  10601. /** Starts the thread running.
  10602. This will start the thread's run() method.
  10603. (if it's already started, startThread() won't do anything).
  10604. @see stopThread
  10605. */
  10606. void startThread() throw();
  10607. /** Starts the thread with a given priority.
  10608. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10609. If the thread is already running, its priority will be changed.
  10610. @see startThread, setPriority
  10611. */
  10612. void startThread (const int priority) throw();
  10613. /** Attempts to stop the thread running.
  10614. This method will cause the threadShouldExit() method to return true
  10615. and call notify() in case the thread is currently waiting.
  10616. Hopefully the thread will then respond to this by exiting cleanly, and
  10617. the stopThread method will wait for a given time-period for this to
  10618. happen.
  10619. If the thread is stuck and fails to respond after the time-out, it gets
  10620. forcibly killed, which is a very bad thing to happen, as it could still
  10621. be holding locks, etc. which are needed by other parts of your program.
  10622. @param timeOutMilliseconds The number of milliseconds to wait for the
  10623. thread to finish before killing it by force. A negative
  10624. value in here will wait forever.
  10625. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10626. */
  10627. void stopThread (const int timeOutMilliseconds) throw();
  10628. /** Returns true if the thread is currently active */
  10629. bool isThreadRunning() const throw();
  10630. /** Sets a flag to tell the thread it should stop.
  10631. Calling this means that the threadShouldExit() method will then return true.
  10632. The thread should be regularly checking this to see whether it should exit.
  10633. @see threadShouldExit
  10634. @see waitForThreadToExit
  10635. */
  10636. void signalThreadShouldExit() throw();
  10637. /** Checks whether the thread has been told to stop running.
  10638. Threads need to check this regularly, and if it returns true, they should
  10639. return from their run() method at the first possible opportunity.
  10640. @see signalThreadShouldExit
  10641. */
  10642. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10643. /** Waits for the thread to stop.
  10644. This will waits until isThreadRunning() is false or until a timeout expires.
  10645. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10646. is less than zero, it will wait forever.
  10647. @returns true if the thread exits, or false if the timeout expires first.
  10648. */
  10649. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10650. /** Changes the thread's priority.
  10651. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10652. of 5 is normal.
  10653. */
  10654. void setPriority (const int priority) throw();
  10655. /** Changes the priority of the caller thread.
  10656. Similar to setPriority(), but this static method acts on the caller thread.
  10657. @see setPriority
  10658. */
  10659. static void setCurrentThreadPriority (const int priority) throw();
  10660. /** Sets the affinity mask for the thread.
  10661. This will only have an effect next time the thread is started - i.e. if the
  10662. thread is already running when called, it'll have no effect.
  10663. @see setCurrentThreadAffinityMask
  10664. */
  10665. void setAffinityMask (const uint32 affinityMask) throw();
  10666. /** Changes the affinity mask for the caller thread.
  10667. This will change the affinity mask for the thread that calls this static method.
  10668. @see setAffinityMask
  10669. */
  10670. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10671. // this can be called from any thread that needs to pause..
  10672. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10673. /** Yields the calling thread's current time-slot. */
  10674. static void JUCE_CALLTYPE yield() throw();
  10675. /** Makes the thread wait for a notification.
  10676. This puts the thread to sleep until either the timeout period expires, or
  10677. another thread calls the notify() method to wake it up.
  10678. @returns true if the event has been signalled, false if the timeout expires.
  10679. */
  10680. bool wait (const int timeOutMilliseconds) const throw();
  10681. /** Wakes up the thread.
  10682. If the thread has called the wait() method, this will wake it up.
  10683. @see wait
  10684. */
  10685. void notify() const throw();
  10686. /** A value type used for thread IDs.
  10687. @see getCurrentThreadId(), getThreadId()
  10688. */
  10689. typedef void* ThreadID;
  10690. /** Returns an id that identifies the caller thread.
  10691. To find the ID of a particular thread object, use getThreadId().
  10692. @returns a unique identifier that identifies the calling thread.
  10693. @see getThreadId
  10694. */
  10695. static ThreadID getCurrentThreadId() throw();
  10696. /** Finds the thread object that is currently running.
  10697. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10698. object associated with them, so this will return 0.
  10699. */
  10700. static Thread* getCurrentThread() throw();
  10701. /** Returns the ID of this thread.
  10702. That means the ID of this thread object - not of the thread that's calling the method.
  10703. This can change when the thread is started and stopped, and will be invalid if the
  10704. thread's not actually running.
  10705. @see getCurrentThreadId
  10706. */
  10707. ThreadID getThreadId() const throw();
  10708. /** Returns the name of the thread.
  10709. This is the name that gets set in the constructor.
  10710. */
  10711. const String getThreadName() const throw() { return threadName_; }
  10712. /** Returns the number of currently-running threads.
  10713. @returns the number of Thread objects known to be currently running.
  10714. @see stopAllThreads
  10715. */
  10716. static int getNumRunningThreads() throw();
  10717. /** Tries to stop all currently-running threads.
  10718. This will attempt to stop all the threads known to be running at the moment.
  10719. */
  10720. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10721. juce_UseDebuggingNewOperator
  10722. private:
  10723. const String threadName_;
  10724. void* volatile threadHandle_;
  10725. CriticalSection startStopLock;
  10726. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10727. int threadPriority_;
  10728. ThreadID threadId_;
  10729. uint32 affinityMask_;
  10730. bool volatile threadShouldExit_;
  10731. friend void JUCE_API juce_threadEntryPoint (void*);
  10732. static void threadEntryPoint (Thread* thread) throw();
  10733. Thread (const Thread&);
  10734. const Thread& operator= (const Thread&);
  10735. };
  10736. #endif // __JUCE_THREAD_JUCEHEADER__
  10737. /********* End of inlined file: juce_Thread.h *********/
  10738. /**
  10739. A critical section that allows multiple simultaneous readers.
  10740. Features of this type of lock are:
  10741. - Multiple readers can hold the lock at the same time, but only one writer
  10742. can hold it at once.
  10743. - Writers trying to gain the lock will be blocked until all readers and writers
  10744. have released it
  10745. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  10746. blocked until the writer has obtained and released it
  10747. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  10748. there are no other readers
  10749. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  10750. - Recursive locking is supported.
  10751. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  10752. */
  10753. class JUCE_API ReadWriteLock
  10754. {
  10755. public:
  10756. /**
  10757. Creates a ReadWriteLock object.
  10758. */
  10759. ReadWriteLock() throw();
  10760. /** Destructor.
  10761. If the object is deleted whilst locked, any subsequent behaviour
  10762. is unpredictable.
  10763. */
  10764. ~ReadWriteLock() throw();
  10765. /** Locks this object for reading.
  10766. Multiple threads can simulaneously lock the object for reading, but if another
  10767. thread has it locked for writing, then this will block until it releases the
  10768. lock.
  10769. @see exitRead, ScopedReadLock
  10770. */
  10771. void enterRead() const throw();
  10772. /** Releases the read-lock.
  10773. If the caller thread hasn't got the lock, this can have unpredictable results.
  10774. If the enterRead() method has been called multiple times by the thread, each
  10775. call must be matched by a call to exitRead() before other threads will be allowed
  10776. to take over the lock.
  10777. @see enterRead, ScopedReadLock
  10778. */
  10779. void exitRead() const throw();
  10780. /** Locks this object for writing.
  10781. This will block until any other threads that have it locked for reading or
  10782. writing have released their lock.
  10783. @see exitWrite, ScopedWriteLock
  10784. */
  10785. void enterWrite() const throw();
  10786. /** Tries to lock this object for writing.
  10787. This is like enterWrite(), but doesn't block - it returns true if it manages
  10788. to obtain the lock.
  10789. @see enterWrite
  10790. */
  10791. bool tryEnterWrite() const throw();
  10792. /** Releases the write-lock.
  10793. If the caller thread hasn't got the lock, this can have unpredictable results.
  10794. If the enterWrite() method has been called multiple times by the thread, each
  10795. call must be matched by a call to exit() before other threads will be allowed
  10796. to take over the lock.
  10797. @see enterWrite, ScopedWriteLock
  10798. */
  10799. void exitWrite() const throw();
  10800. juce_UseDebuggingNewOperator
  10801. private:
  10802. CriticalSection accessLock;
  10803. WaitableEvent waitEvent;
  10804. mutable int numWaitingWriters, numWriters;
  10805. mutable Thread::ThreadID writerThreadId;
  10806. mutable Array <Thread::ThreadID> readerThreads;
  10807. ReadWriteLock (const ReadWriteLock&);
  10808. const ReadWriteLock& operator= (const ReadWriteLock&);
  10809. };
  10810. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  10811. /********* End of inlined file: juce_ReadWriteLock.h *********/
  10812. #endif
  10813. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  10814. #endif
  10815. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10816. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  10817. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10818. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10819. /**
  10820. Automatically locks and unlocks a ReadWriteLock object.
  10821. Use one of these as a local variable to control access to a ReadWriteLock.
  10822. e.g. @code
  10823. ReadWriteLock myLock;
  10824. for (;;)
  10825. {
  10826. const ScopedReadLock myScopedLock (myLock);
  10827. // myLock is now locked
  10828. ...do some stuff...
  10829. // myLock gets unlocked here.
  10830. }
  10831. @endcode
  10832. @see ReadWriteLock, ScopedWriteLock
  10833. */
  10834. class JUCE_API ScopedReadLock
  10835. {
  10836. public:
  10837. /** Creates a ScopedReadLock.
  10838. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  10839. when the ScopedReadLock object is deleted, the ReadWriteLock will
  10840. be unlocked.
  10841. Make sure this object is created and deleted by the same thread,
  10842. otherwise there are no guarantees what will happen! Best just to use it
  10843. as a local stack object, rather than creating one with the new() operator.
  10844. */
  10845. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  10846. /** Destructor.
  10847. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  10848. Make sure this object is created and deleted by the same thread,
  10849. otherwise there are no guarantees what will happen!
  10850. */
  10851. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  10852. private:
  10853. const ReadWriteLock& lock_;
  10854. ScopedReadLock (const ScopedReadLock&);
  10855. const ScopedReadLock& operator= (const ScopedReadLock&);
  10856. };
  10857. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10858. /********* End of inlined file: juce_ScopedReadLock.h *********/
  10859. #endif
  10860. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10861. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  10862. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10863. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10864. /**
  10865. Automatically tries to lock and unlock a CriticalSection object.
  10866. Use one of these as a local variable to control access to a CriticalSection.
  10867. e.g. @code
  10868. CriticalSection myCriticalSection;
  10869. for (;;)
  10870. {
  10871. const ScopedTryLock myScopedTryLock (myCriticalSection);
  10872. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  10873. // should test this with the isLocked() method before doing your thread-unsafe
  10874. // action..
  10875. if (myScopedTryLock.isLocked())
  10876. {
  10877. ...do some stuff...
  10878. }
  10879. else
  10880. {
  10881. ..our attempt at locking failed because another thread had already locked it..
  10882. }
  10883. // myCriticalSection gets unlocked here (if it was locked)
  10884. }
  10885. @endcode
  10886. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  10887. */
  10888. class JUCE_API ScopedTryLock
  10889. {
  10890. public:
  10891. /** Creates a ScopedTryLock.
  10892. As soon as it is created, this will try to lock the CriticalSection, and
  10893. when the ScopedTryLock object is deleted, the CriticalSection will
  10894. be unlocked if the lock was successful.
  10895. Make sure this object is created and deleted by the same thread,
  10896. otherwise there are no guarantees what will happen! Best just to use it
  10897. as a local stack object, rather than creating one with the new() operator.
  10898. */
  10899. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  10900. /** Destructor.
  10901. The CriticalSection will be unlocked (if locked) when the destructor is called.
  10902. Make sure this object is created and deleted by the same thread,
  10903. otherwise there are no guarantees what will happen!
  10904. */
  10905. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  10906. /** Lock state
  10907. @return True if the CriticalSection is locked.
  10908. */
  10909. bool isLocked() const throw() { return lockWasSuccessful; }
  10910. private:
  10911. const CriticalSection& lock_;
  10912. const bool lockWasSuccessful;
  10913. ScopedTryLock (const ScopedTryLock&);
  10914. const ScopedTryLock& operator= (const ScopedTryLock&);
  10915. };
  10916. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10917. /********* End of inlined file: juce_ScopedTryLock.h *********/
  10918. #endif
  10919. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10920. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  10921. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10922. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10923. /**
  10924. Automatically locks and unlocks a ReadWriteLock object.
  10925. Use one of these as a local variable to control access to a ReadWriteLock.
  10926. e.g. @code
  10927. ReadWriteLock myLock;
  10928. for (;;)
  10929. {
  10930. const ScopedWriteLock myScopedLock (myLock);
  10931. // myLock is now locked
  10932. ...do some stuff...
  10933. // myLock gets unlocked here.
  10934. }
  10935. @endcode
  10936. @see ReadWriteLock, ScopedReadLock
  10937. */
  10938. class JUCE_API ScopedWriteLock
  10939. {
  10940. public:
  10941. /** Creates a ScopedWriteLock.
  10942. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  10943. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  10944. be unlocked.
  10945. Make sure this object is created and deleted by the same thread,
  10946. otherwise there are no guarantees what will happen! Best just to use it
  10947. as a local stack object, rather than creating one with the new() operator.
  10948. */
  10949. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  10950. /** Destructor.
  10951. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  10952. Make sure this object is created and deleted by the same thread,
  10953. otherwise there are no guarantees what will happen!
  10954. */
  10955. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  10956. private:
  10957. const ReadWriteLock& lock_;
  10958. ScopedWriteLock (const ScopedWriteLock&);
  10959. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  10960. };
  10961. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10962. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  10963. #endif
  10964. #ifndef __JUCE_THREAD_JUCEHEADER__
  10965. #endif
  10966. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10967. /********* Start of inlined file: juce_ThreadPool.h *********/
  10968. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10969. #define __JUCE_THREADPOOL_JUCEHEADER__
  10970. class ThreadPool;
  10971. class ThreadPoolThread;
  10972. /**
  10973. A task that is executed by a ThreadPool object.
  10974. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  10975. its threads.
  10976. The runJob() method needs to be implemented to do the task, and if the code that
  10977. does the work takes a significant time to run, it must keep checking the shouldExit()
  10978. method to see if something is trying to interrupt the job. If shouldExit() returns
  10979. true, the runJob() method must return immediately.
  10980. @see ThreadPool, Thread
  10981. */
  10982. class JUCE_API ThreadPoolJob
  10983. {
  10984. public:
  10985. /** Creates a thread pool job object.
  10986. After creating your job, add it to a thread pool with ThreadPool::addJob().
  10987. */
  10988. ThreadPoolJob (const String& name);
  10989. /** Destructor. */
  10990. virtual ~ThreadPoolJob();
  10991. /** Returns the name of this job.
  10992. @see setJobName
  10993. */
  10994. const String getJobName() const;
  10995. /** Changes the job's name.
  10996. @see getJobName
  10997. */
  10998. void setJobName (const String& newName);
  10999. /** These are the values that can be returned by the runJob() method.
  11000. */
  11001. enum JobStatus
  11002. {
  11003. jobHasFinished = 0, /**< indicates that the job has finished and can be
  11004. removed from the pool. */
  11005. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  11006. should be automatically deleted by the pool. */
  11007. jobNeedsRunningAgain /**< indicates that the job would like to be called
  11008. again when a thread is free. */
  11009. };
  11010. /** Peforms the actual work that this job needs to do.
  11011. Your subclass must implement this method, in which is does its work.
  11012. If the code in this method takes a significant time to run, it must repeatedly check
  11013. the shouldExit() method to see if something is trying to interrupt the job.
  11014. If shouldExit() ever returns true, the runJob() method must return immediately.
  11015. If this method returns jobHasFinished, then the job will be removed from the pool
  11016. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  11017. pool and will get a chance to run again as soon as a thread is free.
  11018. @see shouldExit()
  11019. */
  11020. virtual JobStatus runJob() = 0;
  11021. /** Returns true if this job is currently running its runJob() method. */
  11022. bool isRunning() const throw() { return isActive; }
  11023. /** Returns true if something is trying to interrupt this job and make it stop.
  11024. Your runJob() method must call this whenever it gets a chance, and if it ever
  11025. returns true, the runJob() method must return immediately.
  11026. @see signalJobShouldExit()
  11027. */
  11028. bool shouldExit() const throw() { return shouldStop; }
  11029. /** Calling this will cause the shouldExit() method to return true, and the job
  11030. should (if it's been implemented correctly) stop as soon as possible.
  11031. @see shouldExit()
  11032. */
  11033. void signalJobShouldExit();
  11034. juce_UseDebuggingNewOperator
  11035. private:
  11036. friend class ThreadPool;
  11037. friend class ThreadPoolThread;
  11038. String jobName;
  11039. ThreadPool* pool;
  11040. bool shouldStop, isActive, shouldBeDeleted;
  11041. };
  11042. /**
  11043. A set of threads that will run a list of jobs.
  11044. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11045. will be called by the next pooled thread that becomes free.
  11046. @see ThreadPoolJob, Thread
  11047. */
  11048. class JUCE_API ThreadPool
  11049. {
  11050. public:
  11051. /** Creates a thread pool.
  11052. Once you've created a pool, you can give it some things to do with the addJob()
  11053. method.
  11054. @param numberOfThreads the maximum number of actual threads to run.
  11055. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11056. until there are some jobs to run. If false, then
  11057. all the threads will be fired-up immediately so that
  11058. they're ready for action
  11059. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11060. inactive for this length of time, they will automatically
  11061. be stopped until more jobs come along and they're needed
  11062. */
  11063. ThreadPool (const int numberOfThreads,
  11064. const bool startThreadsOnlyWhenNeeded = true,
  11065. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11066. /** Destructor.
  11067. This will attempt to remove all the jobs before deleting, but if you want to
  11068. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11069. the pool.
  11070. */
  11071. ~ThreadPool();
  11072. /** Adds a job to the queue.
  11073. Once a job has been added, then the next time a thread is free, it will run
  11074. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11075. runJob() method, the pool will either remove the job from the pool or add it to
  11076. the back of the queue to be run again.
  11077. */
  11078. void addJob (ThreadPoolJob* const job);
  11079. /** Tries to remove a job from the pool.
  11080. If the job isn't yet running, this will simply remove it. If it is running, it
  11081. will wait for it to finish.
  11082. If the timeout period expires before the job finishes running, then the job will be
  11083. left in the pool and this will return false. It returns true if the job is sucessfully
  11084. stopped and removed.
  11085. @param job the job to remove
  11086. @param interruptIfRunning if true, then if the job is currently busy, its
  11087. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11088. to interrupt it. If false, then if the job will be allowed to run
  11089. until it stops normally (or the timeout expires)
  11090. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11091. before giving up and returning false
  11092. */
  11093. bool removeJob (ThreadPoolJob* const job,
  11094. const bool interruptIfRunning,
  11095. const int timeOutMilliseconds);
  11096. /** Tries clear all jobs from the pool.
  11097. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11098. methods called to try to interrupt them
  11099. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11100. before giving up and returning false
  11101. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11102. expires while waiting for them to stop
  11103. */
  11104. bool removeAllJobs (const bool interruptRunningJobs,
  11105. const int timeOutMilliseconds);
  11106. /** Returns the number of jobs currently running or queued.
  11107. */
  11108. int getNumJobs() const throw();
  11109. /** Returns one of the jobs in the queue.
  11110. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11111. around in the list, and this method may return 0 if the index is currently out-of-range.
  11112. */
  11113. ThreadPoolJob* getJob (const int index) const;
  11114. /** Returns true if the given job is currently queued or running.
  11115. @see isJobRunning()
  11116. */
  11117. bool contains (const ThreadPoolJob* const job) const throw();
  11118. /** Returns true if the given job is currently being run by a thread.
  11119. */
  11120. bool isJobRunning (const ThreadPoolJob* const job) const;
  11121. /** Waits until a job has finished running and has been removed from the pool.
  11122. This will wait until the job is no longer in the pool - i.e. until its
  11123. runJob() method returns ThreadPoolJob::jobHasFinished.
  11124. If the timeout period expires before the job finishes, this will return false;
  11125. it returns true if the job has finished successfully.
  11126. */
  11127. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11128. const int timeOutMilliseconds) const;
  11129. /** Returns a list of the names of all the jobs currently running or queued.
  11130. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11131. */
  11132. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  11133. /** Changes the priority of all the threads.
  11134. This will call Thread::setPriority() for each thread in the pool.
  11135. */
  11136. void setThreadPriorities (const int newPriority);
  11137. juce_UseDebuggingNewOperator
  11138. private:
  11139. const int numThreads, threadStopTimeout;
  11140. int priority;
  11141. Thread** threads;
  11142. VoidArray jobs;
  11143. CriticalSection lock;
  11144. uint32 lastJobEndTime;
  11145. friend class ThreadPoolThread;
  11146. bool runNextJob();
  11147. ThreadPool (const ThreadPool&);
  11148. const ThreadPool& operator= (const ThreadPool&);
  11149. };
  11150. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11151. /********* End of inlined file: juce_ThreadPool.h *********/
  11152. #endif
  11153. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11154. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11155. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11156. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11157. /**
  11158. Used by the TimeSliceThread class.
  11159. To register your class with a TimeSliceThread, derive from this class and
  11160. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11161. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11162. deleting your client!
  11163. @see TimeSliceThread
  11164. */
  11165. class JUCE_API TimeSliceClient
  11166. {
  11167. public:
  11168. /** Destructor. */
  11169. virtual ~TimeSliceClient() {}
  11170. /** Called back by a TimeSliceThread.
  11171. When you register this class with it, a TimeSliceThread will repeatedly call
  11172. this method.
  11173. The implementation of this method should use its time-slice to do something that's
  11174. quick - never block for longer than absolutely necessary.
  11175. @returns Your method should return true if it needs more time, or false if it's
  11176. not too busy and doesn't need calling back urgently. If all the thread's
  11177. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11178. up to half a second in between callbacks. You can force the TimeSliceThread
  11179. to wake up and poll again immediately by calling its notify() method.
  11180. */
  11181. virtual bool useTimeSlice() = 0;
  11182. };
  11183. /**
  11184. A thread that keeps a list of clients, and calls each one in turn, giving them
  11185. all a chance to run some sort of short task.
  11186. @see TimeSliceClient, Thread
  11187. */
  11188. class JUCE_API TimeSliceThread : public Thread
  11189. {
  11190. public:
  11191. /**
  11192. Creates a TimeSliceThread.
  11193. When first created, the thread is not running. Use the startThread()
  11194. method to start it.
  11195. */
  11196. TimeSliceThread (const String& threadName);
  11197. /** Destructor.
  11198. Deleting a Thread object that is running will only give the thread a
  11199. brief opportunity to stop itself cleanly, so it's recommended that you
  11200. should always call stopThread() with a decent timeout before deleting,
  11201. to avoid the thread being forcibly killed (which is a Bad Thing).
  11202. */
  11203. ~TimeSliceThread();
  11204. /** Adds a client to the list.
  11205. The client's callbacks will start immediately (possibly before the method
  11206. has returned).
  11207. */
  11208. void addTimeSliceClient (TimeSliceClient* const client);
  11209. /** Removes a client from the list.
  11210. This method will make sure that all callbacks to the client have completely
  11211. finished before the method returns.
  11212. */
  11213. void removeTimeSliceClient (TimeSliceClient* const client);
  11214. /** Returns the number of registered clients. */
  11215. int getNumClients() const throw();
  11216. /** Returns one of the registered clients. */
  11217. TimeSliceClient* getClient (const int index) const throw();
  11218. /** @internal */
  11219. void run();
  11220. juce_UseDebuggingNewOperator
  11221. private:
  11222. CriticalSection callbackLock, listLock;
  11223. Array <TimeSliceClient*> clients;
  11224. int index;
  11225. TimeSliceClient* clientBeingCalled;
  11226. bool clientsChanged;
  11227. TimeSliceThread (const TimeSliceThread&);
  11228. const TimeSliceThread& operator= (const TimeSliceThread&);
  11229. };
  11230. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11231. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11232. #endif
  11233. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11234. #endif
  11235. #endif
  11236. /********* End of inlined file: juce_core_includes.h *********/
  11237. // if you're compiling a command-line app, you might want to just include the core headers,
  11238. // so you can set this macro before including juce.h
  11239. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11240. /********* Start of inlined file: juce_app_includes.h *********/
  11241. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11242. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11243. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11244. /********* Start of inlined file: juce_Application.h *********/
  11245. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11246. #define __JUCE_APPLICATION_JUCEHEADER__
  11247. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11248. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11249. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11250. /********* Start of inlined file: juce_Component.h *********/
  11251. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11252. #define __JUCE_COMPONENT_JUCEHEADER__
  11253. /********* Start of inlined file: juce_MouseCursor.h *********/
  11254. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11255. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11256. class Image;
  11257. class RefCountedMouseCursor;
  11258. class ComponentPeer;
  11259. class Component;
  11260. /**
  11261. Represents a mouse cursor image.
  11262. This object can either be used to represent one of the standard mouse
  11263. cursor shapes, or a custom one generated from an image.
  11264. */
  11265. class JUCE_API MouseCursor
  11266. {
  11267. public:
  11268. /** The set of available standard mouse cursors. */
  11269. enum StandardCursorType
  11270. {
  11271. NoCursor = 0, /**< An invisible cursor. */
  11272. NormalCursor, /**< The stardard arrow cursor. */
  11273. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11274. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11275. CrosshairCursor, /**< A pair of crosshairs. */
  11276. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11277. that you're dragging a copy of something. */
  11278. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11279. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11280. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11281. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11282. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11283. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11284. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11285. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11286. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11287. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11288. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11289. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11290. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11291. };
  11292. /** Creates the standard arrow cursor. */
  11293. MouseCursor() throw();
  11294. /** Creates one of the standard mouse cursor */
  11295. MouseCursor (const StandardCursorType type) throw();
  11296. /** Creates a custom cursor from an image.
  11297. @param image the image to use for the cursor - if this is bigger than the
  11298. system can manage, it might get scaled down first, and might
  11299. also have to be turned to black-and-white if it can't do colour
  11300. cursors.
  11301. @param hotSpotX the x position of the cursor's hotspot within the image
  11302. @param hotSpotY the y position of the cursor's hotspot within the image
  11303. */
  11304. MouseCursor (Image& image,
  11305. const int hotSpotX,
  11306. const int hotSpotY) throw();
  11307. /** Creates a copy of another cursor object. */
  11308. MouseCursor (const MouseCursor& other) throw();
  11309. /** Copies this cursor from another object. */
  11310. const MouseCursor& operator= (const MouseCursor& other) throw();
  11311. /** Destructor. */
  11312. ~MouseCursor() throw();
  11313. /** Checks whether two mouse cursors are the same.
  11314. For custom cursors, two cursors created from the same image won't be
  11315. recognised as the same, only MouseCursor objects that have been
  11316. copied from the same object.
  11317. */
  11318. bool operator== (const MouseCursor& other) const throw();
  11319. /** Checks whether two mouse cursors are the same.
  11320. For custom cursors, two cursors created from the same image won't be
  11321. recognised as the same, only MouseCursor objects that have been
  11322. copied from the same object.
  11323. */
  11324. bool operator!= (const MouseCursor& other) const throw();
  11325. /** Makes the system show its default 'busy' cursor.
  11326. This will turn the system cursor to an hourglass or spinning beachball
  11327. until the next time the mouse is moved, or hideWaitCursor() is called.
  11328. This is handy if the message loop is about to block for a couple of
  11329. seconds while busy and you want to give the user feedback about this.
  11330. @see MessageManager::setTimeBeforeShowingWaitCursor
  11331. */
  11332. static void showWaitCursor() throw();
  11333. /** If showWaitCursor has been called, this will return the mouse to its
  11334. normal state.
  11335. This will look at what component is under the mouse, and update the
  11336. cursor to be the correct one for that component.
  11337. @see showWaitCursor
  11338. */
  11339. static void hideWaitCursor() throw();
  11340. juce_UseDebuggingNewOperator
  11341. private:
  11342. RefCountedMouseCursor* cursorHandle;
  11343. friend class Component;
  11344. void showInWindow (ComponentPeer* window) const throw();
  11345. void showInAllWindows() const throw();
  11346. void* getHandle() const throw();
  11347. };
  11348. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11349. /********* End of inlined file: juce_MouseCursor.h *********/
  11350. /********* Start of inlined file: juce_MouseListener.h *********/
  11351. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11352. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11353. /********* Start of inlined file: juce_MouseEvent.h *********/
  11354. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11355. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11356. class Component;
  11357. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11358. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11359. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11360. /**
  11361. Represents the state of the mouse buttons and modifier keys.
  11362. This is used both by mouse events and by KeyPress objects to describe
  11363. the state of keys such as shift, control, alt, etc.
  11364. @see KeyPress, MouseEvent::mods
  11365. */
  11366. class JUCE_API ModifierKeys
  11367. {
  11368. public:
  11369. /** Creates a ModifierKeys object from a raw set of flags.
  11370. @param flags to represent the keys that are down
  11371. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11372. rightButtonModifier, commandModifier, popupMenuClickModifier
  11373. */
  11374. ModifierKeys (const int flags = 0) throw();
  11375. /** Creates a copy of another object. */
  11376. ModifierKeys (const ModifierKeys& other) throw();
  11377. /** Copies this object from another one. */
  11378. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11379. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11380. This is a platform-agnostic way of checking for the operating system's
  11381. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11382. Windows/Linux, it's actually checking for the CTRL key.
  11383. */
  11384. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11385. /** Checks whether the user is trying to launch a pop-up menu.
  11386. This checks for platform-specific modifiers that might indicate that the user
  11387. is following the operating system's normal method of showing a pop-up menu.
  11388. So on Windows/Linux, this method is really testing for a right-click.
  11389. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11390. */
  11391. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11392. /** Checks whether the flag is set for the left mouse-button. */
  11393. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11394. /** Checks whether the flag is set for the right mouse-button.
  11395. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11396. this is platform-independent (and makes your code more explanatory too).
  11397. */
  11398. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11399. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11400. /** Tests for any of the mouse-button flags. */
  11401. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11402. /** Tests for any of the modifier key flags. */
  11403. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11404. /** Checks whether the shift key's flag is set. */
  11405. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11406. /** Checks whether the CTRL key's flag is set.
  11407. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11408. popup-menu modifiers.
  11409. @see isCommandDown, isPopupMenu
  11410. */
  11411. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11412. /** Checks whether the shift key's flag is set. */
  11413. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11414. /** Flags that represent the different keys. */
  11415. enum Flags
  11416. {
  11417. /** Shift key flag. */
  11418. shiftModifier = 1,
  11419. /** CTRL key flag. */
  11420. ctrlModifier = 2,
  11421. /** ALT key flag. */
  11422. altModifier = 4,
  11423. /** Left mouse button flag. */
  11424. leftButtonModifier = 16,
  11425. /** Right mouse button flag. */
  11426. rightButtonModifier = 32,
  11427. /** Middle mouse button flag. */
  11428. middleButtonModifier = 64,
  11429. #if JUCE_MAC
  11430. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11431. commandModifier = 8,
  11432. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11433. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11434. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11435. #else
  11436. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11437. commandModifier = ctrlModifier,
  11438. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11439. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11440. popupMenuClickModifier = rightButtonModifier,
  11441. #endif
  11442. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11443. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11444. /** Represents a combination of all the mouse buttons at once. */
  11445. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11446. };
  11447. /** Returns the raw flags for direct testing. */
  11448. inline int getRawFlags() const throw() { return flags; }
  11449. /** Tests a combination of flags and returns true if any of them are set. */
  11450. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11451. /** Creates a ModifierKeys object to represent the last-known state of the
  11452. keyboard and mouse buttons.
  11453. @see getCurrentModifiersRealtime
  11454. */
  11455. static const ModifierKeys getCurrentModifiers() throw();
  11456. /** Creates a ModifierKeys object to represent the current state of the
  11457. keyboard and mouse buttons.
  11458. This isn't often needed and isn't recommended, but will actively check all the
  11459. mouse and key states rather than just returning their last-known state like
  11460. getCurrentModifiers() does.
  11461. This is only needed in special circumstances for up-to-date modifier information
  11462. at times when the app's event loop isn't running normally.
  11463. */
  11464. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11465. private:
  11466. int flags;
  11467. static int currentModifierFlags;
  11468. friend class ComponentPeer;
  11469. static void updateCurrentModifiers() throw();
  11470. };
  11471. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11472. /********* End of inlined file: juce_ModifierKeys.h *********/
  11473. /**
  11474. Contains position and status information about a mouse event.
  11475. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11476. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11477. */
  11478. class JUCE_API MouseEvent
  11479. {
  11480. public:
  11481. /** Creates a MouseEvent.
  11482. Normally an application will never need to use this.
  11483. @param x the x position of the mouse, relative to the component that is passed-in
  11484. @param y the y position of the mouse, relative to the component that is passed-in
  11485. @param modifiers the key modifiers at the time of the event
  11486. @param originator the component that the mouse event applies to
  11487. @param eventTime the time the event happened
  11488. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11489. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11490. the same as the current mouse-x position.
  11491. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11492. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11493. the same as the current mouse-y position.
  11494. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11495. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11496. the same as the current mouse-event time.
  11497. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11498. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11499. */
  11500. MouseEvent (const int x, const int y,
  11501. const ModifierKeys& modifiers,
  11502. Component* const originator,
  11503. const Time& eventTime,
  11504. const int mouseDownX,
  11505. const int mouseDownY,
  11506. const Time& mouseDownTime,
  11507. const int numberOfClicks,
  11508. const bool mouseWasDragged) throw();
  11509. /** Destructor. */
  11510. ~MouseEvent() throw();
  11511. /** The x-position of the mouse when the event occurred.
  11512. This value is relative to the top-left of the component to which the
  11513. event applies (as indicated by the MouseEvent::eventComponent field).
  11514. */
  11515. int x;
  11516. /** The y-position of the mouse when the event occurred.
  11517. This value is relative to the top-left of the component to which the
  11518. event applies (as indicated by the MouseEvent::eventComponent field).
  11519. */
  11520. int y;
  11521. /** The key modifiers associated with the event.
  11522. This will let you find out which mouse buttons were down, as well as which
  11523. modifier keys were held down.
  11524. When used for mouse-up events, this will indicate the state of the mouse buttons
  11525. just before they were released, so that you can tell which button they let go of.
  11526. */
  11527. ModifierKeys mods;
  11528. /** The component that this event applies to.
  11529. This is usually the component that the mouse was over at the time, but for mouse-drag
  11530. events the mouse could actually be over a different component and the events are
  11531. still sent to the component that the button was originally pressed on.
  11532. The x and y member variables are relative to this component's position.
  11533. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11534. component, this pointer will be updated, but originalComponent remains unchanged.
  11535. @see originalComponent
  11536. */
  11537. Component* eventComponent;
  11538. /** The component that the event first occurred on.
  11539. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11540. component, this value remains unchanged to indicate the first component that received it.
  11541. @see eventComponent
  11542. */
  11543. Component* originalComponent;
  11544. /** The time that this mouse-event occurred.
  11545. */
  11546. Time eventTime;
  11547. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11548. The co-ordinate is relative to the component specified in MouseEvent::component.
  11549. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11550. */
  11551. int getMouseDownX() const throw();
  11552. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11553. The co-ordinate is relative to the component specified in MouseEvent::component.
  11554. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11555. */
  11556. int getMouseDownY() const throw();
  11557. /** Returns the straight-line distance between where the mouse is now and where it
  11558. was the last time the button was pressed.
  11559. This is quite handy for things like deciding whether the user has moved far enough
  11560. for it to be considered a drag operation.
  11561. @see getDistanceFromDragStartX
  11562. */
  11563. int getDistanceFromDragStart() const throw();
  11564. /** Returns the difference between the mouse's current x postion and where it was
  11565. when the button was last pressed.
  11566. @see getDistanceFromDragStart
  11567. */
  11568. int getDistanceFromDragStartX() const throw();
  11569. /** Returns the difference between the mouse's current y postion and where it was
  11570. when the button was last pressed.
  11571. @see getDistanceFromDragStart
  11572. */
  11573. int getDistanceFromDragStartY() const throw();
  11574. /** Returns true if the mouse has just been clicked.
  11575. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11576. the user has dragged the mouse more than a few pixels from the place where the
  11577. mouse-down occurred.
  11578. Once they have dragged it far enough for this method to return false, it will continue
  11579. to return false until the mouse-up, even if they move the mouse back to the same
  11580. position where they originally pressed it. This means that it's very handy for
  11581. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11582. callback to ignore any small movements they might make while clicking.
  11583. @returns true if the mouse wasn't dragged by more than a few pixels between
  11584. the last time the button was pressed and released.
  11585. */
  11586. bool mouseWasClicked() const throw();
  11587. /** For a click event, the number of times the mouse was clicked in succession.
  11588. So for example a double-click event will return 2, a triple-click 3, etc.
  11589. */
  11590. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11591. /** Returns the time that the mouse button has been held down for.
  11592. If called from a mouseDrag or mouseUp callback, this will return the
  11593. number of milliseconds since the corresponding mouseDown event occurred.
  11594. If called in other contexts, e.g. a mouseMove, then the returned value
  11595. may be 0 or an undefined value.
  11596. */
  11597. int getLengthOfMousePress() const throw();
  11598. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11599. The co-ordinates are relative to the top-left of the main monitor.
  11600. @see getMouseDownScreenX, Desktop::getMousePosition
  11601. */
  11602. int getScreenX() const throw();
  11603. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11604. The co-ordinates are relative to the top-left of the main monitor.
  11605. @see getMouseDownScreenY, Desktop::getMousePosition
  11606. */
  11607. int getScreenY() const throw();
  11608. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11609. The co-ordinates are relative to the top-left of the main monitor.
  11610. @see getScreenX, Desktop::getMousePosition
  11611. */
  11612. int getMouseDownScreenX() const throw();
  11613. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11614. The co-ordinates are relative to the top-left of the main monitor.
  11615. @see getScreenY, Desktop::getMousePosition
  11616. */
  11617. int getMouseDownScreenY() const throw();
  11618. /** Creates a version of this event that is relative to a different component.
  11619. The x and y positions of the event that is returned will have been
  11620. adjusted to be relative to the new component.
  11621. */
  11622. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11623. /** Changes the application-wide setting for the double-click time limit.
  11624. This is the maximum length of time between mouse-clicks for it to be
  11625. considered a double-click. It's used by the Component class.
  11626. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11627. */
  11628. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11629. /** Returns the application-wide setting for the double-click time limit.
  11630. This is the maximum length of time between mouse-clicks for it to be
  11631. considered a double-click. It's used by the Component class.
  11632. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11633. */
  11634. static int getDoubleClickTimeout() throw();
  11635. juce_UseDebuggingNewOperator
  11636. private:
  11637. int mouseDownX, mouseDownY;
  11638. Time mouseDownTime;
  11639. int numberOfClicks;
  11640. bool wasMovedSinceMouseDown;
  11641. };
  11642. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11643. /********* End of inlined file: juce_MouseEvent.h *********/
  11644. /**
  11645. A MouseListener can be registered with a component to receive callbacks
  11646. about mouse events that happen to that component.
  11647. @see Component::addMouseListener, Component::removeMouseListener
  11648. */
  11649. class JUCE_API MouseListener
  11650. {
  11651. public:
  11652. /** Destructor. */
  11653. virtual ~MouseListener() {}
  11654. /** Called when the mouse moves inside a component.
  11655. If the mouse button isn't pressed and the mouse moves over a component,
  11656. this will be called to let the component react to this.
  11657. A component will always get a mouseEnter callback before a mouseMove.
  11658. @param e details about the position and status of the mouse event, including
  11659. the source component in which it occurred
  11660. @see mouseEnter, mouseExit, mouseDrag, contains
  11661. */
  11662. virtual void mouseMove (const MouseEvent& e);
  11663. /** Called when the mouse first enters a component.
  11664. If the mouse button isn't pressed and the mouse moves into a component,
  11665. this will be called to let the component react to this.
  11666. When the mouse button is pressed and held down while being moved in
  11667. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11668. mouseDrag messages are sent to the component that the mouse was originally
  11669. clicked on, until the button is 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 mouseExit, mouseDrag, mouseMove, contains
  11673. */
  11674. virtual void mouseEnter (const MouseEvent& e);
  11675. /** Called when the mouse moves out of a component.
  11676. This will be called when the mouse moves off the edge of this
  11677. component.
  11678. If the mouse button was pressed, and it was then dragged off the
  11679. edge of the component and released, then this callback will happen
  11680. when the button is released, after the mouseUp callback.
  11681. @param e details about the position and status of the mouse event, including
  11682. the source component in which it occurred
  11683. @see mouseEnter, mouseDrag, mouseMove, contains
  11684. */
  11685. virtual void mouseExit (const MouseEvent& e);
  11686. /** Called when a mouse button is pressed.
  11687. The MouseEvent object passed in contains lots of methods for finding out
  11688. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11689. were held down at the time.
  11690. Once a button is held down, the mouseDrag method will be called when the
  11691. mouse moves, until the button is released.
  11692. @param e details about the position and status of the mouse event, including
  11693. the source component in which it occurred
  11694. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11695. */
  11696. virtual void mouseDown (const MouseEvent& e);
  11697. /** Called when the mouse is moved while a button is held down.
  11698. When a mouse button is pressed inside a component, that component
  11699. receives mouseDrag callbacks each time the mouse moves, even if the
  11700. mouse strays outside the component's bounds.
  11701. @param e details about the position and status of the mouse event, including
  11702. the source component in which it occurred
  11703. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11704. */
  11705. virtual void mouseDrag (const MouseEvent& e);
  11706. /** Called when a mouse button is released.
  11707. A mouseUp callback is sent to the component in which a button was pressed
  11708. even if the mouse is actually over a different component when the
  11709. button is released.
  11710. The MouseEvent object passed in contains lots of methods for finding out
  11711. which buttons were down just before they were released.
  11712. @param e details about the position and status of the mouse event, including
  11713. the source component in which it occurred
  11714. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11715. */
  11716. virtual void mouseUp (const MouseEvent& e);
  11717. /** Called when a mouse button has been double-clicked on a component.
  11718. The MouseEvent object passed in contains lots of methods for finding out
  11719. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11720. were held down at the time.
  11721. @param e details about the position and status of the mouse event, including
  11722. the source component in which it occurred
  11723. @see mouseDown, mouseUp
  11724. */
  11725. virtual void mouseDoubleClick (const MouseEvent& e);
  11726. /** Called when the mouse-wheel is moved.
  11727. This callback is sent to the component that the mouse is over when the
  11728. wheel is moved.
  11729. If not overridden, the component will forward this message to its parent, so
  11730. that parent components can collect mouse-wheel messages that happen to
  11731. child components which aren't interested in them.
  11732. @param e details about the position and status of the mouse event, including
  11733. the source component in which it occurred
  11734. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11735. value means the wheel has been pushed to the right, negative means it
  11736. was pushed to the left
  11737. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11738. value means the wheel has been pushed upwards, negative means it
  11739. was pushed downwards
  11740. */
  11741. virtual void mouseWheelMove (const MouseEvent& e,
  11742. float wheelIncrementX,
  11743. float wheelIncrementY);
  11744. private:
  11745. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11746. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11747. // if that happens, update your code to use the new one above.
  11748. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11749. };
  11750. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11751. /********* End of inlined file: juce_MouseListener.h *********/
  11752. /********* Start of inlined file: juce_ComponentListener.h *********/
  11753. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11754. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11755. class Component;
  11756. /**
  11757. Gets informed about changes to a component's hierarchy or position.
  11758. To monitor a component for changes, register a subclass of ComponentListener
  11759. with the component using Component::addComponentListener().
  11760. Be sure to deregister listeners before you delete them!
  11761. @see Component::addComponentListener, Component::removeComponentListener
  11762. */
  11763. class JUCE_API ComponentListener
  11764. {
  11765. public:
  11766. /** Destructor. */
  11767. virtual ~ComponentListener() {}
  11768. /** Called when the component's position or size changes.
  11769. @param component the component that was moved or resized
  11770. @param wasMoved true if the component's top-left corner has just moved
  11771. @param wasResized true if the component's width or height has just changed
  11772. @see Component::setBounds, Component::resized, Component::moved
  11773. */
  11774. virtual void componentMovedOrResized (Component& component,
  11775. bool wasMoved,
  11776. bool wasResized);
  11777. /** Called when the component is brought to the top of the z-order.
  11778. @param component the component that was moved
  11779. @see Component::toFront, Component::broughtToFront
  11780. */
  11781. virtual void componentBroughtToFront (Component& component);
  11782. /** Called when the component is made visible or invisible.
  11783. @param component the component that changed
  11784. @see Component::setVisible
  11785. */
  11786. virtual void componentVisibilityChanged (Component& component);
  11787. /** Called when the component has children added or removed.
  11788. @param component the component whose children were changed
  11789. @see Component::childrenChanged, Component::addChildComponent,
  11790. Component::removeChildComponent
  11791. */
  11792. virtual void componentChildrenChanged (Component& component);
  11793. /** Called to indicate that the component's parents have changed.
  11794. When a component is added or removed from its parent, all of its children
  11795. will produce this notification (recursively - so all children of its
  11796. children will also be called as well).
  11797. @param component the component that this listener is registered with
  11798. @see Component::parentHierarchyChanged
  11799. */
  11800. virtual void componentParentHierarchyChanged (Component& component);
  11801. /** Called when the component's name is changed.
  11802. @see Component::setName, Component::getName
  11803. */
  11804. virtual void componentNameChanged (Component& component);
  11805. };
  11806. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11807. /********* End of inlined file: juce_ComponentListener.h *********/
  11808. /********* Start of inlined file: juce_KeyListener.h *********/
  11809. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11810. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11811. /********* Start of inlined file: juce_KeyPress.h *********/
  11812. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11813. #define __JUCE_KEYPRESS_JUCEHEADER__
  11814. /**
  11815. Represents a key press, including any modifier keys that are needed.
  11816. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11817. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11818. */
  11819. class JUCE_API KeyPress
  11820. {
  11821. public:
  11822. /** Creates an (invalid) KeyPress.
  11823. @see isValid
  11824. */
  11825. KeyPress() throw();
  11826. /** Creates a KeyPress for a key and some modifiers.
  11827. e.g.
  11828. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11829. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11830. @param keyCode a code that represents the key - this value must be
  11831. one of special constants listed in this class, or an
  11832. 8-bit character code such as a letter (case is ignored),
  11833. digit or a simple key like "," or ".". Note that this
  11834. isn't the same as the textCharacter parameter, so for example
  11835. a keyCode of 'a' and a shift-key modifier should have a
  11836. textCharacter value of 'A'.
  11837. @param modifiers the modifiers to associate with the keystroke
  11838. @param textCharacter the character that would be printed if someone typed
  11839. this keypress into a text editor. This value may be
  11840. null if the keypress is a non-printing character
  11841. @see getKeyCode, isKeyCode, getModifiers
  11842. */
  11843. KeyPress (const int keyCode,
  11844. const ModifierKeys& modifiers,
  11845. const juce_wchar textCharacter) throw();
  11846. /** Creates a keypress with a keyCode but no modifiers or text character.
  11847. */
  11848. KeyPress (const int keyCode) throw();
  11849. /** Creates a copy of another KeyPress. */
  11850. KeyPress (const KeyPress& other) throw();
  11851. /** Copies this KeyPress from another one. */
  11852. const KeyPress& operator= (const KeyPress& other) throw();
  11853. /** Compares two KeyPress objects. */
  11854. bool operator== (const KeyPress& other) const throw();
  11855. /** Compares two KeyPress objects. */
  11856. bool operator!= (const KeyPress& other) const throw();
  11857. /** Returns true if this is a valid KeyPress.
  11858. A null keypress can be created by the default constructor, in case it's
  11859. needed.
  11860. */
  11861. bool isValid() const throw() { return keyCode != 0; }
  11862. /** Returns the key code itself.
  11863. This will either be one of the special constants defined in this class,
  11864. or an 8-bit character code.
  11865. */
  11866. int getKeyCode() const throw() { return keyCode; }
  11867. /** Returns the key modifiers.
  11868. @see ModifierKeys
  11869. */
  11870. const ModifierKeys getModifiers() const throw() { return mods; }
  11871. /** Returns the character that is associated with this keypress.
  11872. This is the character that you'd expect to see printed if you press this
  11873. keypress in a text editor or similar component.
  11874. */
  11875. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11876. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11877. the modifiers.
  11878. The values for key codes can either be one of the special constants defined in
  11879. this class, or an 8-bit character code.
  11880. @see getKeyCode
  11881. */
  11882. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11883. /** Converts a textual key description to a KeyPress.
  11884. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11885. This isn't designed to cope with any kind of input, but should be given the
  11886. strings that are created by the getTextDescription() method.
  11887. If the string can't be parsed, the object returned will be invalid.
  11888. @see getTextDescription
  11889. */
  11890. static const KeyPress createFromDescription (const String& textVersion) throw();
  11891. /** Creates a textual description of the key combination.
  11892. e.g. "CTRL + C" or "DELETE".
  11893. To store a keypress in a file, use this method, along with createFromDescription()
  11894. to retrieve it later.
  11895. */
  11896. const String getTextDescription() const throw();
  11897. /** Checks whether the user is currently holding down the keys that make up this
  11898. KeyPress.
  11899. Note that this will return false if any extra modifier keys are
  11900. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11901. then it will be false.
  11902. */
  11903. bool isCurrentlyDown() const throw();
  11904. /** Checks whether a particular key is held down, irrespective of modifiers.
  11905. The values for key codes can either be one of the special constants defined in
  11906. this class, or an 8-bit character code.
  11907. */
  11908. static bool isKeyCurrentlyDown (int keyCode) throw();
  11909. // Key codes
  11910. //
  11911. // Note that the actual values of these are platform-specific and may change
  11912. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  11913. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  11914. //
  11915. static const int spaceKey; /**< key-code for the space bar */
  11916. static const int escapeKey; /**< key-code for the escape key */
  11917. static const int returnKey; /**< key-code for the return key*/
  11918. static const int tabKey; /**< key-code for the tab key*/
  11919. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  11920. static const int backspaceKey; /**< key-code for the backspace key */
  11921. static const int insertKey; /**< key-code for the insert key */
  11922. static const int upKey; /**< key-code for the cursor-up key */
  11923. static const int downKey; /**< key-code for the cursor-down key */
  11924. static const int leftKey; /**< key-code for the cursor-left key */
  11925. static const int rightKey; /**< key-code for the cursor-right key */
  11926. static const int pageUpKey; /**< key-code for the page-up key */
  11927. static const int pageDownKey; /**< key-code for the page-down key */
  11928. static const int homeKey; /**< key-code for the home key */
  11929. static const int endKey; /**< key-code for the end key */
  11930. static const int F1Key; /**< key-code for the F1 key */
  11931. static const int F2Key; /**< key-code for the F2 key */
  11932. static const int F3Key; /**< key-code for the F3 key */
  11933. static const int F4Key; /**< key-code for the F4 key */
  11934. static const int F5Key; /**< key-code for the F5 key */
  11935. static const int F6Key; /**< key-code for the F6 key */
  11936. static const int F7Key; /**< key-code for the F7 key */
  11937. static const int F8Key; /**< key-code for the F8 key */
  11938. static const int F9Key; /**< key-code for the F9 key */
  11939. static const int F10Key; /**< key-code for the F10 key */
  11940. static const int F11Key; /**< key-code for the F11 key */
  11941. static const int F12Key; /**< key-code for the F12 key */
  11942. static const int F13Key; /**< key-code for the F13 key */
  11943. static const int F14Key; /**< key-code for the F14 key */
  11944. static const int F15Key; /**< key-code for the F15 key */
  11945. static const int F16Key; /**< key-code for the F16 key */
  11946. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  11947. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  11948. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  11949. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  11950. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  11951. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  11952. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  11953. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  11954. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  11955. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  11956. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  11957. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  11958. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  11959. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  11960. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  11961. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  11962. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  11963. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  11964. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  11965. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  11966. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  11967. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  11968. juce_UseDebuggingNewOperator
  11969. private:
  11970. int keyCode;
  11971. ModifierKeys mods;
  11972. juce_wchar textCharacter;
  11973. };
  11974. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  11975. /********* End of inlined file: juce_KeyPress.h *********/
  11976. class Component;
  11977. /**
  11978. Receives callbacks when keys are pressed.
  11979. You can add a key listener to a component to be informed when that component
  11980. gets key events. See the Component::addListener method for more details.
  11981. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  11982. */
  11983. class JUCE_API KeyListener
  11984. {
  11985. public:
  11986. /** Destructor. */
  11987. virtual ~KeyListener() {}
  11988. /** Called to indicate that a key has been pressed.
  11989. If your implementation returns true, then the key event is considered to have
  11990. been consumed, and will not be passed on to any other components. If it returns
  11991. false, then the key will be passed to other components that might want to use it.
  11992. @param key the keystroke, including modifier keys
  11993. @param originatingComponent the component that received the key event
  11994. @see keyStateChanged, Component::keyPressed
  11995. */
  11996. virtual bool keyPressed (const KeyPress& key,
  11997. Component* originatingComponent) = 0;
  11998. /** Called when any key is pressed or released.
  11999. When this is called, classes that might be interested in
  12000. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  12001. check whether their key has changed.
  12002. If your implementation returns true, then the key event is considered to have
  12003. been consumed, and will not be passed on to any other components. If it returns
  12004. false, then the key will be passed to other components that might want to use it.
  12005. @param originatingComponent the component that received the key event
  12006. @see KeyPress, Component::keyStateChanged
  12007. */
  12008. virtual bool keyStateChanged (Component* originatingComponent);
  12009. };
  12010. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  12011. /********* End of inlined file: juce_KeyListener.h *********/
  12012. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  12013. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12014. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12015. class Component;
  12016. /**
  12017. Controls the order in which focus moves between components.
  12018. The default algorithm used by this class to work out the order of traversal
  12019. is as follows:
  12020. - if two components both have an explicit focus order specified, then the
  12021. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12022. method).
  12023. - any component with an explicit focus order greater than 0 comes before ones
  12024. that don't have an order specified.
  12025. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12026. order.
  12027. If you need traversal in a more customised way, you can create a subclass
  12028. of KeyboardFocusTraverser that uses your own algorithm, and use
  12029. Component::createFocusTraverser() to create it.
  12030. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12031. */
  12032. class JUCE_API KeyboardFocusTraverser
  12033. {
  12034. public:
  12035. KeyboardFocusTraverser();
  12036. /** Destructor. */
  12037. virtual ~KeyboardFocusTraverser();
  12038. /** Returns the component that should be given focus after the specified one
  12039. when moving "forwards".
  12040. The default implementation will return the next component which is to the
  12041. right of or below this one.
  12042. This may return 0 if there's no suitable candidate.
  12043. */
  12044. virtual Component* getNextComponent (Component* current);
  12045. /** Returns the component that should be given focus after the specified one
  12046. when moving "backwards".
  12047. The default implementation will return the next component which is to the
  12048. left of or above this one.
  12049. This may return 0 if there's no suitable candidate.
  12050. */
  12051. virtual Component* getPreviousComponent (Component* current);
  12052. /** Returns the component that should receive focus be default within the given
  12053. parent component.
  12054. The default implementation will just return the foremost child component that
  12055. wants focus.
  12056. This may return 0 if there's no suitable candidate.
  12057. */
  12058. virtual Component* getDefaultComponent (Component* parentComponent);
  12059. };
  12060. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12061. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12062. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12063. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12064. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12065. /********* Start of inlined file: juce_Graphics.h *********/
  12066. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12067. #define __JUCE_GRAPHICS_JUCEHEADER__
  12068. /********* Start of inlined file: juce_Font.h *********/
  12069. #ifndef __JUCE_FONT_JUCEHEADER__
  12070. #define __JUCE_FONT_JUCEHEADER__
  12071. /********* Start of inlined file: juce_Typeface.h *********/
  12072. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12073. #define __JUCE_TYPEFACE_JUCEHEADER__
  12074. /********* Start of inlined file: juce_Path.h *********/
  12075. #ifndef __JUCE_PATH_JUCEHEADER__
  12076. #define __JUCE_PATH_JUCEHEADER__
  12077. /********* Start of inlined file: juce_AffineTransform.h *********/
  12078. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12079. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12080. /**
  12081. Represents a 2D affine-transformation matrix.
  12082. An affine transformation is a transformation such as a rotation, scale, shear,
  12083. resize or translation.
  12084. These are used for various 2D transformation tasks, e.g. with Path objects.
  12085. @see Path, Point, Line
  12086. */
  12087. class JUCE_API AffineTransform
  12088. {
  12089. public:
  12090. /** Creates an identity transform. */
  12091. AffineTransform() throw();
  12092. /** Creates a copy of another transform. */
  12093. AffineTransform (const AffineTransform& other) throw();
  12094. /** Creates a transform from a set of raw matrix values.
  12095. The resulting matrix is:
  12096. (mat00 mat01 mat02)
  12097. (mat10 mat11 mat12)
  12098. ( 0 0 1 )
  12099. */
  12100. AffineTransform (const float mat00, const float mat01, const float mat02,
  12101. const float mat10, const float mat11, const float mat12) throw();
  12102. /** Copies from another AffineTransform object */
  12103. const AffineTransform& operator= (const AffineTransform& other) throw();
  12104. /** Compares two transforms. */
  12105. bool operator== (const AffineTransform& other) const throw();
  12106. /** Compares two transforms. */
  12107. bool operator!= (const AffineTransform& other) const throw();
  12108. /** A ready-to-use identity transform, which you can use to append other
  12109. transformations to.
  12110. e.g. @code
  12111. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12112. .scaled (2.0f);
  12113. @endcode
  12114. */
  12115. static const AffineTransform identity;
  12116. /** Transforms a 2D co-ordinate using this matrix. */
  12117. void transformPoint (float& x,
  12118. float& y) const throw();
  12119. /** Transforms a 2D co-ordinate using this matrix. */
  12120. void transformPoint (double& x,
  12121. double& y) const throw();
  12122. /** Returns a new transform which is the same as this one followed by a translation. */
  12123. const AffineTransform translated (const float deltaX,
  12124. const float deltaY) const throw();
  12125. /** Returns a new transform which is a translation. */
  12126. static const AffineTransform translation (const float deltaX,
  12127. const float deltaY) throw();
  12128. /** Returns a transform which is the same as this one followed by a rotation.
  12129. The rotation is specified by a number of radians to rotate clockwise, centred around
  12130. the origin (0, 0).
  12131. */
  12132. const AffineTransform rotated (const float angleInRadians) const throw();
  12133. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12134. The rotation is specified by a number of radians to rotate clockwise, centred around
  12135. the co-ordinates passed in.
  12136. */
  12137. const AffineTransform rotated (const float angleInRadians,
  12138. const float pivotX,
  12139. const float pivotY) const throw();
  12140. /** Returns a new transform which is a rotation about (0, 0). */
  12141. static const AffineTransform rotation (const float angleInRadians) throw();
  12142. /** Returns a new transform which is a rotation about a given point. */
  12143. static const AffineTransform rotation (const float angleInRadians,
  12144. const float pivotX,
  12145. const float pivotY) throw();
  12146. /** Returns a transform which is the same as this one followed by a re-scaling.
  12147. The scaling is centred around the origin (0, 0).
  12148. */
  12149. const AffineTransform scaled (const float factorX,
  12150. const float factorY) const throw();
  12151. /** Returns a new transform which is a re-scale about the origin. */
  12152. static const AffineTransform scale (const float factorX,
  12153. const float factorY) throw();
  12154. /** Returns a transform which is the same as this one followed by a shear.
  12155. The shear is centred around the origin (0, 0).
  12156. */
  12157. const AffineTransform sheared (const float shearX,
  12158. const float shearY) const throw();
  12159. /** Returns a matrix which is the inverse operation of this one.
  12160. Some matrices don't have an inverse - in this case, the method will just return
  12161. an identity transform.
  12162. */
  12163. const AffineTransform inverted() const throw();
  12164. /** Returns the result of concatenating another transformation after this one. */
  12165. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12166. /** Returns true if this transform has no effect on points. */
  12167. bool isIdentity() const throw();
  12168. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12169. bool isSingularity() const throw();
  12170. juce_UseDebuggingNewOperator
  12171. /* The transform matrix is:
  12172. (mat00 mat01 mat02)
  12173. (mat10 mat11 mat12)
  12174. ( 0 0 1 )
  12175. */
  12176. float mat00, mat01, mat02;
  12177. float mat10, mat11, mat12;
  12178. private:
  12179. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12180. const float mat10, const float mat11, const float mat12) const throw();
  12181. };
  12182. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12183. /********* End of inlined file: juce_AffineTransform.h *********/
  12184. /********* Start of inlined file: juce_Point.h *********/
  12185. #ifndef __JUCE_POINT_JUCEHEADER__
  12186. #define __JUCE_POINT_JUCEHEADER__
  12187. /**
  12188. A pair of (x, y) co-ordinates.
  12189. Uses 32-bit floating point accuracy.
  12190. @see Line, Path, AffineTransform
  12191. */
  12192. class JUCE_API Point
  12193. {
  12194. public:
  12195. /** Creates a point with co-ordinates (0, 0). */
  12196. Point() throw();
  12197. /** Creates a copy of another point. */
  12198. Point (const Point& other) throw();
  12199. /** Creates a point from an (x, y) position. */
  12200. Point (const float x, const float y) throw();
  12201. /** Copies this point from another one.
  12202. @see setXY
  12203. */
  12204. const Point& operator= (const Point& other) throw();
  12205. /** Destructor. */
  12206. ~Point() throw();
  12207. /** Returns the point's x co-ordinate. */
  12208. inline float getX() const throw() { return x; }
  12209. /** Returns the point's y co-ordinate. */
  12210. inline float getY() const throw() { return y; }
  12211. /** Changes the point's x and y co-ordinates. */
  12212. void setXY (const float x,
  12213. const float y) throw();
  12214. /** Uses a transform to change the point's co-ordinates.
  12215. @see AffineTransform::transformPoint
  12216. */
  12217. void applyTransform (const AffineTransform& transform) throw();
  12218. juce_UseDebuggingNewOperator
  12219. private:
  12220. float x, y;
  12221. };
  12222. #endif // __JUCE_POINT_JUCEHEADER__
  12223. /********* End of inlined file: juce_Point.h *********/
  12224. /********* Start of inlined file: juce_Justification.h *********/
  12225. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12226. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12227. /**
  12228. Represents a type of justification to be used when positioning graphical items.
  12229. e.g. it indicates whether something should be placed top-left, top-right,
  12230. centred, etc.
  12231. It is used in various places wherever this kind of information is needed.
  12232. */
  12233. class JUCE_API Justification
  12234. {
  12235. public:
  12236. /** Creates a Justification object using a combination of flags. */
  12237. inline Justification (const int flags_) throw() : flags (flags_) {}
  12238. /** Creates a copy of another Justification object. */
  12239. Justification (const Justification& other) throw();
  12240. /** Copies another Justification object. */
  12241. const Justification& operator= (const Justification& other) throw();
  12242. /** Returns the raw flags that are set for this Justification object. */
  12243. inline int getFlags() const throw() { return flags; }
  12244. /** Tests a set of flags for this object.
  12245. @returns true if any of the flags passed in are set on this object.
  12246. */
  12247. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12248. /** Returns just the flags from this object that deal with vertical layout. */
  12249. int getOnlyVerticalFlags() const throw();
  12250. /** Returns just the flags from this object that deal with horizontal layout. */
  12251. int getOnlyHorizontalFlags() const throw();
  12252. /** Adjusts the position of a rectangle to fit it into a space.
  12253. The (x, y) position of the rectangle will be updated to position it inside the
  12254. given space according to the justification flags.
  12255. */
  12256. void applyToRectangle (int& x, int& y,
  12257. const int w, const int h,
  12258. const int spaceX, const int spaceY,
  12259. const int spaceW, const int spaceH) const throw();
  12260. /** Flag values that can be combined and used in the constructor. */
  12261. enum
  12262. {
  12263. /** Indicates that the item should be aligned against the left edge of the available space. */
  12264. left = 1,
  12265. /** Indicates that the item should be aligned against the right edge of the available space. */
  12266. right = 2,
  12267. /** Indicates that the item should be placed in the centre between the left and right
  12268. sides of the available space. */
  12269. horizontallyCentred = 4,
  12270. /** Indicates that the item should be aligned against the top edge of the available space. */
  12271. top = 8,
  12272. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12273. bottom = 16,
  12274. /** Indicates that the item should be placed in the centre between the top and bottom
  12275. sides of the available space. */
  12276. verticallyCentred = 32,
  12277. /** Indicates that lines of text should be spread out to fill the maximum width
  12278. available, so that both margins are aligned vertically.
  12279. */
  12280. horizontallyJustified = 64,
  12281. /** Indicates that the item should be centred vertically and horizontally.
  12282. This is equivalent to (horizontallyCentred | verticallyCentred)
  12283. */
  12284. centred = 36,
  12285. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12286. This is equivalent to (left | verticallyCentred)
  12287. */
  12288. centredLeft = 33,
  12289. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12290. This is equivalent to (right | verticallyCentred)
  12291. */
  12292. centredRight = 34,
  12293. /** Indicates that the item should be centred horizontally and placed at the top.
  12294. This is equivalent to (horizontallyCentred | top)
  12295. */
  12296. centredTop = 12,
  12297. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12298. This is equivalent to (horizontallyCentred | bottom)
  12299. */
  12300. centredBottom = 20,
  12301. /** Indicates that the item should be placed in the top-left corner.
  12302. This is equivalent to (left | top)
  12303. */
  12304. topLeft = 9,
  12305. /** Indicates that the item should be placed in the top-right corner.
  12306. This is equivalent to (right | top)
  12307. */
  12308. topRight = 10,
  12309. /** Indicates that the item should be placed in the bottom-left corner.
  12310. This is equivalent to (left | bottom)
  12311. */
  12312. bottomLeft = 17,
  12313. /** Indicates that the item should be placed in the bottom-left corner.
  12314. This is equivalent to (right | bottom)
  12315. */
  12316. bottomRight = 18
  12317. };
  12318. private:
  12319. int flags;
  12320. };
  12321. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12322. /********* End of inlined file: juce_Justification.h *********/
  12323. /**
  12324. A path is a sequence of lines and curves that may either form a closed shape
  12325. or be open-ended.
  12326. To use a path, you can create an empty one, then add lines and curves to it
  12327. to create shapes, then it can be rendered by a Graphics context or used
  12328. for geometric operations.
  12329. e.g. @code
  12330. Path myPath;
  12331. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12332. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12333. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12334. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12335. // add an ellipse as well, which will form a second sub-path within the path..
  12336. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12337. // double the width of the whole thing..
  12338. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12339. // and draw it to a graphics context with a 5-pixel thick outline.
  12340. g.strokePath (myPath, PathStrokeType (5.0f));
  12341. @endcode
  12342. A path object can actually contain multiple sub-paths, which may themselves
  12343. be open or closed.
  12344. @see PathFlatteningIterator, PathStrokeType, Graphics
  12345. */
  12346. class JUCE_API Path : private ArrayAllocationBase <float>
  12347. {
  12348. public:
  12349. /** Creates an empty path. */
  12350. Path() throw();
  12351. /** Creates a copy of another path. */
  12352. Path (const Path& other) throw();
  12353. /** Destructor. */
  12354. ~Path() throw();
  12355. /** Copies this path from another one. */
  12356. const Path& operator= (const Path& other) throw();
  12357. /** Returns true if the path doesn't contain any lines or curves. */
  12358. bool isEmpty() const throw();
  12359. /** Returns the smallest rectangle that contains all points within the path.
  12360. */
  12361. void getBounds (float& x, float& y,
  12362. float& w, float& h) const throw();
  12363. /** Returns the smallest rectangle that contains all points within the path
  12364. after it's been transformed with the given tranasform matrix.
  12365. */
  12366. void getBoundsTransformed (const AffineTransform& transform,
  12367. float& x, float& y,
  12368. float& w, float& h) const throw();
  12369. /** Checks whether a point lies within the path.
  12370. This is only relevent for closed paths (see closeSubPath()), and
  12371. may produce false results if used on a path which has open sub-paths.
  12372. The path's winding rule is taken into account by this method.
  12373. @see closeSubPath, setUsingNonZeroWinding
  12374. */
  12375. bool contains (const float x,
  12376. const float y) const throw();
  12377. /** Checks whether a line crosses the path.
  12378. This will return positive if the line crosses any of the paths constituent
  12379. lines or curves. It doesn't take into account whether the line is inside
  12380. or outside the path, or whether the path is open or closed.
  12381. */
  12382. bool intersectsLine (const float x1, const float y1,
  12383. const float x2, const float y2) throw();
  12384. /** Removes all lines and curves, resetting the path completely. */
  12385. void clear() throw();
  12386. /** Begins a new subpath with a given starting position.
  12387. This will move the path's current position to the co-ordinates passed in and
  12388. make it ready to draw lines or curves starting from this position.
  12389. After adding whatever lines and curves are needed, you can either
  12390. close the current sub-path using closeSubPath() or call startNewSubPath()
  12391. to move to a new sub-path, leaving the old one open-ended.
  12392. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12393. */
  12394. void startNewSubPath (const float startX,
  12395. const float startY) throw();
  12396. /** Closes a the current sub-path with a line back to its start-point.
  12397. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12398. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12399. to join the final point back to the start.
  12400. This ensures that closes shapes are recognised as such, and this is
  12401. important for tasks like drawing strokes, which needs to know whether to
  12402. draw end-caps or not.
  12403. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12404. */
  12405. void closeSubPath() throw();
  12406. /** Adds a line from the shape's last position to a new end-point.
  12407. This will connect the end-point of the last line or curve that was added
  12408. to a new point, using a straight line.
  12409. See the class description for an example of how to add lines and curves to a path.
  12410. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12411. */
  12412. void lineTo (const float endX,
  12413. const float endY) throw();
  12414. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12415. This will connect the end-point of the last line or curve that was added
  12416. to a new point, using a quadratic spline with one control-point.
  12417. See the class description for an example of how to add lines and curves to a path.
  12418. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12419. */
  12420. void quadraticTo (const float controlPointX,
  12421. const float controlPointY,
  12422. const float endPointX,
  12423. const float endPointY) throw();
  12424. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12425. This will connect the end-point of the last line or curve that was added
  12426. to a new point, using a cubic spline with two control-points.
  12427. See the class description for an example of how to add lines and curves to a path.
  12428. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12429. */
  12430. void cubicTo (const float controlPoint1X,
  12431. const float controlPoint1Y,
  12432. const float controlPoint2X,
  12433. const float controlPoint2Y,
  12434. const float endPointX,
  12435. const float endPointY) throw();
  12436. /** Returns the last point that was added to the path by one of the drawing methods.
  12437. */
  12438. const Point getCurrentPosition() const;
  12439. /** Adds a rectangle to the path.
  12440. The rectangle is added as a new sub-path. (Any currently open paths will be
  12441. left open).
  12442. @see addRoundedRectangle, addTriangle
  12443. */
  12444. void addRectangle (const float x, const float y,
  12445. const float w, const float h) throw();
  12446. /** Adds a rectangle with rounded corners to the path.
  12447. The rectangle is added as a new sub-path. (Any currently open paths will be
  12448. left open).
  12449. @see addRectangle, addTriangle
  12450. */
  12451. void addRoundedRectangle (const float x, const float y,
  12452. const float w, const float h,
  12453. float cornerSize) throw();
  12454. /** Adds a rectangle with rounded corners to the path.
  12455. The rectangle is added as a new sub-path. (Any currently open paths will be
  12456. left open).
  12457. @see addRectangle, addTriangle
  12458. */
  12459. void addRoundedRectangle (const float x, const float y,
  12460. const float w, const float h,
  12461. float cornerSizeX,
  12462. float cornerSizeY) throw();
  12463. /** Adds a triangle to the path.
  12464. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12465. left open).
  12466. Note that whether the vertices are specified in clockwise or anticlockwise
  12467. order will affect how the triangle is filled when it overlaps other
  12468. shapes (the winding order setting will affect this of course).
  12469. */
  12470. void addTriangle (const float x1, const float y1,
  12471. const float x2, const float y2,
  12472. const float x3, const float y3) throw();
  12473. /** Adds a quadrilateral to the path.
  12474. The quad is added as a new closed sub-path. (Any currently open paths will be
  12475. left open).
  12476. Note that whether the vertices are specified in clockwise or anticlockwise
  12477. order will affect how the quad is filled when it overlaps other
  12478. shapes (the winding order setting will affect this of course).
  12479. */
  12480. void addQuadrilateral (const float x1, const float y1,
  12481. const float x2, const float y2,
  12482. const float x3, const float y3,
  12483. const float x4, const float y4) throw();
  12484. /** Adds an ellipse to the path.
  12485. The shape is added as a new sub-path. (Any currently open paths will be
  12486. left open).
  12487. @see addArc
  12488. */
  12489. void addEllipse (const float x, const float y,
  12490. const float width, const float height) throw();
  12491. /** Adds an elliptical arc to the current path.
  12492. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12493. or anti-clockwise according to whether the end angle is greater than the start. This means
  12494. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12495. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12496. @param y the top edge of the rectangle in which the elliptical outline fits
  12497. @param width the width of the rectangle in which the elliptical outline fits
  12498. @param height the height of the rectangle in which the elliptical outline fits
  12499. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12500. top-centre of the ellipse)
  12501. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12502. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12503. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12504. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12505. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12506. it will be added to the current sub-path, continuing from the current postition
  12507. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12508. */
  12509. void addArc (const float x, const float y,
  12510. const float width, const float height,
  12511. const float fromRadians,
  12512. const float toRadians,
  12513. const bool startAsNewSubPath = false) throw();
  12514. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12515. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12516. or anti-clockwise according to whether the end angle is greater than the start. This means
  12517. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12518. @param centreX the centre x of the ellipse
  12519. @param centreY the centre y of the ellipse
  12520. @param radiusX the horizontal radius of the ellipse
  12521. @param radiusY the vertical radius of the ellipse
  12522. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12523. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12524. top-centre of the ellipse)
  12525. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12526. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12527. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12528. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12529. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12530. it will be added to the current sub-path, continuing from the current postition
  12531. @see addArc, arcTo
  12532. */
  12533. void addCentredArc (const float centreX, const float centreY,
  12534. const float radiusX, const float radiusY,
  12535. const float rotationOfEllipse,
  12536. const float fromRadians,
  12537. const float toRadians,
  12538. const bool startAsNewSubPath = false) throw();
  12539. /** Adds a "pie-chart" shape to the path.
  12540. The shape is added as a new sub-path. (Any currently open paths will be
  12541. left open).
  12542. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12543. or anti-clockwise according to whether the end angle is greater than the start. This means
  12544. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12545. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12546. @param y the top edge of the rectangle in which the elliptical outline fits
  12547. @param width the width of the rectangle in which the elliptical outline fits
  12548. @param height the height of the rectangle in which the elliptical outline fits
  12549. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12550. top-centre of the ellipse)
  12551. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12552. top-centre of the ellipse)
  12553. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12554. ellipse at its centre, where this value indicates the inner ellipse's size with
  12555. respect to the outer one.
  12556. @see addArc
  12557. */
  12558. void addPieSegment (const float x, const float y,
  12559. const float width, const float height,
  12560. const float fromRadians,
  12561. const float toRadians,
  12562. const float innerCircleProportionalSize);
  12563. /** Adds a line with a specified thickness.
  12564. The line is added as a new closed sub-path. (Any currently open paths will be
  12565. left open).
  12566. @see addArrow
  12567. */
  12568. void addLineSegment (const float startX, const float startY,
  12569. const float endX, const float endY,
  12570. float lineThickness) throw();
  12571. /** Adds a line with an arrowhead on the end.
  12572. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12573. left open).
  12574. */
  12575. void addArrow (const float startX, const float startY,
  12576. const float endX, const float endY,
  12577. float lineThickness,
  12578. float arrowheadWidth,
  12579. float arrowheadLength) throw();
  12580. /** Adds a star shape to the path.
  12581. */
  12582. void addStar (const float centreX,
  12583. const float centreY,
  12584. const int numberOfPoints,
  12585. const float innerRadius,
  12586. const float outerRadius,
  12587. const float startAngle = 0.0f);
  12588. /** Adds a speech-bubble shape to the path.
  12589. @param bodyX the left of the main body area of the bubble
  12590. @param bodyY the top of the main body area of the bubble
  12591. @param bodyW the width of the main body area of the bubble
  12592. @param bodyH the height of the main body area of the bubble
  12593. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12594. @param arrowTipX the x position that the tip of the arrow should connect to
  12595. @param arrowTipY the y position that the tip of the arrow should connect to
  12596. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12597. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12598. arrow's base should be - this is a proportional distance between 0 and 1.0
  12599. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12600. */
  12601. void addBubble (float bodyX, float bodyY,
  12602. float bodyW, float bodyH,
  12603. float cornerSize,
  12604. float arrowTipX,
  12605. float arrowTipY,
  12606. int whichSide,
  12607. float arrowPositionAlongEdgeProportional,
  12608. float arrowWidth);
  12609. /** Adds another path to this one.
  12610. The new path is added as a new sub-path. (Any currently open paths in this
  12611. path will be left open).
  12612. @param pathToAppend the path to add
  12613. */
  12614. void addPath (const Path& pathToAppend) throw();
  12615. /** Adds another path to this one, transforming it on the way in.
  12616. The new path is added as a new sub-path, its points being transformed by the given
  12617. matrix before being added.
  12618. @param pathToAppend the path to add
  12619. @param transformToApply an optional transform to apply to the incoming vertices
  12620. */
  12621. void addPath (const Path& pathToAppend,
  12622. const AffineTransform& transformToApply) throw();
  12623. /** Swaps the contents of this path with another one.
  12624. The internal data of the two paths is swapped over, so this is much faster than
  12625. copying it to a temp variable and back.
  12626. */
  12627. void swapWithPath (Path& other);
  12628. /** Applies a 2D transform to all the vertices in the path.
  12629. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12630. */
  12631. void applyTransform (const AffineTransform& transform) throw();
  12632. /** Rescales this path to make it fit neatly into a given space.
  12633. This is effectively a quick way of calling
  12634. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12635. @param x the x position of the rectangle to fit the path inside
  12636. @param y the y position of the rectangle to fit the path inside
  12637. @param width the width of the rectangle to fit the path inside
  12638. @param height the height of the rectangle to fit the path inside
  12639. @param preserveProportions if true, it will fit the path into the space without altering its
  12640. horizontal/vertical scale ratio; if false, it will distort the
  12641. path to fill the specified ratio both horizontally and vertically
  12642. @see applyTransform, getTransformToScaleToFit
  12643. */
  12644. void scaleToFit (const float x, const float y,
  12645. const float width, const float height,
  12646. const bool preserveProportions) throw();
  12647. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12648. @param x the x position of the rectangle to fit the path inside
  12649. @param y the y position of the rectangle to fit the path inside
  12650. @param width the width of the rectangle to fit the path inside
  12651. @param height the height of the rectangle to fit the path inside
  12652. @param preserveProportions if true, it will fit the path into the space without altering its
  12653. horizontal/vertical scale ratio; if false, it will distort the
  12654. path to fill the specified ratio both horizontally and vertically
  12655. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12656. than the available rectangle, so this describes how it should be
  12657. positioned within the space.
  12658. @returns an appropriate transformation
  12659. @see applyTransform, scaleToFit
  12660. */
  12661. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12662. const float width, const float height,
  12663. const bool preserveProportions,
  12664. const Justification& justificationType = Justification::centred) const throw();
  12665. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12666. Wherever two lines meet at an angle, this will replace the corner with a curve
  12667. of the given radius.
  12668. */
  12669. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12670. /** Changes the winding-rule to be used when filling the path.
  12671. If set to true (which is the default), then the path uses a non-zero-winding rule
  12672. to determine which points are inside the path. If set to false, it uses an
  12673. alternate-winding rule.
  12674. The winding-rule comes into play when areas of the shape overlap other
  12675. areas, and determines whether the overlapping regions are considered to be
  12676. inside or outside.
  12677. Changing this value just sets a flag - it doesn't affect the contents of the
  12678. path.
  12679. @see isUsingNonZeroWinding
  12680. */
  12681. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12682. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12683. The default for a new path is true.
  12684. @see setUsingNonZeroWinding
  12685. */
  12686. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12687. /** Iterates the lines and curves that a path contains.
  12688. @see Path, PathFlatteningIterator
  12689. */
  12690. class JUCE_API Iterator
  12691. {
  12692. public:
  12693. Iterator (const Path& path);
  12694. ~Iterator();
  12695. /** Moves onto the next element in the path.
  12696. If this returns false, there are no more elements. If it returns true,
  12697. the elementType variable will be set to the type of the current element,
  12698. and some of the x and y variables will be filled in with values.
  12699. */
  12700. bool next();
  12701. enum PathElementType
  12702. {
  12703. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12704. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12705. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12706. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12707. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12708. };
  12709. PathElementType elementType;
  12710. float x1, y1, x2, y2, x3, y3;
  12711. private:
  12712. const Path& path;
  12713. int index;
  12714. Iterator (const Iterator&);
  12715. const Iterator& operator= (const Iterator&);
  12716. };
  12717. /** Loads a stored path from a data stream.
  12718. The data in the stream must have been written using writePathToStream().
  12719. Note that this will append the stored path to whatever is currently in
  12720. this path, so you might need to call clear() beforehand.
  12721. @see loadPathFromData, writePathToStream
  12722. */
  12723. void loadPathFromStream (InputStream& source);
  12724. /** Loads a stored path from a block of data.
  12725. This is similar to loadPathFromStream(), but just reads from a block
  12726. of data. Useful if you're including stored shapes in your code as a
  12727. block of static data.
  12728. @see loadPathFromStream, writePathToStream
  12729. */
  12730. void loadPathFromData (const unsigned char* const data,
  12731. const int numberOfBytes) throw();
  12732. /** Stores the path by writing it out to a stream.
  12733. After writing out a path, you can reload it using loadPathFromStream().
  12734. @see loadPathFromStream, loadPathFromData
  12735. */
  12736. void writePathToStream (OutputStream& destination) const;
  12737. /** Creates a string containing a textual representation of this path.
  12738. @see restoreFromString
  12739. */
  12740. const String toString() const;
  12741. /** Restores this path from a string that was created with the toString() method.
  12742. @see toString()
  12743. */
  12744. void restoreFromString (const String& stringVersion);
  12745. juce_UseDebuggingNewOperator
  12746. private:
  12747. friend class PathFlatteningIterator;
  12748. friend class Path::Iterator;
  12749. int numElements;
  12750. float pathXMin, pathXMax, pathYMin, pathYMax;
  12751. bool useNonZeroWinding;
  12752. static const float lineMarker;
  12753. static const float moveMarker;
  12754. static const float quadMarker;
  12755. static const float cubicMarker;
  12756. static const float closeSubPathMarker;
  12757. };
  12758. #endif // __JUCE_PATH_JUCEHEADER__
  12759. /********* End of inlined file: juce_Path.h *********/
  12760. class Font;
  12761. class Typeface;
  12762. /**
  12763. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12764. @see Typeface, PositionedGlyph, GlyphArrangement
  12765. */
  12766. class JUCE_API TypefaceGlyphInfo
  12767. {
  12768. public:
  12769. /** Returns the path that describes the glyph's outline.
  12770. This is normalised to a height of 1.0, and its origin is the
  12771. left-hand edge of the glyph's baseline.
  12772. */
  12773. const Path& getPath() const throw() { return path; }
  12774. /** Returns the unicode character that this glyph represents. */
  12775. juce_wchar getCharacter() const throw() { return character; }
  12776. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12777. /** Returns the distance to leave between this and a following character.
  12778. The value returned is expressed as a proportion of the font's height.
  12779. */
  12780. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12781. /** Returns the typeface that this glyph belongs to. */
  12782. Typeface* getTypeface() const throw() { return typeface; }
  12783. private:
  12784. friend class Typeface;
  12785. struct KerningPair
  12786. {
  12787. juce_wchar character2;
  12788. float kerningAmount;
  12789. };
  12790. const juce_wchar character;
  12791. const Path path;
  12792. float width;
  12793. MemoryBlock kerningPairs;
  12794. Typeface* const typeface;
  12795. TypefaceGlyphInfo (const juce_wchar character,
  12796. const Path& shape,
  12797. const float horizontalSeparation,
  12798. Typeface* const typeface) throw();
  12799. ~TypefaceGlyphInfo() throw();
  12800. KerningPair& getKerningPair (const int index) const throw();
  12801. int getNumKerningPairs() const throw();
  12802. void addKerningPair (const juce_wchar subsequentCharacter,
  12803. const float extraKerningAmount) throw();
  12804. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12805. };
  12806. /**
  12807. Represents a size-independent system font.
  12808. A Font object represents a particular Typeface along with a specific size,
  12809. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12810. of the shapes of the glyphs and their properties.
  12811. */
  12812. class JUCE_API Typeface : public ReferenceCountedObject
  12813. {
  12814. public:
  12815. /** Tries to load a named system font and to initialise all the glyphs
  12816. appropriately from it.
  12817. @param faceName the name of the typeface, e.g. "Times"
  12818. @param bold whether to try to find a bold version of the font (may not always be available)
  12819. @param italic whether to try to find an italicised version of the font (may not always be available)
  12820. */
  12821. Typeface (const String& faceName,
  12822. const bool bold,
  12823. const bool italic);
  12824. /** Creates a copy of another typeface */
  12825. Typeface (const Typeface& other);
  12826. /** Destructor. */
  12827. ~Typeface();
  12828. /** Copies another typeface over this one. */
  12829. const Typeface& operator= (const Typeface& other) throw();
  12830. /** Returns a unique ID for the typeface.
  12831. This is based on the name and style, so can be used to compare two Typeface objects.
  12832. */
  12833. int hashCode() const throw() { return hash; }
  12834. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12835. const String& getName() const throw() { return typefaceName; }
  12836. /** Returns the font's ascent as a proportion of its height. */
  12837. float getAscent() const throw() { return ascent; }
  12838. /** Returns true if the font is flagged as being bold. */
  12839. bool isBold() const throw() { return bold; }
  12840. /** Returns true if the typeface's 'italic' flag is set. */
  12841. bool isItalic() const throw() { return italic; }
  12842. /** Finds the Path that describes the outline shape of a character.
  12843. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12844. height of the font).
  12845. This may return 0 if the typeface has no characters, but if the character
  12846. that is asked for is not found, it will first try to return a default
  12847. character instead.
  12848. */
  12849. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12850. /** Tries to find the information describing a glyph for this character.
  12851. If there isn't a glyph specifically for the character it will return
  12852. a default glyph instead; if the typeface is empty, it may return a null
  12853. pointer.
  12854. */
  12855. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12856. /** Deletes all the glyphs and kerning data fom the typeface. */
  12857. void clear() throw();
  12858. /** Adds a glyph to the typeface.
  12859. This is typically only called by the platform-specific code that generates
  12860. the typeface from a system font.
  12861. */
  12862. void addGlyph (const juce_wchar character,
  12863. const Path& path,
  12864. const float horizontalSpacing) throw();
  12865. /** Adds a kerning distance to the typeface.
  12866. The extra amount passed in is expressed as a proportion of the font's
  12867. height, normalised to 1.0.
  12868. This is typically only called by the platform-specific code that generates
  12869. the typeface from a system font.
  12870. */
  12871. void addKerningPair (const juce_wchar firstChar,
  12872. const juce_wchar secondChar,
  12873. const float extraAmount) throw();
  12874. /** Sets the typeface's name.
  12875. This is typically only called by the platform-specific code that generates
  12876. the typeface from a system font. Calling this method won't actually affect
  12877. the underlying font being used.
  12878. */
  12879. void setName (const String& name) throw();
  12880. /** Sets the font's ascent value, as a proportion of the font height.
  12881. This is typically only called by the platform-specific code that generates
  12882. the typeface from a system font.
  12883. */
  12884. void setAscent (const float newAscent) throw();
  12885. /** Sets the typeface's 'bold' flag.
  12886. This is typically only called by the platform-specific code that generates
  12887. the typeface from a system font.
  12888. */
  12889. void setBold (const bool shouldBeBold) throw();
  12890. /** Sets the typeface's 'italic' flag.
  12891. This is typically only called by the platform-specific code that generates
  12892. the typeface from a system font.
  12893. */
  12894. void setItalic (const bool shouldBeItalic) throw();
  12895. /** Changes the character index to use as the default character.
  12896. This is the character that gets returned for characters which don't have a
  12897. glyph set for them.
  12898. */
  12899. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12900. /** Creates a typeface from data created using Typeface::serialise().
  12901. This will attempt to load a compressed typeface that was created using
  12902. the Typeface::serialise() method. This is handy if you want to store
  12903. a typeface in your application as a binary blob, and use it without
  12904. having to actually install it on the computer.
  12905. @see Typeface::serialise()
  12906. */
  12907. Typeface (InputStream& serialisedTypefaceStream);
  12908. /** Writes the typeface to a stream (using a proprietary format).
  12909. This lets you save a typeface and reload it using the
  12910. Typeface::Typeface (InputStream&) constructor. The data's saved in
  12911. a compressed format.
  12912. @see Typeface::Typeface (InputStream&)
  12913. */
  12914. void serialise (OutputStream& outputStream);
  12915. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  12916. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  12917. juce_UseDebuggingNewOperator
  12918. private:
  12919. VoidArray glyphs;
  12920. short lookupTable [128];
  12921. String typefaceName;
  12922. int hash;
  12923. float ascent; // as a proportion of the height
  12924. bool bold, italic, isFullyPopulated;
  12925. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  12926. Typeface() throw();
  12927. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  12928. friend class Font;
  12929. friend class TypefaceCache;
  12930. friend class FontGlyphAlphaMap;
  12931. static const Ptr getTypefaceFor (const Font& font) throw();
  12932. // this is a platform-dependent method that will look for the given typeface
  12933. // and set up its kerning tables, etc. accordingly.
  12934. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  12935. // to the typeface immediately, rather than having to add them later on-demand.
  12936. void initialiseTypefaceCharacteristics (const String& fontName,
  12937. bool bold, bool italic,
  12938. bool addAllGlyphsToFont) throw();
  12939. // platform-specific routine to look up and add a glyph to this typeface
  12940. bool findAndAddSystemGlyph (juce_wchar character) throw();
  12941. void updateHashCode() throw();
  12942. };
  12943. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  12944. /********* End of inlined file: juce_Typeface.h *********/
  12945. /**
  12946. Represents a particular font, including its size, style, etc.
  12947. Apart from the typeface to be used, a Font object also dictates whether
  12948. the font is bold, italic, underlined, how big it is, and its kerning and
  12949. horizontal scale factor.
  12950. @see Typeface
  12951. */
  12952. class JUCE_API Font
  12953. {
  12954. public:
  12955. /** A combination of these values is used by the constructor to specify the
  12956. style of font to use.
  12957. */
  12958. enum FontStyleFlags
  12959. {
  12960. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  12961. bold = 1, /**< boldens the font. @see setStyleFlags */
  12962. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  12963. underlined = 4 /**< underlines the font. @see setStyleFlags */
  12964. };
  12965. /** Creates a sans-serif font in a given size.
  12966. @param fontHeight the height in pixels (can be fractional)
  12967. @param styleFlags the style to use - this can be a combination of the
  12968. Font::bold, Font::italic and Font::underlined, or
  12969. just Font::plain for the normal style.
  12970. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12971. */
  12972. Font (const float fontHeight,
  12973. const int styleFlags = plain) throw();
  12974. /** Creates a font with a given typeface and parameters.
  12975. @param typefaceName the name of the typeface to use
  12976. @param fontHeight the height in pixels (can be fractional)
  12977. @param styleFlags the style to use - this can be a combination of the
  12978. Font::bold, Font::italic and Font::underlined, or
  12979. just Font::plain for the normal style.
  12980. @see FontStyleFlags, getDefaultSansSerifFontName, setDefaultSansSerifFontName
  12981. */
  12982. Font (const String& typefaceName,
  12983. const float fontHeight,
  12984. const int styleFlags) throw();
  12985. /** Creates a copy of another Font object. */
  12986. Font (const Font& other) throw();
  12987. /** Creates a font based on a typeface.
  12988. The font object stores its own internal copy of the typeface, so you can safely
  12989. delete the one passed in after calling this.
  12990. */
  12991. Font (const Typeface& typeface) throw();
  12992. /** Creates a basic sans-serif font at a default height.
  12993. You should use one of the other constructors for creating a font that you're planning
  12994. on drawing with - this constructor is here to help initialise objects before changing
  12995. the font's settings later.
  12996. */
  12997. Font() throw();
  12998. /** Copies this font from another one. */
  12999. const Font& operator= (const Font& other) throw();
  13000. bool operator== (const Font& other) const throw();
  13001. bool operator!= (const Font& other) const throw();
  13002. /** Destructor. */
  13003. ~Font() throw();
  13004. /** Changes the name of the typeface family.
  13005. e.g. "Arial", "Courier", etc.
  13006. If a suitable font isn't found on the machine, it'll just use a default instead.
  13007. */
  13008. void setTypefaceName (const String& faceName) throw();
  13009. /** Returns the name of the typeface family that this font uses.
  13010. e.g. "Arial", "Courier", etc.
  13011. */
  13012. const String& getTypefaceName() const throw() { return typefaceName; }
  13013. /** Returns a platform-specific font family that is recommended for sans-serif fonts.
  13014. This is the typeface that will be used when a font is created without
  13015. specifying another name.
  13016. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  13017. setDefaultSansSerifFontName
  13018. */
  13019. static const String getDefaultSansSerifFontName() throw();
  13020. /** Returns a platform-specific font family that is recommended for serif fonts.
  13021. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13022. */
  13023. static const String getDefaultSerifFontName() throw();
  13024. /** Returns a platform-specific font family that is recommended for monospaced fonts.
  13025. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13026. */
  13027. static const String getDefaultMonospacedFontName() throw();
  13028. /** Changes the default sans-serif typeface family name.
  13029. This changes the value that is returned by getDefaultSansSerifFontName(), so
  13030. changing this will change the default system font used.
  13031. @see getDefaultSansSerifFontName
  13032. */
  13033. static void setDefaultSansSerifFontName (const String& name) throw();
  13034. /** Returns the total height of this font.
  13035. This is the maximum height, from the top of the ascent to the bottom of the
  13036. descenders.
  13037. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13038. */
  13039. float getHeight() const throw() { return height; }
  13040. /** Changes the font's height.
  13041. @see getHeight, setHeightWithoutChangingWidth
  13042. */
  13043. void setHeight (float newHeight) throw();
  13044. /** Changes the font's height without changing its width.
  13045. This alters the horizontal scale to compensate for the change in height.
  13046. */
  13047. void setHeightWithoutChangingWidth (float newHeight) throw();
  13048. /** Returns the height of the font above its baseline.
  13049. This is the maximum height from the baseline to the top.
  13050. @see getHeight, getDescent
  13051. */
  13052. float getAscent() const throw();
  13053. /** Returns the amount that the font descends below its baseline.
  13054. This is calculated as (getHeight() - getAscent()).
  13055. @see getAscent, getHeight
  13056. */
  13057. float getDescent() const throw();
  13058. /** Returns the font's style flags.
  13059. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13060. enum, to describe whether the font is bold, italic, etc.
  13061. @see FontStyleFlags
  13062. */
  13063. int getStyleFlags() const throw() { return styleFlags; }
  13064. /** Changes the font's style.
  13065. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13066. enum, to set the font's properties
  13067. @see FontStyleFlags
  13068. */
  13069. void setStyleFlags (const int newFlags) throw();
  13070. /** Makes the font bold or non-bold. */
  13071. void setBold (const bool shouldBeBold) throw();
  13072. /** Returns true if the font is bold. */
  13073. bool isBold() const throw();
  13074. /** Makes the font italic or non-italic. */
  13075. void setItalic (const bool shouldBeItalic) throw();
  13076. /** Returns true if the font is italic. */
  13077. bool isItalic() const throw();
  13078. /** Makes the font underlined or non-underlined. */
  13079. void setUnderline (const bool shouldBeUnderlined) throw();
  13080. /** Returns true if the font is underlined. */
  13081. bool isUnderlined() const throw();
  13082. /** Changes the font's horizontal scale factor.
  13083. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13084. narrower, greater than 1.0 will be stretched out.
  13085. */
  13086. void setHorizontalScale (const float scaleFactor) throw();
  13087. /** Returns the font's horizontal scale.
  13088. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13089. than 1.0 will be stretched out.
  13090. @see setHorizontalScale
  13091. */
  13092. float getHorizontalScale() const throw() { return horizontalScale; }
  13093. /** Changes the font's kerning.
  13094. @param extraKerning a multiple of the font's height that will be added
  13095. to space between the characters. So a value of zero is
  13096. normal spacing, positive values spread the letters out,
  13097. negative values make them closer together.
  13098. */
  13099. void setExtraKerningFactor (const float extraKerning) throw();
  13100. /** Returns the font's kerning.
  13101. This is the extra space added between adjacent characters, as a proportion
  13102. of the font's height.
  13103. A value of zero is normal spacing, positive values will spread the letters
  13104. out more, and negative values make them closer together.
  13105. */
  13106. float getExtraKerningFactor() const throw() { return kerning; }
  13107. /** Changes all the font's characteristics with one call. */
  13108. void setSizeAndStyle (const float newHeight,
  13109. const int newStyleFlags,
  13110. const float newHorizontalScale,
  13111. const float newKerningAmount) throw();
  13112. /** Resets this font's characteristics.
  13113. This is basically like saying "myFont = Font();", because it resets the
  13114. typeface, size, style, etc to a default state. Not very useful to most
  13115. people, its raison d'etre is to help the Graphics class be more efficient.
  13116. */
  13117. void resetToDefaultState() throw();
  13118. /** Returns the total width of a string as it would be drawn using this font.
  13119. For a more accurate floating-point result, use getStringWidthFloat().
  13120. */
  13121. int getStringWidth (const String& text) const throw();
  13122. /** Returns the total width of a string as it would be drawn using this font.
  13123. @see getStringWidth
  13124. */
  13125. float getStringWidthFloat (const String& text) const throw();
  13126. /** Returns the typeface used by this font.
  13127. Note that the object returned may go out of scope if this font is deleted
  13128. or has its style changed.
  13129. */
  13130. Typeface* getTypeface() const throw();
  13131. /** Creates an array of Font objects to represent all the fonts on the system.
  13132. If you just need the names of the typefaces, you can also use
  13133. findAllTypefaceNames() instead.
  13134. @param results the array to which new Font objects will be added.
  13135. */
  13136. static void findFonts (OwnedArray<Font>& results) throw();
  13137. /** Returns a list of all the available typeface names.
  13138. The names returned can be passed into setTypefaceName().
  13139. You can use this instead of findFonts() if you only need their names, and not
  13140. font objects.
  13141. */
  13142. static const StringArray findAllTypefaceNames() throw();
  13143. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13144. in the requested typeface.
  13145. */
  13146. static const String getFallbackFontName() throw();
  13147. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13148. available in whatever font you're trying to use.
  13149. */
  13150. static void setFallbackFontName (const String& name) throw();
  13151. juce_UseDebuggingNewOperator
  13152. private:
  13153. friend class FontGlyphAlphaMap;
  13154. friend class TypefaceCache;
  13155. String typefaceName;
  13156. float height, horizontalScale, kerning;
  13157. mutable float ascent;
  13158. int styleFlags;
  13159. mutable Typeface::Ptr typeface;
  13160. // platform-specific calls
  13161. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13162. friend void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  13163. static void initialiseDefaultFontNames() throw();
  13164. };
  13165. #endif // __JUCE_FONT_JUCEHEADER__
  13166. /********* End of inlined file: juce_Font.h *********/
  13167. /********* Start of inlined file: juce_Rectangle.h *********/
  13168. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13169. #define __JUCE_RECTANGLE_JUCEHEADER__
  13170. /**
  13171. A rectangle, specified using integer co-ordinates.
  13172. @see RectangleList, Path, Line, Point
  13173. */
  13174. class JUCE_API Rectangle
  13175. {
  13176. public:
  13177. /** Creates a rectangle of zero size.
  13178. The default co-ordinates will be (0, 0, 0, 0).
  13179. */
  13180. Rectangle() throw();
  13181. /** Creates a copy of another rectangle. */
  13182. Rectangle (const Rectangle& other) throw();
  13183. /** Creates a rectangle with a given position and size. */
  13184. Rectangle (const int x, const int y,
  13185. const int width, const int height) throw();
  13186. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13187. Rectangle (const int width, const int height) throw();
  13188. /** Destructor. */
  13189. ~Rectangle() throw();
  13190. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13191. inline int getX() const throw() { return x; }
  13192. /** Returns the y co-ordinate of the rectangle's top edge. */
  13193. inline int getY() const throw() { return y; }
  13194. /** Returns the width of the rectangle. */
  13195. inline int getWidth() const throw() { return w; }
  13196. /** Returns the height of the rectangle. */
  13197. inline int getHeight() const throw() { return h; }
  13198. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13199. inline int getRight() const throw() { return x + w; }
  13200. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13201. inline int getBottom() const throw() { return y + h; }
  13202. /** Returns the x co-ordinate of the rectangle's centre. */
  13203. inline int getCentreX() const throw() { return x + (w >> 1); }
  13204. /** Returns the y co-ordinate of the rectangle's centre. */
  13205. inline int getCentreY() const throw() { return y + (h >> 1); }
  13206. /** Returns true if the rectangle's width and height are both zero or less */
  13207. bool isEmpty() const throw();
  13208. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13209. void setPosition (const int x, const int y) throw();
  13210. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13211. void setSize (const int w, const int h) throw();
  13212. /** Changes all the rectangle's co-ordinates. */
  13213. void setBounds (const int newX, const int newY,
  13214. const int newWidth, const int newHeight) throw();
  13215. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13216. void translate (const int deltaX,
  13217. const int deltaY) throw();
  13218. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13219. const Rectangle translated (const int deltaX,
  13220. const int deltaY) const throw();
  13221. /** Expands the rectangle by a given amount.
  13222. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13223. @see expanded, reduce, reduced
  13224. */
  13225. void expand (const int deltaX,
  13226. const int deltaY) throw();
  13227. /** Returns a rectangle that is larger than this one by a given amount.
  13228. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13229. @see expand, reduce, reduced
  13230. */
  13231. const Rectangle expanded (const int deltaX,
  13232. const int deltaY) const throw();
  13233. /** Shrinks the rectangle by a given amount.
  13234. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13235. @see reduced, expand, expanded
  13236. */
  13237. void reduce (const int deltaX,
  13238. const int deltaY) throw();
  13239. /** Returns a rectangle that is smaller than this one by a given amount.
  13240. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13241. @see reduce, expand, expanded
  13242. */
  13243. const Rectangle reduced (const int deltaX,
  13244. const int deltaY) const throw();
  13245. /** Returns true if the two rectangles are identical. */
  13246. bool operator== (const Rectangle& other) const throw();
  13247. /** Returns true if the two rectangles are not identical. */
  13248. bool operator!= (const Rectangle& other) const throw();
  13249. /** Returns true if this co-ordinate is inside the rectangle. */
  13250. bool contains (const int x, const int y) const throw();
  13251. /** Returns true if this other rectangle is completely inside this one. */
  13252. bool contains (const Rectangle& other) const throw();
  13253. /** Returns true if any part of another rectangle overlaps this one. */
  13254. bool intersects (const Rectangle& other) const throw();
  13255. /** Returns the region that is the overlap between this and another rectangle.
  13256. If the two rectangles don't overlap, the rectangle returned will be empty.
  13257. */
  13258. const Rectangle getIntersection (const Rectangle& other) const throw();
  13259. /** Clips a rectangle so that it lies only within this one.
  13260. This is a non-static version of intersectRectangles().
  13261. Returns false if the two regions didn't overlap.
  13262. */
  13263. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13264. /** Returns the smallest rectangle that contains both this one and the one
  13265. passed-in.
  13266. */
  13267. const Rectangle getUnion (const Rectangle& other) const throw();
  13268. /** If this rectangle merged with another one results in a simple rectangle, this
  13269. will set this rectangle to the result, and return true.
  13270. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13271. or if they form a complex region.
  13272. */
  13273. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13274. /** If after removing another rectangle from this one the result is a simple rectangle,
  13275. this will set this object's bounds to be the result, and return true.
  13276. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13277. or if removing the other one would form a complex region.
  13278. */
  13279. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13280. /** Static utility to intersect two sets of rectangular co-ordinates.
  13281. Returns false if the two regions didn't overlap.
  13282. @see intersectRectangle
  13283. */
  13284. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13285. int x2, int y2, int w2, int h2) throw();
  13286. /** Creates a string describing this rectangle.
  13287. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13288. Coupled with the fromString() method, this is very handy for things like
  13289. storing rectangles (particularly component positions) in XML attributes.
  13290. @see fromString
  13291. */
  13292. const String toString() const throw();
  13293. /** Parses a string containing a rectangle's details.
  13294. The string should contain 4 integer tokens, in the form "x y width height". They
  13295. can be comma or whitespace separated.
  13296. This method is intended to go with the toString() method, to form an easy way
  13297. of saving/loading rectangles as strings.
  13298. @see toString
  13299. */
  13300. static const Rectangle fromString (const String& stringVersion);
  13301. juce_UseDebuggingNewOperator
  13302. private:
  13303. friend class RectangleList;
  13304. int x, y, w, h;
  13305. };
  13306. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13307. /********* End of inlined file: juce_Rectangle.h *********/
  13308. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13309. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13310. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13311. /**
  13312. Describes a type of stroke used to render a solid outline along a path.
  13313. A PathStrokeType object can be used directly to create the shape of an outline
  13314. around a path, and is used by Graphics::strokePath to specify the type of
  13315. stroke to draw.
  13316. @see Path, Graphics::strokePath
  13317. */
  13318. class JUCE_API PathStrokeType
  13319. {
  13320. public:
  13321. /** The type of shape to use for the corners between two adjacent line segments. */
  13322. enum JointStyle
  13323. {
  13324. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13325. Note that for angles that curve back on themselves, drawing a
  13326. mitre could require extending the point too far away from the
  13327. path, so a mitre limit is imposed and any corners that exceed it
  13328. are drawn as bevelled instead. */
  13329. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13330. beveled /**< Indicates that corners should be drawn with a line flattening their
  13331. outside edge. */
  13332. };
  13333. /** The type shape to use for the ends of lines. */
  13334. enum EndCapStyle
  13335. {
  13336. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13337. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13338. the thickness of the stroke. */
  13339. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13340. };
  13341. /** Creates a stroke type.
  13342. @param strokeThickness the width of the line to use
  13343. @param jointStyle the type of joints to use for corners
  13344. @param endStyle the type of end-caps to use for the ends of open paths.
  13345. */
  13346. PathStrokeType (const float strokeThickness,
  13347. const JointStyle jointStyle = mitered,
  13348. const EndCapStyle endStyle = butt) throw();
  13349. /** Createes a copy of another stroke type. */
  13350. PathStrokeType (const PathStrokeType& other) throw();
  13351. /** Copies another stroke onto this one. */
  13352. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13353. /** Destructor. */
  13354. ~PathStrokeType() throw();
  13355. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13356. @param destPath the resultant stroked outline shape will be copied into this path.
  13357. Note that it's ok for the source and destination Paths to be
  13358. the same object, so you can easily turn a path into a stroked version
  13359. of itself.
  13360. @param sourcePath the path to use as the source
  13361. @param transform an optional transform to apply to the points from the source path
  13362. as they are being used
  13363. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13364. a higher resolution, which improved the quality if you'll later want
  13365. to enlarge the stroked path
  13366. @see createDashedStroke
  13367. */
  13368. void createStrokedPath (Path& destPath,
  13369. const Path& sourcePath,
  13370. const AffineTransform& transform = AffineTransform::identity,
  13371. const float extraAccuracy = 1.0f) const throw();
  13372. /** Applies this stroke type to a path, creating a dashed line.
  13373. This is similar to createStrokedPath, but uses the array passed in to
  13374. break the stroke up into a series of dashes.
  13375. @param destPath the resultant stroked outline shape will be copied into this path.
  13376. Note that it's ok for the source and destination Paths to be
  13377. the same object, so you can easily turn a path into a stroked version
  13378. of itself.
  13379. @param sourcePath the path to use as the source
  13380. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13381. a line of length 2, then skip a length of 3, then add a line of length 4,
  13382. skip 5, and keep repeating this pattern.
  13383. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13384. an even number, otherwise the pattern will get out of step as it
  13385. repeats.
  13386. @param transform an optional transform to apply to the points from the source path
  13387. as they are being used
  13388. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13389. a higher resolution, which improved the quality if you'll later want
  13390. to enlarge the stroked path
  13391. */
  13392. void createDashedStroke (Path& destPath,
  13393. const Path& sourcePath,
  13394. const float* dashLengths,
  13395. int numDashLengths,
  13396. const AffineTransform& transform = AffineTransform::identity,
  13397. const float extraAccuracy = 1.0f) const throw();
  13398. /** Returns the stroke thickness. */
  13399. float getStrokeThickness() const throw() { return thickness; }
  13400. /** Returns the joint style. */
  13401. JointStyle getJointStyle() const throw() { return jointStyle; }
  13402. /** Returns the end-cap style. */
  13403. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13404. juce_UseDebuggingNewOperator
  13405. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13406. bool operator== (const PathStrokeType& other) const throw();
  13407. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13408. bool operator!= (const PathStrokeType& other) const throw();
  13409. private:
  13410. float thickness;
  13411. JointStyle jointStyle;
  13412. EndCapStyle endStyle;
  13413. };
  13414. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13415. /********* End of inlined file: juce_PathStrokeType.h *********/
  13416. /********* Start of inlined file: juce_Line.h *********/
  13417. #ifndef __JUCE_LINE_JUCEHEADER__
  13418. #define __JUCE_LINE_JUCEHEADER__
  13419. /**
  13420. Represents a line, using 32-bit float co-ordinates.
  13421. This class contains a bunch of useful methods for various geometric
  13422. tasks.
  13423. @see Point, Rectangle, Path, Graphics::drawLine
  13424. */
  13425. class JUCE_API Line
  13426. {
  13427. public:
  13428. /** Creates a line, using (0, 0) as its start and end points. */
  13429. Line() throw();
  13430. /** Creates a copy of another line. */
  13431. Line (const Line& other) throw();
  13432. /** Creates a line based on the co-ordinates of its start and end points. */
  13433. Line (const float startX,
  13434. const float startY,
  13435. const float endX,
  13436. const float endY) throw();
  13437. /** Creates a line from its start and end points. */
  13438. Line (const Point& start,
  13439. const Point& end) throw();
  13440. /** Copies a line from another one. */
  13441. const Line& operator= (const Line& other) throw();
  13442. /** Destructor. */
  13443. ~Line() throw();
  13444. /** Returns the x co-ordinate of the line's start point. */
  13445. inline float getStartX() const throw() { return startX; }
  13446. /** Returns the y co-ordinate of the line's start point. */
  13447. inline float getStartY() const throw() { return startY; }
  13448. /** Returns the x co-ordinate of the line's end point. */
  13449. inline float getEndX() const throw() { return endX; }
  13450. /** Returns the y co-ordinate of the line's end point. */
  13451. inline float getEndY() const throw() { return endY; }
  13452. /** Returns the line's start point. */
  13453. const Point getStart() const throw();
  13454. /** Returns the line's end point. */
  13455. const Point getEnd() const throw();
  13456. /** Changes this line's start point */
  13457. void setStart (const float newStartX,
  13458. const float newStartY) throw();
  13459. /** Changes this line's end point */
  13460. void setEnd (const float newEndX,
  13461. const float newEndY) throw();
  13462. /** Changes this line's start point */
  13463. void setStart (const Point& newStart) throw();
  13464. /** Changes this line's end point */
  13465. void setEnd (const Point& newEnd) throw();
  13466. /** Applies an affine transform to the line's start and end points. */
  13467. void applyTransform (const AffineTransform& transform) throw();
  13468. /** Returns the length of the line. */
  13469. float getLength() const throw();
  13470. /** Returns true if the line's start and end x co-ordinates are the same. */
  13471. bool isVertical() const throw();
  13472. /** Returns true if the line's start and end y co-ordinates are the same. */
  13473. bool isHorizontal() const throw();
  13474. /** Returns the line's angle.
  13475. This value is the number of radians clockwise from the 3 o'clock direction,
  13476. where the line's start point is considered to be at the centre.
  13477. */
  13478. float getAngle() const throw();
  13479. /** Compares two lines. */
  13480. bool operator== (const Line& other) const throw();
  13481. /** Compares two lines. */
  13482. bool operator!= (const Line& other) const throw();
  13483. /** Finds the intersection between two lines.
  13484. @param line the other line
  13485. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13486. where they would meet if they were infinitely long)
  13487. the intersection (if the lines intersect). If the lines
  13488. are parallel, this will just be set to the position
  13489. of one of the line's endpoints.
  13490. @param intersectionY the y co-ordinate of the point where the lines meet
  13491. @returns true if the line segments intersect; false if they dont. Even if they
  13492. don't intersect, the intersection co-ordinates returned will still
  13493. be valid
  13494. */
  13495. bool intersects (const Line& line,
  13496. float& intersectionX,
  13497. float& intersectionY) const throw();
  13498. /** Returns the location of the point which is a given distance along this line.
  13499. @param distanceFromStart the distance to move along the line from its
  13500. start point. This value can be negative or longer
  13501. than the line itself
  13502. @see getPointAlongLineProportionally
  13503. */
  13504. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13505. /** Returns a point which is a certain distance along and to the side of this line.
  13506. This effectively moves a given distance along the line, then another distance
  13507. perpendicularly to this, and returns the resulting position.
  13508. @param distanceFromStart the distance to move along the line from its
  13509. start point. This value can be negative or longer
  13510. than the line itself
  13511. @param perpendicularDistance how far to move sideways from the line. If you're
  13512. looking along the line from its start towards its
  13513. end, then a positive value here will move to the
  13514. right, negative value move to the left.
  13515. */
  13516. const Point getPointAlongLine (const float distanceFromStart,
  13517. const float perpendicularDistance) const throw();
  13518. /** Returns the location of the point which is a given distance along this line
  13519. proportional to the line's length.
  13520. @param proportionOfLength the distance to move along the line from its
  13521. start point, in multiples of the line's length.
  13522. So a value of 0.0 will return the line's start point
  13523. and a value of 1.0 will return its end point. (This value
  13524. can be negative or greater than 1.0).
  13525. @see getPointAlongLine
  13526. */
  13527. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13528. /** Returns the smallest distance between this line segment and a given point.
  13529. So if the point is close to the line, this will return the perpendicular
  13530. distance from the line; if the point is a long way beyond one of the line's
  13531. end-point's, it'll return the straight-line distance to the nearest end-point.
  13532. @param x x position of the point to test
  13533. @param y y position of the point to test
  13534. @returns the point's distance from the line
  13535. @see getPositionAlongLineOfNearestPoint
  13536. */
  13537. float getDistanceFromLine (const float x,
  13538. const float y) const throw();
  13539. /** Finds the point on this line which is nearest to a given point, and
  13540. returns its position as a proportional position along the line.
  13541. @param x x position of the point to test
  13542. @param y y position of the point to test
  13543. @returns a value 0 to 1.0 which is the distance along this line from the
  13544. line's start to the point which is nearest to the point passed-in. To
  13545. turn this number into a position, use getPointAlongLineProportionally().
  13546. @see getDistanceFromLine, getPointAlongLineProportionally
  13547. */
  13548. float findNearestPointTo (const float x,
  13549. const float y) const throw();
  13550. /** Returns true if the given point lies above this line.
  13551. The return value is true if the point's y coordinate is less than the y
  13552. coordinate of this line at the given x (assuming the line extends infinitely
  13553. in both directions).
  13554. */
  13555. bool isPointAbove (const float x, const float y) const throw();
  13556. /** Returns a shortened copy of this line.
  13557. This will chop off part of the start of this line by a certain amount, (leaving the
  13558. end-point the same), and return the new line.
  13559. */
  13560. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13561. /** Returns a shortened copy of this line.
  13562. This will chop off part of the end of this line by a certain amount, (leaving the
  13563. start-point the same), and return the new line.
  13564. */
  13565. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13566. /** Cuts off parts of this line to keep the parts that are either inside or
  13567. outside a path.
  13568. Note that this isn't smart enough to cope with situations where the
  13569. line would need to be cut into multiple pieces to correctly clip against
  13570. a re-entrant shape.
  13571. @param path the path to clip against
  13572. @param keepSectionOutsidePath if true, it's the section outside the path
  13573. that will be kept; if false its the section inside
  13574. the path
  13575. @returns true if the line was changed.
  13576. */
  13577. bool clipToPath (const Path& path,
  13578. const bool keepSectionOutsidePath) throw();
  13579. juce_UseDebuggingNewOperator
  13580. private:
  13581. float startX, startY, endX, endY;
  13582. };
  13583. #endif // __JUCE_LINE_JUCEHEADER__
  13584. /********* End of inlined file: juce_Line.h *********/
  13585. /********* Start of inlined file: juce_Colours.h *********/
  13586. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13587. #define __JUCE_COLOURS_JUCEHEADER__
  13588. /********* Start of inlined file: juce_Colour.h *********/
  13589. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13590. #define __JUCE_COLOUR_JUCEHEADER__
  13591. /********* Start of inlined file: juce_PixelFormats.h *********/
  13592. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13593. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13594. #if JUCE_MSVC
  13595. #pragma pack (push, 1)
  13596. #define PACKED
  13597. #elif JUCE_GCC
  13598. #define PACKED __attribute__((packed))
  13599. #else
  13600. #define PACKED
  13601. #endif
  13602. /**
  13603. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13604. operations with it.
  13605. This is used internally by the imaging classes.
  13606. @see PixelRGB
  13607. */
  13608. class JUCE_API PixelARGB
  13609. {
  13610. public:
  13611. /** Creates a pixel without defining its colour. */
  13612. PixelARGB() throw() {}
  13613. ~PixelARGB() throw() {}
  13614. /** Creates a pixel from a 32-bit argb value.
  13615. */
  13616. PixelARGB (const uint32 argb_) throw()
  13617. : argb (argb_)
  13618. {
  13619. }
  13620. forcedinline uint32 getARGB() const throw() { return argb; }
  13621. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13622. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13623. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13624. forcedinline uint8 getRed() const throw() { return components.r; }
  13625. forcedinline uint8 getGreen() const throw() { return components.g; }
  13626. forcedinline uint8 getBlue() const throw() { return components.b; }
  13627. /** Blends another pixel onto this one.
  13628. This takes into account the opacity of the pixel being overlaid, and blends
  13629. it accordingly.
  13630. */
  13631. template <class Pixel>
  13632. forcedinline void blend (const Pixel& src) throw()
  13633. {
  13634. uint32 sargb = src.getARGB();
  13635. const uint32 alpha = 0x100 - (sargb >> 24);
  13636. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13637. sargb += 0xff00ff00 & (getAG() * alpha);
  13638. argb = sargb;
  13639. }
  13640. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13641. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13642. being used, so this can blend semi-transparently from a PixelRGB argument.
  13643. */
  13644. template <class Pixel>
  13645. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13646. {
  13647. ++extraAlpha;
  13648. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13649. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13650. const uint32 alpha = 0x100 - (sargb >> 24);
  13651. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13652. sargb += 0xff00ff00 & (getAG() * alpha);
  13653. argb = sargb;
  13654. }
  13655. /** Blends another pixel with this one, creating a colour that is somewhere
  13656. between the two, as specified by the amount.
  13657. */
  13658. template <class Pixel>
  13659. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13660. {
  13661. uint32 drb = getRB();
  13662. drb += (((src.getRB() - drb) * amount) >> 8);
  13663. drb &= 0x00ff00ff;
  13664. uint32 dag = getAG();
  13665. dag += (((src.getAG() - dag) * amount) >> 8);
  13666. dag &= 0x00ff00ff;
  13667. dag <<= 8;
  13668. dag |= drb;
  13669. argb = dag;
  13670. }
  13671. /** Copies another pixel colour over this one.
  13672. This doesn't blend it - this colour is simply replaced by the other one.
  13673. */
  13674. template <class Pixel>
  13675. forcedinline void set (const Pixel& src) throw()
  13676. {
  13677. argb = src.getARGB();
  13678. }
  13679. /** Replaces the colour's alpha value with another one. */
  13680. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13681. {
  13682. components.a = newAlpha;
  13683. }
  13684. /** Multiplies the colour's alpha value with another one. */
  13685. forcedinline void multiplyAlpha (int multiplier) throw()
  13686. {
  13687. ++multiplier;
  13688. argb = ((multiplier * getAG()) & 0xff00ff00)
  13689. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13690. }
  13691. forcedinline void multiplyAlpha (const float multiplier) throw()
  13692. {
  13693. multiplyAlpha ((int) (multiplier * 256.0f));
  13694. }
  13695. /** Sets the pixel's colour from individual components. */
  13696. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13697. {
  13698. components.b = b;
  13699. components.g = g;
  13700. components.r = r;
  13701. components.a = a;
  13702. }
  13703. /** Premultiplies the pixel's RGB values by its alpha. */
  13704. forcedinline void premultiply() throw()
  13705. {
  13706. const uint32 alpha = components.a;
  13707. if (alpha < 0xff)
  13708. {
  13709. if (alpha == 0)
  13710. {
  13711. components.b = 0;
  13712. components.g = 0;
  13713. components.r = 0;
  13714. }
  13715. else
  13716. {
  13717. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13718. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13719. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13720. }
  13721. }
  13722. }
  13723. /** Unpremultiplies the pixel's RGB values. */
  13724. forcedinline void unpremultiply() throw()
  13725. {
  13726. const uint32 alpha = components.a;
  13727. if (alpha < 0xff)
  13728. {
  13729. if (alpha == 0)
  13730. {
  13731. components.b = 0;
  13732. components.g = 0;
  13733. components.r = 0;
  13734. }
  13735. else
  13736. {
  13737. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13738. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13739. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13740. }
  13741. }
  13742. }
  13743. forcedinline void desaturate() throw()
  13744. {
  13745. if (components.a < 0xff && components.a > 0)
  13746. {
  13747. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13748. components.r = components.g = components.b
  13749. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13750. }
  13751. else
  13752. {
  13753. components.r = components.g = components.b
  13754. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13755. }
  13756. }
  13757. private:
  13758. union
  13759. {
  13760. uint32 argb;
  13761. struct
  13762. {
  13763. #if JUCE_BIG_ENDIAN
  13764. uint8 a : 8, r : 8, g : 8, b : 8;
  13765. #else
  13766. uint8 b, g, r, a;
  13767. #endif
  13768. } PACKED components;
  13769. };
  13770. } PACKED;
  13771. /**
  13772. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13773. This is used internally by the imaging classes.
  13774. @see PixelARGB
  13775. */
  13776. class JUCE_API PixelRGB
  13777. {
  13778. public:
  13779. /** Creates a pixel without defining its colour. */
  13780. PixelRGB() throw() {}
  13781. ~PixelRGB() throw() {}
  13782. /** Creates a pixel from a 32-bit argb value.
  13783. (The argb format is that used by PixelARGB)
  13784. */
  13785. PixelRGB (const uint32 argb) throw()
  13786. {
  13787. r = (uint8) (argb >> 16);
  13788. g = (uint8) (argb >> 8);
  13789. b = (uint8) (argb);
  13790. }
  13791. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13792. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13793. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13794. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13795. forcedinline uint8 getRed() const throw() { return r; }
  13796. forcedinline uint8 getGreen() const throw() { return g; }
  13797. forcedinline uint8 getBlue() const throw() { return b; }
  13798. /** Blends another pixel onto this one.
  13799. This takes into account the opacity of the pixel being overlaid, and blends
  13800. it accordingly.
  13801. */
  13802. forcedinline void blend (const PixelARGB& src) throw()
  13803. {
  13804. uint32 sargb = src.getARGB();
  13805. const uint32 alpha = 0x100 - (sargb >> 24);
  13806. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13807. sargb += 0x0000ff00 & (g * alpha);
  13808. r = (uint8) (sargb >> 16);
  13809. g = (uint8) (sargb >> 8);
  13810. b = (uint8) sargb;
  13811. }
  13812. forcedinline void blend (const PixelRGB& src) throw()
  13813. {
  13814. set (src);
  13815. }
  13816. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13817. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13818. being used, so this can blend semi-transparently from a PixelRGB argument.
  13819. */
  13820. template <class Pixel>
  13821. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13822. {
  13823. ++extraAlpha;
  13824. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13825. const uint32 sag = extraAlpha * src.getAG();
  13826. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13827. const uint32 alpha = 0x100 - (sargb >> 24);
  13828. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13829. sargb += 0x0000ff00 & (g * alpha);
  13830. b = (uint8) sargb;
  13831. g = (uint8) (sargb >> 8);
  13832. r = (uint8) (sargb >> 16);
  13833. }
  13834. /** Blends another pixel with this one, creating a colour that is somewhere
  13835. between the two, as specified by the amount.
  13836. */
  13837. template <class Pixel>
  13838. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13839. {
  13840. uint32 drb = getRB();
  13841. drb += (((src.getRB() - drb) * amount) >> 8);
  13842. uint32 dag = getAG();
  13843. dag += (((src.getAG() - dag) * amount) >> 8);
  13844. b = (uint8) drb;
  13845. g = (uint8) dag;
  13846. r = (uint8) (drb >> 16);
  13847. }
  13848. /** Copies another pixel colour over this one.
  13849. This doesn't blend it - this colour is simply replaced by the other one.
  13850. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13851. is thrown away.
  13852. */
  13853. template <class Pixel>
  13854. forcedinline void set (const Pixel& src) throw()
  13855. {
  13856. b = src.getBlue();
  13857. g = src.getGreen();
  13858. r = src.getRed();
  13859. }
  13860. /** This method is included for compatibility with the PixelARGB class. */
  13861. forcedinline void setAlpha (const uint8) throw() {}
  13862. /** Multiplies the colour's alpha value with another one. */
  13863. forcedinline void multiplyAlpha (int) throw() {}
  13864. /** Sets the pixel's colour from individual components. */
  13865. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  13866. {
  13867. r = r_;
  13868. g = g_;
  13869. b = b_;
  13870. }
  13871. /** Premultiplies the pixel's RGB values by its alpha. */
  13872. forcedinline void premultiply() throw() {}
  13873. /** Unpremultiplies the pixel's RGB values. */
  13874. forcedinline void unpremultiply() throw() {}
  13875. forcedinline void desaturate() throw()
  13876. {
  13877. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  13878. }
  13879. private:
  13880. #if JUCE_MAC
  13881. uint8 r, g, b;
  13882. #else
  13883. uint8 b, g, r;
  13884. #endif
  13885. } PACKED;
  13886. #if JUCE_MSVC
  13887. #pragma pack (pop)
  13888. #endif
  13889. #undef PACKED
  13890. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  13891. /********* End of inlined file: juce_PixelFormats.h *********/
  13892. /**
  13893. Represents a colour, also including a transparency value.
  13894. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  13895. */
  13896. class JUCE_API Colour
  13897. {
  13898. public:
  13899. /** Creates a transparent black colour. */
  13900. Colour() throw();
  13901. /** Creates a copy of another Colour object. */
  13902. Colour (const Colour& other) throw();
  13903. /** Creates a colour from a 32-bit ARGB value.
  13904. The format of this number is:
  13905. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13906. All components in the range 0x00 to 0xff.
  13907. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13908. @see getPixelARGB
  13909. */
  13910. explicit Colour (const uint32 argb) throw();
  13911. /** Creates an opaque colour using 8-bit red, green and blue values */
  13912. Colour (const uint8 red,
  13913. const uint8 green,
  13914. const uint8 blue) throw();
  13915. /** Creates an opaque colour using 8-bit red, green and blue values */
  13916. static const Colour fromRGB (const uint8 red,
  13917. const uint8 green,
  13918. const uint8 blue) throw();
  13919. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13920. Colour (const uint8 red,
  13921. const uint8 green,
  13922. const uint8 blue,
  13923. const uint8 alpha) throw();
  13924. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13925. static const Colour fromRGBA (const uint8 red,
  13926. const uint8 green,
  13927. const uint8 blue,
  13928. const uint8 alpha) throw();
  13929. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  13930. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  13931. Values outside the valid range will be clipped.
  13932. */
  13933. Colour (const uint8 red,
  13934. const uint8 green,
  13935. const uint8 blue,
  13936. const float alpha) throw();
  13937. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  13938. static const Colour fromRGBAFloat (const uint8 red,
  13939. const uint8 green,
  13940. const uint8 blue,
  13941. const float alpha) throw();
  13942. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13943. The floating point values must be between 0.0 and 1.0.
  13944. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13945. Values outside the valid range will be clipped.
  13946. */
  13947. Colour (const float hue,
  13948. const float saturation,
  13949. const float brightness,
  13950. const uint8 alpha) throw();
  13951. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  13952. All values must be between 0.0 and 1.0.
  13953. Numbers outside the valid range will be clipped.
  13954. */
  13955. Colour (const float hue,
  13956. const float saturation,
  13957. const float brightness,
  13958. const float alpha) throw();
  13959. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  13960. The floating point values must be between 0.0 and 1.0.
  13961. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13962. Values outside the valid range will be clipped.
  13963. */
  13964. static const Colour fromHSV (const float hue,
  13965. const float saturation,
  13966. const float brightness,
  13967. const float alpha) throw();
  13968. /** Destructor. */
  13969. ~Colour() throw();
  13970. /** Copies another Colour object. */
  13971. const Colour& operator= (const Colour& other) throw();
  13972. /** Compares two colours. */
  13973. bool operator== (const Colour& other) const throw();
  13974. /** Compares two colours. */
  13975. bool operator!= (const Colour& other) const throw();
  13976. /** Returns the red component of this colour.
  13977. @returns a value between 0x00 and 0xff.
  13978. */
  13979. uint8 getRed() const throw() { return argb.getRed(); }
  13980. /** Returns the green component of this colour.
  13981. @returns a value between 0x00 and 0xff.
  13982. */
  13983. uint8 getGreen() const throw() { return argb.getGreen(); }
  13984. /** Returns the blue component of this colour.
  13985. @returns a value between 0x00 and 0xff.
  13986. */
  13987. uint8 getBlue() const throw() { return argb.getBlue(); }
  13988. /** Returns the red component of this colour as a floating point value.
  13989. @returns a value between 0.0 and 1.0
  13990. */
  13991. float getFloatRed() const throw();
  13992. /** Returns the green component of this colour as a floating point value.
  13993. @returns a value between 0.0 and 1.0
  13994. */
  13995. float getFloatGreen() const throw();
  13996. /** Returns the blue component of this colour as a floating point value.
  13997. @returns a value between 0.0 and 1.0
  13998. */
  13999. float getFloatBlue() const throw();
  14000. /** Returns a premultiplied ARGB pixel object that represents this colour.
  14001. */
  14002. const PixelARGB getPixelARGB() const throw();
  14003. /** Returns a 32-bit integer that represents this colour.
  14004. The format of this number is:
  14005. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14006. */
  14007. uint32 getARGB() const throw();
  14008. /** Returns the colour's alpha (opacity).
  14009. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  14010. */
  14011. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  14012. /** Returns the colour's alpha (opacity) as a floating point value.
  14013. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  14014. */
  14015. float getFloatAlpha() const throw();
  14016. /** Returns true if this colour is completely opaque.
  14017. Equivalent to (getAlpha() == 0xff).
  14018. */
  14019. bool isOpaque() const throw();
  14020. /** Returns true if this colour is completely transparent.
  14021. Equivalent to (getAlpha() == 0x00).
  14022. */
  14023. bool isTransparent() const throw();
  14024. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14025. const Colour withAlpha (const uint8 newAlpha) const throw();
  14026. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14027. const Colour withAlpha (const float newAlpha) const throw();
  14028. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14029. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14030. */
  14031. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14032. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14033. If the foreground colour is semi-transparent, it is blended onto this colour
  14034. accordingly.
  14035. */
  14036. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14037. /** Returns the colour's hue component.
  14038. The value returned is in the range 0.0 to 1.0
  14039. */
  14040. float getHue() const throw();
  14041. /** Returns the colour's saturation component.
  14042. The value returned is in the range 0.0 to 1.0
  14043. */
  14044. float getSaturation() const throw();
  14045. /** Returns the colour's brightness component.
  14046. The value returned is in the range 0.0 to 1.0
  14047. */
  14048. float getBrightness() const throw();
  14049. /** Returns the colour's hue, saturation and brightness components all at once.
  14050. The values returned are in the range 0.0 to 1.0
  14051. */
  14052. void getHSB (float& hue,
  14053. float& saturation,
  14054. float& brightness) const throw();
  14055. /** Returns a copy of this colour with a different hue. */
  14056. const Colour withHue (const float newHue) const throw();
  14057. /** Returns a copy of this colour with a different saturation. */
  14058. const Colour withSaturation (const float newSaturation) const throw();
  14059. /** Returns a copy of this colour with a different brightness.
  14060. @see brighter, darker, withMultipliedBrightness
  14061. */
  14062. const Colour withBrightness (const float newBrightness) const throw();
  14063. /** Returns a copy of this colour with it hue rotated.
  14064. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14065. @see brighter, darker, withMultipliedBrightness
  14066. */
  14067. const Colour withRotatedHue (const float amountToRotate) const throw();
  14068. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14069. The new colour's saturation is (this->getSaturation() * multiplier)
  14070. (the result is clipped to legal limits).
  14071. */
  14072. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14073. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14074. The new colour's saturation is (this->getBrightness() * multiplier)
  14075. (the result is clipped to legal limits).
  14076. */
  14077. const Colour withMultipliedBrightness (const float amount) const throw();
  14078. /** Returns a brighter version of this colour.
  14079. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14080. unchanged, and higher values make it brighter
  14081. @see withMultipliedBrightness
  14082. */
  14083. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14084. /** Returns a darker version of this colour.
  14085. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14086. unchanged, and higher values make it darker
  14087. @see withMultipliedBrightness
  14088. */
  14089. const Colour darker (float amountDarker = 0.4f) const throw();
  14090. /** Returns a colour that will be clearly visible against this colour.
  14091. The amount parameter indicates how contrasting the new colour should
  14092. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14093. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14094. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14095. */
  14096. const Colour contrasting (const float amount = 1.0f) const throw();
  14097. /** Returns a colour that contrasts against two colours.
  14098. Looks for a colour that contrasts with both of the colours passed-in.
  14099. Handy for things like choosing a highlight colour in text editors, etc.
  14100. */
  14101. static const Colour contrasting (const Colour& colour1,
  14102. const Colour& colour2) throw();
  14103. /** Returns an opaque shade of grey.
  14104. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14105. */
  14106. static const Colour greyLevel (const float brightness) throw();
  14107. /** Returns a stringified version of this colour.
  14108. The string can be turned back into a colour using the fromString() method.
  14109. */
  14110. const String toString() const throw();
  14111. /** Reads the colour from a string that was created with toString().
  14112. */
  14113. static const Colour fromString (const String& encodedColourString);
  14114. juce_UseDebuggingNewOperator
  14115. private:
  14116. PixelARGB argb;
  14117. };
  14118. #endif // __JUCE_COLOUR_JUCEHEADER__
  14119. /********* End of inlined file: juce_Colour.h *********/
  14120. /**
  14121. Contains a set of predefined named colours (mostly standard HTML colours)
  14122. @see Colour, Colours::greyLevel
  14123. */
  14124. class Colours
  14125. {
  14126. public:
  14127. static JUCE_API const Colour
  14128. transparentBlack, /**< ARGB = 0x00000000 */
  14129. transparentWhite, /**< ARGB = 0x00ffffff */
  14130. black, /**< ARGB = 0xff000000 */
  14131. white, /**< ARGB = 0xffffffff */
  14132. blue, /**< ARGB = 0xff0000ff */
  14133. grey, /**< ARGB = 0xff808080 */
  14134. green, /**< ARGB = 0xff008000 */
  14135. red, /**< ARGB = 0xffff0000 */
  14136. yellow, /**< ARGB = 0xffffff00 */
  14137. aliceblue, antiquewhite, aqua, aquamarine,
  14138. azure, beige, bisque, blanchedalmond,
  14139. blueviolet, brown, burlywood, cadetblue,
  14140. chartreuse, chocolate, coral, cornflowerblue,
  14141. cornsilk, crimson, cyan, darkblue,
  14142. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14143. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14144. darkorchid, darkred, darksalmon, darkseagreen,
  14145. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14146. deeppink, deepskyblue, dimgrey, dodgerblue,
  14147. firebrick, floralwhite, forestgreen, fuchsia,
  14148. gainsboro, gold, goldenrod, greenyellow,
  14149. honeydew, hotpink, indianred, indigo,
  14150. ivory, khaki, lavender, lavenderblush,
  14151. lemonchiffon, lightblue, lightcoral, lightcyan,
  14152. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14153. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14154. lightsteelblue, lightyellow, lime, limegreen,
  14155. linen, magenta, maroon, mediumaquamarine,
  14156. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14157. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14158. midnightblue, mintcream, mistyrose, navajowhite,
  14159. navy, oldlace, olive, olivedrab,
  14160. orange, orangered, orchid, palegoldenrod,
  14161. palegreen, paleturquoise, palevioletred, papayawhip,
  14162. peachpuff, peru, pink, plum,
  14163. powderblue, purple, rosybrown, royalblue,
  14164. saddlebrown, salmon, sandybrown, seagreen,
  14165. seashell, sienna, silver, skyblue,
  14166. slateblue, slategrey, snow, springgreen,
  14167. steelblue, tan, teal, thistle,
  14168. tomato, turquoise, violet, wheat,
  14169. whitesmoke, yellowgreen;
  14170. /** Attempts to look up a string in the list of known colour names, and return
  14171. the appropriate colour.
  14172. A non-case-sensitive search is made of the list of predefined colours, and
  14173. if a match is found, that colour is returned. If no match is found, the
  14174. colour passed in as the defaultColour parameter is returned.
  14175. */
  14176. static JUCE_API const Colour findColourForName (const String& colourName,
  14177. const Colour& defaultColour);
  14178. private:
  14179. // this isn't a class you should ever instantiate - it's just here for the
  14180. // static values in it.
  14181. Colours();
  14182. };
  14183. #endif // __JUCE_COLOURS_JUCEHEADER__
  14184. /********* End of inlined file: juce_Colours.h *********/
  14185. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14186. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14187. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14188. /********* Start of inlined file: juce_Brush.h *********/
  14189. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14190. #define __JUCE_BRUSH_JUCEHEADER__
  14191. class Path;
  14192. class AffineTransform;
  14193. class LowLevelGraphicsContext;
  14194. class Image;
  14195. class Graphics;
  14196. /**
  14197. A brush is used to fill areas with colours, patterns, or images.
  14198. The Graphics class has an idea of a current brush which it uses to render
  14199. shapes, rectangles, lines, text, etc.
  14200. This is the base class - there are subclasses for useful types of fill pattern,
  14201. and applications can define their own brushes too.
  14202. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14203. */
  14204. class JUCE_API Brush
  14205. {
  14206. protected:
  14207. /** Creates a Brush.
  14208. (Nothing much happens in the base class).
  14209. */
  14210. Brush() throw();
  14211. public:
  14212. /** Destructor. */
  14213. virtual ~Brush() throw();
  14214. /** Creates a copy of whatever class of Brush this is. */
  14215. virtual Brush* createCopy() const throw() = 0;
  14216. /** Does whatever is relevent to transform the geometry of this brush. */
  14217. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14218. /** Does whatever is relevent to change the opacity of this brush. */
  14219. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14220. /** Must return true if this brush won't draw any pixels. */
  14221. virtual bool isInvisible() const throw() = 0;
  14222. virtual void paintPath (LowLevelGraphicsContext& context,
  14223. const Path& path, const AffineTransform& transform) throw() = 0;
  14224. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14225. int x, int y, int w, int h) throw() = 0;
  14226. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14227. const Image& alphaChannelImage, int imageX, int imageY,
  14228. int x, int y, int w, int h) throw() = 0;
  14229. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14230. int x, float y1, float y2) throw();
  14231. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14232. int y, float x1, float x2) throw();
  14233. virtual void paintLine (LowLevelGraphicsContext& context,
  14234. float x1, float y1, float x2, float y2) throw();
  14235. private:
  14236. Brush (const Brush&);
  14237. const Brush& operator= (const Brush&);
  14238. };
  14239. #endif // __JUCE_BRUSH_JUCEHEADER__
  14240. /********* End of inlined file: juce_Brush.h *********/
  14241. /**
  14242. A Brush that fills its area with a solid (or semi-transparent) colour.
  14243. An application won't normally need to use this class directly, as drawing
  14244. with solid colours is taken care of automatically by the Graphics class
  14245. (it actually uses one of these brushes internally when you set the colour
  14246. with the Graphics::setColour() method).
  14247. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14248. */
  14249. class JUCE_API SolidColourBrush : public Brush
  14250. {
  14251. public:
  14252. /** Creates a SolidColourBrush to draw with the given colour.
  14253. The colour can be changed later with the setColour() method.
  14254. */
  14255. SolidColourBrush (const Colour& colour) throw();
  14256. /** Creates a SolidColourBrush set to black.
  14257. The colour can be changed later with the setColour() method.
  14258. */
  14259. SolidColourBrush() throw();
  14260. /** Destructor. */
  14261. ~SolidColourBrush() throw();
  14262. /** Returns the colour currently being used. */
  14263. const Colour& getColour() const throw() { return colour; }
  14264. /** Sets the colour to use for drawing. */
  14265. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14266. Brush* createCopy() const throw();
  14267. void applyTransform (const AffineTransform& transform) throw();
  14268. bool isInvisible() const throw();
  14269. void multiplyOpacity (const float multiple) throw();
  14270. void paintPath (LowLevelGraphicsContext& context,
  14271. const Path& path, const AffineTransform& transform) throw();
  14272. void paintRectangle (LowLevelGraphicsContext& context,
  14273. int x, int y, int w, int h) throw();
  14274. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14275. const Image& alphaChannelImage, int imageX, int imageY,
  14276. int x, int y, int w, int h) throw();
  14277. void paintVerticalLine (LowLevelGraphicsContext& context,
  14278. int x, float y1, float y2) throw();
  14279. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14280. int y, float x1, float x2) throw();
  14281. void paintLine (LowLevelGraphicsContext& context,
  14282. float x1, float y1, float x2, float y2) throw();
  14283. juce_UseDebuggingNewOperator
  14284. private:
  14285. Colour colour;
  14286. SolidColourBrush (const SolidColourBrush&);
  14287. const SolidColourBrush& operator= (const SolidColourBrush&);
  14288. };
  14289. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14290. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14291. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14292. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14293. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14294. /**
  14295. Defines the method used to postion some kind of rectangular object within
  14296. a rectangular viewport.
  14297. Although similar to Justification, this is more specific, and has some extra
  14298. options.
  14299. */
  14300. class JUCE_API RectanglePlacement
  14301. {
  14302. public:
  14303. /** Creates a RectanglePlacement object using a combination of flags. */
  14304. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14305. /** Creates a copy of another Justification object. */
  14306. RectanglePlacement (const RectanglePlacement& other) throw();
  14307. /** Copies another Justification object. */
  14308. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14309. /** Flag values that can be combined and used in the constructor. */
  14310. enum
  14311. {
  14312. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14313. xLeft = 1,
  14314. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14315. xRight = 2,
  14316. /** Indicates that the source should be placed in the centre between the left and right
  14317. sides of the available space. */
  14318. xMid = 4,
  14319. /** Indicates that the source's top edge should be aligned with the top edge of the
  14320. destination rectangle. */
  14321. yTop = 8,
  14322. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14323. destination rectangle. */
  14324. yBottom = 16,
  14325. /** Indicates that the source should be placed in the centre between the top and bottom
  14326. sides of the available space. */
  14327. yMid = 32,
  14328. /** If this flag is set, then the source rectangle will be resized to completely fill
  14329. the destination rectangle, and all other flags are ignored.
  14330. */
  14331. stretchToFit = 64,
  14332. /** If this flag is set, then the source rectangle will be resized so that it is the
  14333. minimum size to completely fill the destination rectangle. This means that some
  14334. of the source rectangle may fall outside the destination.
  14335. If this flag is not set, the source will be given the maximum size at which none
  14336. of it falls outside the destination rectangle.
  14337. */
  14338. fillDestination = 128,
  14339. /** Indicates that the source rectangle can be reduced in size if required, but should
  14340. never be made larger than its original size.
  14341. */
  14342. onlyReduceInSize = 256,
  14343. /** Indicates that the source rectangle can be enlarged if required, but should
  14344. never be made smaller than its original size.
  14345. */
  14346. onlyIncreaseInSize = 512,
  14347. /** Indicates that the source rectangle's size should be left unchanged.
  14348. */
  14349. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14350. /** A shorthand value that is equivalent to (xMid | yMid). */
  14351. centred = 4 + 32
  14352. };
  14353. /** Returns the raw flags that are set for this object. */
  14354. inline int getFlags() const throw() { return flags; }
  14355. /** Tests a set of flags for this object.
  14356. @returns true if any of the flags passed in are set on this object.
  14357. */
  14358. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14359. /** Adjusts the position and size of a rectangle to fit it into a space.
  14360. The source rectangle co-ordinates will be adjusted so that they fit into
  14361. the destination rectangle based on this object's flags.
  14362. */
  14363. void applyTo (double& sourceX,
  14364. double& sourceY,
  14365. double& sourceW,
  14366. double& sourceH,
  14367. const double destinationX,
  14368. const double destinationY,
  14369. const double destinationW,
  14370. const double destinationH) const throw();
  14371. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14372. into the destination rectangle using the current flags.
  14373. */
  14374. const AffineTransform getTransformToFit (float sourceX,
  14375. float sourceY,
  14376. float sourceW,
  14377. float sourceH,
  14378. const float destinationX,
  14379. const float destinationY,
  14380. const float destinationW,
  14381. const float destinationH) const throw();
  14382. private:
  14383. int flags;
  14384. };
  14385. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14386. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14387. class LowLevelGraphicsContext;
  14388. class Image;
  14389. class RectangleList;
  14390. /**
  14391. A graphics context, used for drawing a component or image.
  14392. When a Component needs painting, a Graphics context is passed to its
  14393. Component::paint() method, and this you then call methods within this
  14394. object to actually draw the component's content.
  14395. A Graphics can also be created from an image, to allow drawing directly onto
  14396. that image.
  14397. @see Component::paint
  14398. */
  14399. class JUCE_API Graphics
  14400. {
  14401. public:
  14402. /** Creates a Graphics object to draw directly onto the given image.
  14403. The graphics object that is created will be set up to draw onto the image,
  14404. with the context's clipping area being the entire size of the image, and its
  14405. origin being the image's origin. To draw into a subsection of an image, use the
  14406. reduceClipRegion() and setOrigin() methods.
  14407. Obviously you shouldn't delete the image before this context is deleted.
  14408. */
  14409. Graphics (Image& imageToDrawOnto) throw();
  14410. /** Destructor. */
  14411. ~Graphics() throw();
  14412. /** Changes the current drawing colour.
  14413. This sets the colour that will now be used for drawing operations - it also
  14414. sets the opacity to that of the colour passed-in.
  14415. If a brush is being used when this method is called, the brush will be deselected,
  14416. and any subsequent drawing will be done with a solid colour brush instead.
  14417. @see setOpacity, setBrush, getColour
  14418. */
  14419. void setColour (const Colour& newColour) throw();
  14420. /** Returns the colour that's currently being used.
  14421. This will return the last colour set by setColour(), even if the colour's not
  14422. currently being used for drawing because a brush has been selected instead.
  14423. @see setColour
  14424. */
  14425. const Colour& getCurrentColour() const throw();
  14426. /** Changes the opacity to use with the current colour.
  14427. If a solid colour is being used for drawing, this changes its opacity (and this
  14428. will be reflected by calls to the getColour() method).
  14429. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14430. */
  14431. void setOpacity (const float newOpacity) throw();
  14432. /** Changes the current brush to use for drawing.
  14433. If a null pointer is passed in, the context will revert to using a solid
  14434. colour for drawing (using the last colour set by setColour()).
  14435. If a brush is passed in, a copy of it will be used for subsequent drawing
  14436. operations until setColour() or setBrush() is called.
  14437. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14438. */
  14439. void setBrush (const Brush* const newBrush) throw();
  14440. /** Changes the font to use for subsequent text-drawing functions.
  14441. Note there's also a setFont (float, int) method to quickly change the size and
  14442. style of the current font.
  14443. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14444. */
  14445. void setFont (const Font& newFont) throw();
  14446. /** Changes the size and style of the currently-selected font.
  14447. This is a convenient shortcut that changes the context's current font to a
  14448. different size or style. The typeface won't be changed.
  14449. @see Font
  14450. */
  14451. void setFont (const float newFontHeight,
  14452. const int fontStyleFlags = Font::plain) throw();
  14453. /** Returns the font that's currently being used for text operations.
  14454. @see setFont
  14455. */
  14456. const Font& getCurrentFont() const throw();
  14457. /** Draws a one-line text string.
  14458. This will use the current colour (or brush) to fill the text. The font is the last
  14459. one specified by setFont().
  14460. @param text the string to draw
  14461. @param startX the position to draw the left-hand edge of the text
  14462. @param baselineY the position of the text's baseline
  14463. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14464. */
  14465. void drawSingleLineText (const String& text,
  14466. const int startX,
  14467. const int baselineY) const throw();
  14468. /** Draws text across multiple lines.
  14469. This will break the text onto a new line where there's a new-line or
  14470. carriage-return character, or at a word-boundary when the text becomes wider
  14471. than the size specified by the maximumLineWidth parameter.
  14472. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14473. */
  14474. void drawMultiLineText (const String& text,
  14475. const int startX,
  14476. const int baselineY,
  14477. const int maximumLineWidth) const throw();
  14478. /** Renders a string of text as a vector path.
  14479. This allows a string to be transformed with an arbitrary AffineTransform and
  14480. rendered using the current colour/brush. It's much slower than the normal text methods
  14481. but more accurate.
  14482. @see setFont
  14483. */
  14484. void drawTextAsPath (const String& text,
  14485. const AffineTransform& transform) const throw();
  14486. /** Draws a line of text within a specified rectangle.
  14487. The text will be positioned within the rectangle based on the justification
  14488. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14489. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14490. flag is true).
  14491. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14492. */
  14493. void drawText (const String& text,
  14494. const int x,
  14495. const int y,
  14496. const int width,
  14497. const int height,
  14498. const Justification& justificationType,
  14499. const bool useEllipsesIfTooBig) const throw();
  14500. /** Tries to draw a text string inside a given space.
  14501. This does its best to make the given text readable within the specified rectangle,
  14502. so it useful for labelling things.
  14503. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14504. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14505. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14506. it's been truncated.
  14507. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14508. both horizontally and vertically.
  14509. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14510. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14511. can set this value to 1.0f.
  14512. @see GlyphArrangement::addFittedText
  14513. */
  14514. void drawFittedText (const String& text,
  14515. const int x,
  14516. const int y,
  14517. const int width,
  14518. const int height,
  14519. const Justification& justificationFlags,
  14520. const int maximumNumberOfLines,
  14521. const float minimumHorizontalScale = 0.7f) const throw();
  14522. /** Fills the context's entire clip region with the current colour or brush.
  14523. (See also the fillAll (const Colour&) method which is a quick way of filling
  14524. it with a given colour).
  14525. */
  14526. void fillAll() const throw();
  14527. /** Fills the context's entire clip region with a given colour.
  14528. This leaves the context's current colour and brush unchanged, it just
  14529. uses the specified colour temporarily.
  14530. */
  14531. void fillAll (const Colour& colourToUse) const throw();
  14532. /** Fills a rectangle with the current colour or brush.
  14533. @see drawRect, fillRoundedRectangle
  14534. */
  14535. void fillRect (int x,
  14536. int y,
  14537. int width,
  14538. int height) const throw();
  14539. /** Fills a rectangle with the current colour or brush. */
  14540. void fillRect (const Rectangle& rectangle) const throw();
  14541. /** Fills a rectangle with the current colour or brush.
  14542. This uses sub-pixel positioning so is slower than the fillRect method which
  14543. takes integer co-ordinates.
  14544. */
  14545. void fillRect (const float x,
  14546. const float y,
  14547. const float width,
  14548. const float height) const throw();
  14549. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14550. @see drawRoundedRectangle, Path::addRoundedRectangle
  14551. */
  14552. void fillRoundedRectangle (const float x,
  14553. const float y,
  14554. const float width,
  14555. const float height,
  14556. const float cornerSize) const throw();
  14557. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14558. @see drawRoundedRectangle, Path::addRoundedRectangle
  14559. */
  14560. void fillRoundedRectangle (const Rectangle& rectangle,
  14561. const float cornerSize) const throw();
  14562. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14563. */
  14564. void fillCheckerBoard (int x, int y,
  14565. int width, int height,
  14566. const int checkWidth,
  14567. const int checkHeight,
  14568. const Colour& colour1,
  14569. const Colour& colour2) const throw();
  14570. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14571. The lines are drawn inside the given rectangle, and greater line thicknesses
  14572. extend inwards.
  14573. @see fillRect
  14574. */
  14575. void drawRect (const int x,
  14576. const int y,
  14577. const int width,
  14578. const int height,
  14579. const int lineThickness = 1) const throw();
  14580. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14581. The lines are drawn inside the given rectangle, and greater line thicknesses
  14582. extend inwards.
  14583. @see fillRect
  14584. */
  14585. void drawRect (const float x,
  14586. const float y,
  14587. const float width,
  14588. const float height,
  14589. const float lineThickness = 1.0f) const throw();
  14590. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14591. The lines are drawn inside the given rectangle, and greater line thicknesses
  14592. extend inwards.
  14593. @see fillRect
  14594. */
  14595. void drawRect (const Rectangle& rectangle,
  14596. const int lineThickness = 1) const throw();
  14597. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14598. @see fillRoundedRectangle, Path::addRoundedRectangle
  14599. */
  14600. void drawRoundedRectangle (const float x,
  14601. const float y,
  14602. const float width,
  14603. const float height,
  14604. const float cornerSize,
  14605. const float lineThickness) const throw();
  14606. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14607. @see fillRoundedRectangle, Path::addRoundedRectangle
  14608. */
  14609. void drawRoundedRectangle (const Rectangle& rectangle,
  14610. const float cornerSize,
  14611. const float lineThickness) const throw();
  14612. /** Draws a 3D raised (or indented) bevel using two colours.
  14613. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14614. extend inwards.
  14615. The top-left colour is used for the top- and left-hand edges of the
  14616. bevel; the bottom-right colour is used for the bottom- and right-hand
  14617. edges.
  14618. */
  14619. void drawBevel (const int x,
  14620. const int y,
  14621. const int width,
  14622. const int height,
  14623. const int bevelThickness,
  14624. const Colour& topLeftColour = Colours::white,
  14625. const Colour& bottomRightColour = Colours::black,
  14626. const bool useGradient = true) const throw();
  14627. /** Draws a pixel using the current colour or brush.
  14628. */
  14629. void setPixel (int x, int y) const throw();
  14630. /** Fills an ellipse with the current colour or brush.
  14631. The ellipse is drawn to fit inside the given rectangle.
  14632. @see drawEllipse, Path::addEllipse
  14633. */
  14634. void fillEllipse (const float x,
  14635. const float y,
  14636. const float width,
  14637. const float height) const throw();
  14638. /** Draws an elliptical stroke using the current colour or brush.
  14639. @see fillEllipse, Path::addEllipse
  14640. */
  14641. void drawEllipse (const float x,
  14642. const float y,
  14643. const float width,
  14644. const float height,
  14645. const float lineThickness) const throw();
  14646. /** Draws a line between two points.
  14647. The line is 1 pixel wide and drawn with the current colour or brush.
  14648. */
  14649. void drawLine (float startX,
  14650. float startY,
  14651. float endX,
  14652. float endY) const throw();
  14653. /** Draws a line between two points with a given thickness.
  14654. @see Path::addLineSegment
  14655. */
  14656. void drawLine (const float startX,
  14657. const float startY,
  14658. const float endX,
  14659. const float endY,
  14660. const float lineThickness) const throw();
  14661. /** Draws a line between two points.
  14662. The line is 1 pixel wide and drawn with the current colour or brush.
  14663. */
  14664. void drawLine (const Line& line) const throw();
  14665. /** Draws a line between two points with a given thickness.
  14666. @see Path::addLineSegment
  14667. */
  14668. void drawLine (const Line& line,
  14669. const float lineThickness) const throw();
  14670. /** Draws a dashed line using a custom set of dash-lengths.
  14671. @param startX the line's start x co-ordinate
  14672. @param startY the line's start y co-ordinate
  14673. @param endX the line's end x co-ordinate
  14674. @param endY the line's end y co-ordinate
  14675. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14676. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14677. draw 6 pixels, skip 7 pixels, and then repeat.
  14678. @param numDashLengths the number of elements in the array (this must be an even number).
  14679. @param lineThickness the thickness of the line to draw
  14680. @see PathStrokeType::createDashedStroke
  14681. */
  14682. void drawDashedLine (const float startX,
  14683. const float startY,
  14684. const float endX,
  14685. const float endY,
  14686. const float* const dashLengths,
  14687. const int numDashLengths,
  14688. const float lineThickness = 1.0f) const throw();
  14689. /** Draws a vertical line of pixels at a given x position.
  14690. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14691. positions, and these will be anti-aliased if necessary.
  14692. */
  14693. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14694. /** Draws a horizontal line of pixels at a given y position.
  14695. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14696. positions, and these will be anti-aliased if necessary.
  14697. */
  14698. void drawHorizontalLine (const int y, float left, float right) const throw();
  14699. /** Fills a path using the currently selected colour or brush.
  14700. */
  14701. void fillPath (const Path& path,
  14702. const AffineTransform& transform = AffineTransform::identity) const throw();
  14703. /** Draws a path's outline using the currently selected colour or brush.
  14704. */
  14705. void strokePath (const Path& path,
  14706. const PathStrokeType& strokeType,
  14707. const AffineTransform& transform = AffineTransform::identity) const throw();
  14708. /** Draws a line with an arrowhead.
  14709. @param startX the line's start x co-ordinate
  14710. @param startY the line's start y co-ordinate
  14711. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14712. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14713. @param lineThickness the thickness of the line
  14714. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14715. @param arrowheadLength the length of the arrow head (along the length of the line)
  14716. */
  14717. void drawArrow (const float startX,
  14718. const float startY,
  14719. const float endX,
  14720. const float endY,
  14721. const float lineThickness,
  14722. const float arrowheadWidth,
  14723. const float arrowheadLength) const throw();
  14724. /** Types of rendering quality that can be specified when drawing images.
  14725. @see blendImage, Graphics::setImageResamplingQuality
  14726. */
  14727. enum ResamplingQuality
  14728. {
  14729. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14730. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14731. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14732. };
  14733. /** Changes the quality that will be used when resampling images.
  14734. By default a Graphics object will be set to mediumRenderingQuality.
  14735. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14736. */
  14737. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14738. /** Draws an image.
  14739. This will draw the whole of an image, positioning its top-left corner at the
  14740. given co-ordinates, and keeping its size the same. This is the simplest image
  14741. drawing method - the others give more control over the scaling and clipping
  14742. of the images.
  14743. Images are composited using the context's current opacity, so if you
  14744. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14745. (or setColour() with an opaque colour) before drawing images.
  14746. */
  14747. void drawImageAt (const Image* const imageToDraw,
  14748. const int topLeftX,
  14749. const int topLeftY,
  14750. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14751. /** Draws part of an image, rescaling it to fit in a given target region.
  14752. The specified area of the source image is rescaled and drawn to fill the
  14753. specifed destination rectangle.
  14754. Images are composited using the context's current opacity, so if you
  14755. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14756. (or setColour() with an opaque colour) before drawing images.
  14757. @param imageToDraw the image to overlay
  14758. @param destX the left of the destination rectangle
  14759. @param destY the top of the destination rectangle
  14760. @param destWidth the width of the destination rectangle
  14761. @param destHeight the height of the destination rectangle
  14762. @param sourceX the left of the rectangle to copy from the source image
  14763. @param sourceY the top of the rectangle to copy from the source image
  14764. @param sourceWidth the width of the rectangle to copy from the source image
  14765. @param sourceHeight the height of the rectangle to copy from the source image
  14766. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14767. the source image's alpha channel is used as a mask with
  14768. which to fill the destination using the current colour
  14769. or brush. (If the source is has no alpha channel, then
  14770. it will just fill the target with a solid rectangle)
  14771. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14772. */
  14773. void drawImage (const Image* const imageToDraw,
  14774. int destX,
  14775. int destY,
  14776. int destWidth,
  14777. int destHeight,
  14778. int sourceX,
  14779. int sourceY,
  14780. int sourceWidth,
  14781. int sourceHeight,
  14782. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14783. /** Draws part of an image, having applied an affine transform to it.
  14784. This lets you throw the image around in some wacky ways, rotate it, shear,
  14785. scale it, etc.
  14786. A clipping subregion is specified within the source image and no pixels
  14787. outside this region will be used.
  14788. Images are composited using the context's current opacity, so if you
  14789. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14790. (or setColour() with an opaque colour) before drawing images.
  14791. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14792. are ignored and it is filled with the current brush, masked by its alpha channel.
  14793. @see setImageResamplingQuality, drawImage
  14794. */
  14795. void drawImageTransformed (const Image* const imageToDraw,
  14796. int sourceClipX,
  14797. int sourceClipY,
  14798. int sourceClipWidth,
  14799. int sourceClipHeight,
  14800. const AffineTransform& transform,
  14801. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14802. /** Draws an image to fit within a designated rectangle.
  14803. If the image is too big or too small for the space, it will be rescaled
  14804. to fit as nicely as it can do without affecting its aspect ratio. It will
  14805. then be placed within the target rectangle according to the justification flags
  14806. specified.
  14807. @param imageToDraw the source image to draw
  14808. @param destX top-left of the target rectangle to fit it into
  14809. @param destY top-left of the target rectangle to fit it into
  14810. @param destWidth size of the target rectangle to fit the image into
  14811. @param destHeight size of the target rectangle to fit the image into
  14812. @param placementWithinTarget this specifies how the image should be positioned
  14813. within the target rectangle - see the RectanglePlacement
  14814. class for more details about this.
  14815. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14816. alpha channel will be used as a mask with which to
  14817. draw with the current brush or colour. This is
  14818. similar to fillAlphaMap(), and see also drawImage()
  14819. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14820. */
  14821. void drawImageWithin (const Image* const imageToDraw,
  14822. const int destX,
  14823. const int destY,
  14824. const int destWidth,
  14825. const int destHeight,
  14826. const RectanglePlacement& placementWithinTarget,
  14827. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14828. /** Returns the position of the bounding box for the current clipping region.
  14829. @see getClipRegion, clipRegionIntersects
  14830. */
  14831. const Rectangle getClipBounds() const throw();
  14832. /** Checks whether a rectangle overlaps the context's clipping region.
  14833. If this returns false, no part of the given area can be drawn onto, so this
  14834. method can be used to optimise a component's paint() method, by letting it
  14835. avoid drawing complex objects that aren't within the region being repainted.
  14836. */
  14837. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14838. /** Intersects the current clipping region with another region.
  14839. @returns true if the resulting clipping region is non-zero in size
  14840. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14841. */
  14842. bool reduceClipRegion (const int x, const int y,
  14843. const int width, const int height) throw();
  14844. /** Intersects the current clipping region with a rectangle list region.
  14845. @returns true if the resulting clipping region is non-zero in size
  14846. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14847. */
  14848. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14849. /** Excludes a rectangle to stop it being drawn into. */
  14850. void excludeClipRegion (const int x, const int y,
  14851. const int width, const int height) throw();
  14852. /** Returns true if no drawing can be done because the clip region is zero. */
  14853. bool isClipEmpty() const throw();
  14854. /** Saves the current graphics state on an internal stack.
  14855. To restore the state, use restoreState().
  14856. */
  14857. void saveState() throw();
  14858. /** Restores a graphics state that was previously saved with saveState().
  14859. */
  14860. void restoreState() throw();
  14861. /** Moves the position of the context's origin.
  14862. This changes the position that the context considers to be (0, 0) to
  14863. the specified position.
  14864. So if you call setOrigin (100, 100), then the position that was previously
  14865. referred to as (100, 100) will subsequently be considered to be (0, 0).
  14866. @see reduceClipRegion
  14867. */
  14868. void setOrigin (const int newOriginX,
  14869. const int newOriginY) throw();
  14870. /** Resets the current colour, brush, and font to default settings. */
  14871. void resetToDefaultState() throw();
  14872. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  14873. bool isVectorDevice() const throw();
  14874. juce_UseDebuggingNewOperator
  14875. /** Create a graphics that uses a given low-level renderer.
  14876. For internal use only.
  14877. NB. The context will NOT be deleted by this object when it is deleted.
  14878. */
  14879. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  14880. /** @internal */
  14881. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  14882. private:
  14883. LowLevelGraphicsContext* const context;
  14884. const bool ownsContext;
  14885. struct GraphicsState
  14886. {
  14887. GraphicsState() throw();
  14888. GraphicsState (const GraphicsState&) throw();
  14889. ~GraphicsState() throw();
  14890. Colour colour;
  14891. Brush* brush;
  14892. Font font;
  14893. ResamplingQuality quality;
  14894. };
  14895. GraphicsState* state;
  14896. OwnedArray <GraphicsState> stateStack;
  14897. bool saveStatePending;
  14898. void saveStateIfPending() throw();
  14899. const Graphics& operator= (const Graphics& other);
  14900. Graphics (const Graphics&);
  14901. };
  14902. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  14903. /********* End of inlined file: juce_Graphics.h *********/
  14904. /**
  14905. A graphical effect filter that can be applied to components.
  14906. An ImageEffectFilter can be applied to the image that a component
  14907. paints before it hits the screen.
  14908. This is used for adding effects like shadows, blurs, etc.
  14909. @see Component::setComponentEffect
  14910. */
  14911. class JUCE_API ImageEffectFilter
  14912. {
  14913. public:
  14914. /** Overridden to render the effect.
  14915. The implementation of this method must use the image that is passed in
  14916. as its source, and should render its output to the graphics context passed in.
  14917. @param sourceImage the image that the source component has just rendered with
  14918. its paint() method. The image may or may not have an alpha
  14919. channel, depending on whether the component is opaque.
  14920. @param destContext the graphics context to use to draw the resultant image.
  14921. */
  14922. virtual void applyEffect (Image& sourceImage,
  14923. Graphics& destContext) = 0;
  14924. /** Destructor. */
  14925. virtual ~ImageEffectFilter() {}
  14926. };
  14927. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  14928. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  14929. /********* Start of inlined file: juce_RectangleList.h *********/
  14930. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  14931. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  14932. /**
  14933. Maintains a set of rectangles as a complex region.
  14934. This class allows a set of rectangles to be treated as a solid shape, and can
  14935. add and remove rectangular sections of it, and simplify overlapping or
  14936. adjacent rectangles.
  14937. @see Rectangle
  14938. */
  14939. class JUCE_API RectangleList
  14940. {
  14941. public:
  14942. /** Creates an empty RectangleList */
  14943. RectangleList() throw();
  14944. /** Creates a copy of another list */
  14945. RectangleList (const RectangleList& other) throw();
  14946. /** Creates a list containing just one rectangle. */
  14947. RectangleList (const Rectangle& rect) throw();
  14948. /** Copies this list from another one. */
  14949. const RectangleList& operator= (const RectangleList& other) throw();
  14950. /** Destructor. */
  14951. ~RectangleList() throw();
  14952. /** Returns true if the region is empty. */
  14953. bool isEmpty() const throw();
  14954. /** Returns the number of rectangles in the list. */
  14955. int getNumRectangles() const throw() { return rects.size(); }
  14956. /** Returns one of the rectangles at a particular index.
  14957. @returns the rectangle at the index, or an empty rectangle if the
  14958. index is out-of-range.
  14959. */
  14960. const Rectangle getRectangle (const int index) const throw();
  14961. /** Removes all rectangles to leave an empty region. */
  14962. void clear() throw();
  14963. /** Merges a new rectangle into the list.
  14964. The rectangle being added will first be clipped to remove any parts of it
  14965. that overlap existing rectangles in the list.
  14966. */
  14967. void add (const int x, const int y,
  14968. const int w, const int h) throw();
  14969. /** Merges a new rectangle into the list.
  14970. The rectangle being added will first be clipped to remove any parts of it
  14971. that overlap existing rectangles in the list, and adjacent rectangles will be
  14972. merged into it.
  14973. */
  14974. void add (const Rectangle& rect) throw();
  14975. /** Dumbly adds a rectangle to the list without checking for overlaps.
  14976. This simply adds the rectangle to the end, it doesn't merge it or remove
  14977. any overlapping bits.
  14978. */
  14979. void addWithoutMerging (const Rectangle& rect) throw();
  14980. /** Merges another rectangle list into this one.
  14981. Any overlaps between the two lists will be clipped, so that the result is
  14982. the union of both lists.
  14983. */
  14984. void add (const RectangleList& other) throw();
  14985. /** Removes a rectangular region from the list.
  14986. Any rectangles in the list which overlap this will be clipped and subdivided
  14987. if necessary.
  14988. */
  14989. void subtract (const Rectangle& rect) throw();
  14990. /** Removes all areas in another RectangleList from this one.
  14991. Any rectangles in the list which overlap this will be clipped and subdivided
  14992. if necessary.
  14993. */
  14994. void subtract (const RectangleList& otherList) throw();
  14995. /** Removes any areas of the region that lie outside a given rectangle.
  14996. Any rectangles in the list which overlap this will be clipped and subdivided
  14997. if necessary.
  14998. Returns true if the resulting region is not empty, false if it is empty.
  14999. @see getIntersectionWith
  15000. */
  15001. bool clipTo (const Rectangle& rect) throw();
  15002. /** Removes any areas of the region that lie outside a given rectangle list.
  15003. Any rectangles in this object which overlap the specified list will be clipped
  15004. and subdivided if necessary.
  15005. Returns true if the resulting region is not empty, false if it is empty.
  15006. @see getIntersectionWith
  15007. */
  15008. bool clipTo (const RectangleList& other) throw();
  15009. /** Creates a region which is the result of clipping this one to a given rectangle.
  15010. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  15011. resulting region into the list whose reference is passed-in.
  15012. Returns true if the resulting region is not empty, false if it is empty.
  15013. @see clipTo
  15014. */
  15015. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15016. /** Swaps the contents of this and another list.
  15017. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15018. to swap them.
  15019. */
  15020. void swapWith (RectangleList& otherList) throw();
  15021. /** Checks whether the region contains a given point.
  15022. @returns true if the point lies within one of the rectangles in the list
  15023. */
  15024. bool containsPoint (const int x, const int y) const throw();
  15025. /** Checks whether the region contains the whole of a given rectangle.
  15026. @returns true all parts of the rectangle passed in lie within the region
  15027. defined by this object
  15028. @see intersectsRectangle, containsPoint
  15029. */
  15030. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15031. /** Checks whether the region contains any part of a given rectangle.
  15032. @returns true if any part of the rectangle passed in lies within the region
  15033. defined by this object
  15034. @see containsRectangle
  15035. */
  15036. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15037. /** Checks whether this region intersects any part of another one.
  15038. @see intersectsRectangle
  15039. */
  15040. bool intersects (const RectangleList& other) const throw();
  15041. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15042. const Rectangle getBounds() const throw();
  15043. /** Optimises the list into a minimum number of constituent rectangles.
  15044. This will try to combine any adjacent rectangles into larger ones where
  15045. possible, to simplify lists that might have been fragmented by repeated
  15046. add/subtract calls.
  15047. */
  15048. void consolidate() throw();
  15049. /** Adds an x and y value to all the co-ordinates. */
  15050. void offsetAll (const int dx, const int dy) throw();
  15051. /** Creates a Path object to represent this region. */
  15052. const Path toPath() const throw();
  15053. /** An iterator for accessing all the rectangles in a RectangleList. */
  15054. class Iterator
  15055. {
  15056. public:
  15057. Iterator (const RectangleList& list) throw();
  15058. ~Iterator() throw();
  15059. /** Advances to the next rectangle, and returns true if it's not finished.
  15060. Call this before using getRectangle() to find the rectangle that was returned.
  15061. */
  15062. bool next() throw();
  15063. /** Returns the current rectangle. */
  15064. const Rectangle* getRectangle() const throw() { return current; }
  15065. juce_UseDebuggingNewOperator
  15066. private:
  15067. const Rectangle* current;
  15068. const RectangleList& owner;
  15069. int index;
  15070. Iterator (const Iterator&);
  15071. const Iterator& operator= (const Iterator&);
  15072. };
  15073. juce_UseDebuggingNewOperator
  15074. private:
  15075. friend class Iterator;
  15076. Array <Rectangle> rects;
  15077. };
  15078. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15079. /********* End of inlined file: juce_RectangleList.h *********/
  15080. /********* Start of inlined file: juce_BorderSize.h *********/
  15081. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15082. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15083. /**
  15084. Specifies a set of gaps to be left around the sides of a rectangle.
  15085. This is basically the size of the spaces at the top, bottom, left and right of
  15086. a rectangle. It's used by various component classes to specify borders.
  15087. @see Rectangle
  15088. */
  15089. class JUCE_API BorderSize
  15090. {
  15091. public:
  15092. /** Creates a null border.
  15093. All sizes are left as 0.
  15094. */
  15095. BorderSize() throw();
  15096. /** Creates a copy of another border. */
  15097. BorderSize (const BorderSize& other) throw();
  15098. /** Creates a border with the given gaps. */
  15099. BorderSize (const int topGap,
  15100. const int leftGap,
  15101. const int bottomGap,
  15102. const int rightGap) throw();
  15103. /** Creates a border with the given gap on all sides. */
  15104. BorderSize (const int allGaps) throw();
  15105. /** Destructor. */
  15106. ~BorderSize() throw();
  15107. /** Returns the gap that should be left at the top of the region. */
  15108. int getTop() const throw() { return top; }
  15109. /** Returns the gap that should be left at the top of the region. */
  15110. int getLeft() const throw() { return left; }
  15111. /** Returns the gap that should be left at the top of the region. */
  15112. int getBottom() const throw() { return bottom; }
  15113. /** Returns the gap that should be left at the top of the region. */
  15114. int getRight() const throw() { return right; }
  15115. /** Returns the sum of the top and bottom gaps. */
  15116. int getTopAndBottom() const throw() { return top + bottom; }
  15117. /** Returns the sum of the left and right gaps. */
  15118. int getLeftAndRight() const throw() { return left + right; }
  15119. /** Changes the top gap. */
  15120. void setTop (const int newTopGap) throw();
  15121. /** Changes the left gap. */
  15122. void setLeft (const int newLeftGap) throw();
  15123. /** Changes the bottom gap. */
  15124. void setBottom (const int newBottomGap) throw();
  15125. /** Changes the right gap. */
  15126. void setRight (const int newRightGap) throw();
  15127. /** Returns a rectangle with these borders removed from it. */
  15128. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15129. /** Removes this border from a given rectangle. */
  15130. void subtractFrom (Rectangle& rectangle) const throw();
  15131. /** Returns a rectangle with these borders added around it. */
  15132. const Rectangle addedTo (const Rectangle& original) const throw();
  15133. /** Adds this border around a given rectangle. */
  15134. void addTo (Rectangle& original) const throw();
  15135. bool operator== (const BorderSize& other) const throw();
  15136. bool operator!= (const BorderSize& other) const throw();
  15137. juce_UseDebuggingNewOperator
  15138. private:
  15139. int top, left, bottom, right;
  15140. };
  15141. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15142. /********* End of inlined file: juce_BorderSize.h *********/
  15143. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15144. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15145. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15146. class Component;
  15147. class Graphics;
  15148. /********* Start of inlined file: juce_MessageListener.h *********/
  15149. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15150. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15151. /********* Start of inlined file: juce_Message.h *********/
  15152. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15153. #define __JUCE_MESSAGE_JUCEHEADER__
  15154. class MessageListener;
  15155. class MessageManager;
  15156. /** The base class for objects that can be delivered to a MessageListener.
  15157. The simplest Message object contains a few integer and pointer parameters
  15158. that the user can set, and this is enough for a lot of purposes. For passing more
  15159. complex data, subclasses of Message can also be used.
  15160. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15161. */
  15162. class JUCE_API Message
  15163. {
  15164. public:
  15165. /** Creates an uninitialised message.
  15166. The class's variables will also be left uninitialised.
  15167. */
  15168. Message() throw();
  15169. /** Creates a message object, filling in the member variables.
  15170. The corresponding public member variables will be set from the parameters
  15171. passed in.
  15172. */
  15173. Message (const int intParameter1,
  15174. const int intParameter2,
  15175. const int intParameter3,
  15176. void* const pointerParameter) throw();
  15177. /** Destructor. */
  15178. virtual ~Message() throw();
  15179. // These values can be used for carrying simple data that the application needs to
  15180. // pass around. For more complex messages, just create a subclass.
  15181. int intParameter1; /**< user-defined integer value. */
  15182. int intParameter2; /**< user-defined integer value. */
  15183. int intParameter3; /**< user-defined integer value. */
  15184. void* pointerParameter; /**< user-defined pointer value. */
  15185. juce_UseDebuggingNewOperator
  15186. private:
  15187. friend class MessageListener;
  15188. friend class MessageManager;
  15189. MessageListener* messageRecipient;
  15190. Message (const Message&);
  15191. const Message& operator= (const Message&);
  15192. };
  15193. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15194. /********* End of inlined file: juce_Message.h *********/
  15195. /**
  15196. MessageListener subclasses can post and receive Message objects.
  15197. @see Message, MessageManager, ActionListener, ChangeListener
  15198. */
  15199. class JUCE_API MessageListener
  15200. {
  15201. protected:
  15202. /** Creates a MessageListener. */
  15203. MessageListener() throw();
  15204. public:
  15205. /** Destructor.
  15206. When a MessageListener is deleted, it removes itself from a global list
  15207. of registered listeners, so that the isValidMessageListener() method
  15208. will no longer return true.
  15209. */
  15210. virtual ~MessageListener();
  15211. /** This is the callback method that receives incoming messages.
  15212. This is called by the MessageManager from its dispatch loop.
  15213. @see postMessage
  15214. */
  15215. virtual void handleMessage (const Message& message) = 0;
  15216. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15217. later on.
  15218. This method can be called safely by any thread.
  15219. @param message the message object to send - this will be deleted
  15220. automatically by the message queue, so don't keep any
  15221. references to it after calling this method.
  15222. @see handleMessage
  15223. */
  15224. void postMessage (Message* const message) const throw();
  15225. /** Checks whether this MessageListener has been deleted.
  15226. Although not foolproof, this method is safe to call on dangling or null
  15227. pointers. A list of active MessageListeners is kept internally, so this
  15228. checks whether the object is on this list or not.
  15229. Note that it's possible to get a false-positive here, if an object is
  15230. deleted and another is subsequently created that happens to be at the
  15231. exact same memory location, but I can't think of a good way of avoiding
  15232. this.
  15233. */
  15234. bool isValidMessageListener() const throw();
  15235. };
  15236. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15237. /********* End of inlined file: juce_MessageListener.h *********/
  15238. class ComponentBoundsConstrainer;
  15239. class ComponentDeletionWatcher;
  15240. /**
  15241. The base class for window objects that wrap a component as a real operating
  15242. system object.
  15243. This is an abstract base class - the platform specific code contains default
  15244. implementations of it that create and manage windows.
  15245. @see Component::createNewPeer
  15246. */
  15247. class JUCE_API ComponentPeer : public MessageListener
  15248. {
  15249. public:
  15250. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15251. enum StyleFlags
  15252. {
  15253. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15254. entry on the taskbar (ignored on MacOSX) */
  15255. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15256. tooltip, etc. */
  15257. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15258. through it (may not be possible on some platforms). */
  15259. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15260. title bar and frame\. if not specified, the window will be
  15261. borderless. */
  15262. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15263. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15264. minimise button on it. */
  15265. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15266. maximise button on it. */
  15267. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15268. close button on it. */
  15269. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15270. not be possible on all platforms). */
  15271. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15272. do its own repainting, but only to repaint when the
  15273. performAnyPendingRepaintsNow() method is called. */
  15274. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15275. be used for things like plugin windows, to stop them interfering
  15276. with the host's shortcut keys */
  15277. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15278. };
  15279. /** Creates a peer.
  15280. The component is the one that we intend to represent, and the style flags are
  15281. a combination of the values in the StyleFlags enum
  15282. */
  15283. ComponentPeer (Component* const component,
  15284. const int styleFlags) throw();
  15285. /** Destructor. */
  15286. virtual ~ComponentPeer();
  15287. /** Returns the component being represented by this peer. */
  15288. Component* getComponent() const throw() { return component; }
  15289. /** Returns the set of style flags that were set when the window was created.
  15290. @see Component::addToDesktop
  15291. */
  15292. int getStyleFlags() const throw() { return styleFlags; }
  15293. /** Returns the raw handle to whatever kind of window is being used.
  15294. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15295. but rememeber there's no guarantees what you'll get back.
  15296. */
  15297. virtual void* getNativeHandle() const = 0;
  15298. /** Shows or hides the window. */
  15299. virtual void setVisible (bool shouldBeVisible) = 0;
  15300. /** Changes the title of the window. */
  15301. virtual void setTitle (const String& title) = 0;
  15302. /** Moves the window without changing its size.
  15303. If the native window is contained in another window, then the co-ordinates are
  15304. relative to the parent window's origin, not the screen origin.
  15305. This should result in a callback to handleMovedOrResized().
  15306. */
  15307. virtual void setPosition (int x, int y) = 0;
  15308. /** Resizes the window without changing its position.
  15309. This should result in a callback to handleMovedOrResized().
  15310. */
  15311. virtual void setSize (int w, int h) = 0;
  15312. /** Moves and resizes the window.
  15313. If the native window is contained in another window, then the co-ordinates are
  15314. relative to the parent window's origin, not the screen origin.
  15315. This should result in a callback to handleMovedOrResized().
  15316. */
  15317. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15318. /** Returns the current position and size of the window.
  15319. If the native window is contained in another window, then the co-ordinates are
  15320. relative to the parent window's origin, not the screen origin.
  15321. */
  15322. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15323. /** Returns the x-position of this window, relative to the screen's origin. */
  15324. virtual int getScreenX() const = 0;
  15325. /** Returns the y-position of this window, relative to the screen's origin. */
  15326. virtual int getScreenY() const = 0;
  15327. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15328. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15329. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15330. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15331. /** Minimises the window. */
  15332. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15333. /** True if the window is currently minimised. */
  15334. virtual bool isMinimised() const = 0;
  15335. /** Enable/disable fullscreen mode for the window. */
  15336. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15337. /** True if the window is currently full-screen. */
  15338. virtual bool isFullScreen() const = 0;
  15339. /** Sets the size to restore to if fullscreen mode is turned off. */
  15340. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15341. /** Returns the size to restore to if fullscreen mode is turned off. */
  15342. const Rectangle& getNonFullScreenBounds() const throw();
  15343. /** Attempts to change the icon associated with this window.
  15344. */
  15345. virtual void setIcon (const Image& newIcon) = 0;
  15346. /** Sets a constrainer to use if the peer can resize itself.
  15347. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15348. */
  15349. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15350. /** Returns the current constrainer, if one has been set. */
  15351. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15352. /** Checks if a point is in the window.
  15353. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15354. is false, then this returns false if the point is actually inside a child of this
  15355. window.
  15356. */
  15357. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15358. /** Returns the size of the window frame that's around this window.
  15359. Whether or not the window has a normal window frame depends on the flags
  15360. that were set when the window was created by Component::addToDesktop()
  15361. */
  15362. virtual const BorderSize getFrameSize() const = 0;
  15363. /** This is called when the window's bounds change.
  15364. A peer implementation must call this when the window is moved and resized, so that
  15365. this method can pass the message on to the component.
  15366. */
  15367. void handleMovedOrResized();
  15368. /** This is called if the screen resolution changes.
  15369. A peer implementation must call this if the monitor arrangement changes or the available
  15370. screen size changes.
  15371. */
  15372. void handleScreenSizeChange();
  15373. /** This is called to repaint the component into the given context. */
  15374. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15375. /** Sets this window to either be always-on-top or normal.
  15376. Some kinds of window might not be able to do this, so should return false.
  15377. */
  15378. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15379. /** Brings the window to the top, optionally also giving it focus. */
  15380. virtual void toFront (bool makeActive) = 0;
  15381. /** Moves the window to be just behind another one. */
  15382. virtual void toBehind (ComponentPeer* other) = 0;
  15383. /** Called when the window is brought to the front, either by the OS or by a call
  15384. to toFront().
  15385. */
  15386. void handleBroughtToFront();
  15387. /** True if the window has the keyboard focus. */
  15388. virtual bool isFocused() const = 0;
  15389. /** Tries to give the window keyboard focus. */
  15390. virtual void grabFocus() = 0;
  15391. /** Tells the window that text input may be required at the given position.
  15392. This may cause things like a virtual on-screen keyboard to appear, depending
  15393. on the OS.
  15394. */
  15395. virtual void textInputRequired (int x, int y) = 0;
  15396. /** Called when the window gains keyboard focus. */
  15397. void handleFocusGain();
  15398. /** Called when the window loses keyboard focus. */
  15399. void handleFocusLoss();
  15400. Component* getLastFocusedSubcomponent() const throw();
  15401. /** Called when a key is pressed.
  15402. For keycode info, see the KeyPress class.
  15403. Returns true if the keystroke was used.
  15404. */
  15405. bool handleKeyPress (const int keyCode,
  15406. const juce_wchar textCharacter);
  15407. /** Called whenever a key is pressed or released.
  15408. Returns true if the keystroke was used.
  15409. */
  15410. bool handleKeyUpOrDown();
  15411. /** Called whenever a modifier key is pressed or released. */
  15412. void handleModifierKeysChange();
  15413. /** Invalidates a region of the window to be repainted asynchronously. */
  15414. virtual void repaint (int x, int y, int w, int h) = 0;
  15415. /** This can be called (from the message thread) to cause the immediate redrawing
  15416. of any areas of this window that need repainting.
  15417. You shouldn't ever really need to use this, it's mainly for special purposes
  15418. like supporting audio plugins where the host's event loop is out of our control.
  15419. */
  15420. virtual void performAnyPendingRepaintsNow() = 0;
  15421. void handleMouseEnter (int x, int y, const int64 time);
  15422. void handleMouseMove (int x, int y, const int64 time);
  15423. void handleMouseDown (int x, int y, const int64 time);
  15424. void handleMouseDrag (int x, int y, const int64 time);
  15425. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15426. void handleMouseExit (int x, int y, const int64 time);
  15427. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15428. /** Causes a mouse-move callback to be made asynchronously. */
  15429. void sendFakeMouseMove() throw();
  15430. void handleUserClosingWindow();
  15431. void handleFileDragMove (const StringArray& files, int x, int y);
  15432. void handleFileDragExit (const StringArray& files);
  15433. void handleFileDragDrop (const StringArray& files, int x, int y);
  15434. /** Resets the masking region.
  15435. The subclass should call this every time it's about to call the handlePaint
  15436. method.
  15437. @see addMaskedRegion
  15438. */
  15439. void clearMaskedRegion() throw();
  15440. /** Adds a rectangle to the set of areas not to paint over.
  15441. A component can call this on its peer during its paint() method, to signal
  15442. that the painting code should ignore a given region. The reason
  15443. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15444. The masked region is cleared each time before a paint happens, so a component
  15445. will have to make sure it calls this every time it's painted.
  15446. */
  15447. void addMaskedRegion (int x, int y, int w, int h) throw();
  15448. /** Returns the number of currently-active peers.
  15449. @see getPeer
  15450. */
  15451. static int getNumPeers() throw();
  15452. /** Returns one of the currently-active peers.
  15453. @see getNumPeers
  15454. */
  15455. static ComponentPeer* getPeer (const int index) throw();
  15456. /** Checks if this peer object is valid.
  15457. @see getNumPeers
  15458. */
  15459. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15460. juce_UseDebuggingNewOperator
  15461. protected:
  15462. Component* const component;
  15463. const int styleFlags;
  15464. RectangleList maskedRegion;
  15465. Rectangle lastNonFullscreenBounds;
  15466. uint32 lastPaintTime;
  15467. ComponentBoundsConstrainer* constrainer;
  15468. static void updateCurrentModifiers() throw();
  15469. /** @internal */
  15470. void handleMessage (const Message& message);
  15471. private:
  15472. Component* lastFocusedComponent;
  15473. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15474. Component* lastDragAndDropCompUnderMouse;
  15475. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15476. friend class Component;
  15477. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15478. void setLastDragDropTarget (Component* comp);
  15479. ComponentPeer (const ComponentPeer&);
  15480. const ComponentPeer& operator= (const ComponentPeer&);
  15481. };
  15482. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15483. /********* End of inlined file: juce_ComponentPeer.h *********/
  15484. class LookAndFeel;
  15485. /**
  15486. The base class for all JUCE user-interface objects.
  15487. */
  15488. class JUCE_API Component : public MouseListener,
  15489. protected MessageListener
  15490. {
  15491. public:
  15492. /** Creates a component.
  15493. To get it to actually appear, you'll also need to:
  15494. - Either add it to a parent component or use the addToDesktop() method to
  15495. make it a desktop window
  15496. - Set its size and position to something sensible
  15497. - Use setVisible() to make it visible
  15498. And for it to serve any useful purpose, you'll need to write a
  15499. subclass of Component or use one of the other types of component from
  15500. the library.
  15501. */
  15502. Component() throw();
  15503. /** Destructor.
  15504. Note that when a component is deleted, any child components it might
  15505. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15506. */
  15507. virtual ~Component();
  15508. /** Creates a component, setting its name at the same time.
  15509. @see getName, setName
  15510. */
  15511. Component (const String& componentName) throw();
  15512. /** Returns the name of this component.
  15513. @see setName
  15514. */
  15515. const String& getName() const throw() { return componentName_; }
  15516. /** Sets the name of this component.
  15517. When the name changes, all registered ComponentListeners will receive a
  15518. ComponentListener::componentNameChanged() callback.
  15519. @see getName
  15520. */
  15521. virtual void setName (const String& newName);
  15522. /** Checks whether this Component object has been deleted.
  15523. This will check whether this object is still a valid component, or whether
  15524. it's been deleted.
  15525. It's safe to call this on null or dangling pointers, but note that there is a
  15526. small risk if another new (but different) component has been created at the
  15527. same memory address which this one occupied, this methods can return a
  15528. false positive.
  15529. */
  15530. bool isValidComponent() const throw();
  15531. /** Makes the component visible or invisible.
  15532. This method will show or hide the component.
  15533. Note that components default to being non-visible when first created.
  15534. Also note that visible components won't be seen unless all their parent components
  15535. are also visible.
  15536. This method will call visibilityChanged() and also componentVisibilityChanged()
  15537. for any component listeners that are interested in this component.
  15538. @param shouldBeVisible whether to show or hide the component
  15539. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15540. */
  15541. virtual void setVisible (bool shouldBeVisible);
  15542. /** Tests whether the component is visible or not.
  15543. this doesn't necessarily tell you whether this comp is actually on the screen
  15544. because this depends on whether all the parent components are also visible - use
  15545. isShowing() to find this out.
  15546. @see isShowing, setVisible
  15547. */
  15548. bool isVisible() const throw() { return flags.visibleFlag; }
  15549. /** Called when this component's visiblility changes.
  15550. @see setVisible, isVisible
  15551. */
  15552. virtual void visibilityChanged();
  15553. /** Tests whether this component and all its parents are visible.
  15554. @returns true only if this component and all its parents are visible.
  15555. @see isVisible
  15556. */
  15557. bool isShowing() const throw();
  15558. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15559. To do this, this function will cunningly:
  15560. - take a snapshot of the component as it currently looks
  15561. - call setVisible(false) on the component
  15562. - replace it with a special component that will continue drawing the
  15563. snapshot, animating it and gradually making it more transparent
  15564. - when it's gone, the special component will also be deleted
  15565. As soon as this method returns, the component can be safely removed and deleted
  15566. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15567. component's destructor.
  15568. Passing non-zero x and y values will cause the ghostly component image to
  15569. also whizz off by this distance while fading out. If the scale factor is
  15570. not 1.0, it will also zoom from the component's current size to this new size.
  15571. One thing to be careful about is that the parent component must be able to cope
  15572. with this unknown component type being added to it.
  15573. */
  15574. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15575. const int deltaXToMove = 0,
  15576. const int deltaYToMove = 0,
  15577. const float scaleFactorAtEnd = 1.0f);
  15578. /** Makes this component appear as a window on the desktop.
  15579. Note that before calling this, you should make sure that the component's opacity is
  15580. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15581. system will try to create a special transparent window for it, which will generally take
  15582. a lot more CPU to operate (and might not even be possible on some platforms).
  15583. If the component is inside a parent component at the time this method is called, it
  15584. will be first be removed from that parent. Likewise if a component on the desktop
  15585. is subsequently added to another component, it'll be removed from the desktop.
  15586. @param windowStyleFlags a combination of the flags specified in the
  15587. ComponentPeer::StyleFlags enum, which define the
  15588. window's characteristics.
  15589. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15590. in which the juce component should place itself. On Windows,
  15591. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15592. supported on all platforms, and best left as 0 unless you know
  15593. what you're doing
  15594. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15595. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15596. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15597. */
  15598. virtual void addToDesktop (int windowStyleFlags,
  15599. void* nativeWindowToAttachTo = 0);
  15600. /** If the component is currently showing on the desktop, this will hide it.
  15601. You can also use setVisible() to hide a desktop window temporarily, but
  15602. removeFromDesktop() will free any system resources that are being used up.
  15603. @see addToDesktop, isOnDesktop
  15604. */
  15605. void removeFromDesktop();
  15606. /** Returns true if this component is currently showing on the desktop.
  15607. @see addToDesktop, removeFromDesktop
  15608. */
  15609. bool isOnDesktop() const throw();
  15610. /** Returns the heavyweight window that contains this component.
  15611. If this component is itself on the desktop, this will return the window
  15612. object that it is using. Otherwise, it will return the window of
  15613. its top-level parent component.
  15614. This may return 0 if there isn't a desktop component.
  15615. @see addToDesktop, isOnDesktop
  15616. */
  15617. ComponentPeer* getPeer() const throw();
  15618. /** For components on the desktop, this is called if the system wants to close the window.
  15619. This is a signal that either the user or the system wants the window to close. The
  15620. default implementation of this method will trigger an assertion to warn you that your
  15621. component should do something about it, but you can override this to ignore the event
  15622. if you want.
  15623. */
  15624. virtual void userTriedToCloseWindow();
  15625. /** Called for a desktop component which has just been minimised or un-minimised.
  15626. This will only be called for components on the desktop.
  15627. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15628. */
  15629. virtual void minimisationStateChanged (bool isNowMinimised);
  15630. /** Brings the component to the front of its siblings.
  15631. If some of the component's siblings have had their 'always-on-top' flag set,
  15632. then they will still be kept in front of this one (unless of course this
  15633. one is also 'always-on-top').
  15634. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15635. to the component (see grabKeyboardFocus() for more details)
  15636. @see toBack, toBehind, setAlwaysOnTop
  15637. */
  15638. void toFront (const bool shouldAlsoGainFocus);
  15639. /** Changes this component's z-order to be at the back of all its siblings.
  15640. If the component is set to be 'always-on-top', it will only be moved to the
  15641. back of the other other 'always-on-top' components.
  15642. @see toFront, toBehind, setAlwaysOnTop
  15643. */
  15644. void toBack();
  15645. /** Changes this component's z-order so that it's just behind another component.
  15646. @see toFront, toBack
  15647. */
  15648. void toBehind (Component* const other);
  15649. /** Sets whether the component should always be kept at the front of its siblings.
  15650. @see isAlwaysOnTop
  15651. */
  15652. void setAlwaysOnTop (const bool shouldStayOnTop);
  15653. /** Returns true if this component is set to always stay in front of its siblings.
  15654. @see setAlwaysOnTop
  15655. */
  15656. bool isAlwaysOnTop() const throw();
  15657. /** Returns the x co-ordinate of the component's left edge.
  15658. This is a distance in pixels from the left edge of the component's parent.
  15659. @see getScreenX
  15660. */
  15661. inline int getX() const throw() { return bounds_.getX(); }
  15662. /** Returns the y co-ordinate of the top of this component.
  15663. This is a distance in pixels from the top edge of the component's parent.
  15664. @see getScreenY
  15665. */
  15666. inline int getY() const throw() { return bounds_.getY(); }
  15667. /** Returns the component's width in pixels. */
  15668. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15669. /** Returns the component's height in pixels. */
  15670. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15671. /** Returns the x co-ordinate of the component's right-hand edge.
  15672. This is a distance in pixels from the left edge of the component's parent.
  15673. */
  15674. int getRight() const throw() { return bounds_.getRight(); }
  15675. /** Returns the y co-ordinate of the bottom edge of this component.
  15676. This is a distance in pixels from the top edge of the component's parent.
  15677. */
  15678. int getBottom() const throw() { return bounds_.getBottom(); }
  15679. /** Returns this component's bounding box.
  15680. The rectangle returned is relative to the top-left of the component's parent.
  15681. */
  15682. const Rectangle& getBounds() const throw() { return bounds_; }
  15683. /** Returns the region of this component that's not obscured by other, opaque components.
  15684. The RectangleList that is returned represents the area of this component
  15685. which isn't covered by opaque child components.
  15686. If includeSiblings is true, it will also take into account any siblings
  15687. that may be overlapping the component.
  15688. */
  15689. void getVisibleArea (RectangleList& result,
  15690. const bool includeSiblings) const;
  15691. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15692. @see getX, relativePositionToGlobal
  15693. */
  15694. int getScreenX() const throw();
  15695. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15696. @see getY, relativePositionToGlobal
  15697. */
  15698. int getScreenY() const throw();
  15699. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15700. @see globalPositionToRelative, relativePositionToOtherComponent
  15701. */
  15702. void relativePositionToGlobal (int& x, int& y) const throw();
  15703. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15704. @see relativePositionToGlobal, relativePositionToOtherComponent
  15705. */
  15706. void globalPositionToRelative (int& x, int& y) const throw();
  15707. /** Converts a position relative to this component's top-left into a position
  15708. relative to another component's top-left.
  15709. @see relativePositionToGlobal, globalPositionToRelative
  15710. */
  15711. void relativePositionToOtherComponent (const Component* const targetComponent,
  15712. int& x, int& y) const throw();
  15713. /** Moves the component to a new position.
  15714. Changes the component's top-left position (without changing its size).
  15715. The position is relative to the top-left of the component's parent.
  15716. If the component actually moves, this method will make a synchronous call to moved().
  15717. @see setBounds, ComponentListener::componentMovedOrResized
  15718. */
  15719. void setTopLeftPosition (const int x, const int y);
  15720. /** Moves the component to a new position.
  15721. Changes the position of the component's top-right corner (keeping it the same size).
  15722. The position is relative to the top-left of the component's parent.
  15723. If the component actually moves, this method will make a synchronous call to moved().
  15724. */
  15725. void setTopRightPosition (const int x, const int y);
  15726. /** Changes the size of the component.
  15727. A synchronous call to resized() will be occur if the size actually changes.
  15728. */
  15729. void setSize (const int newWidth, const int newHeight);
  15730. /** Changes the component's position and size.
  15731. The co-ordinates are relative to the top-left of the component's parent, or relative
  15732. to the origin of the screen is the component is on the desktop.
  15733. If this method changes the component's top-left position, it will make a synchronous
  15734. call to moved(). If it changes the size, it will also make a call to resized().
  15735. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15736. */
  15737. void setBounds (int x, int y, int width, int height);
  15738. /** Changes the component's position and size.
  15739. @see setBounds
  15740. */
  15741. void setBounds (const Rectangle& newBounds);
  15742. /** Changes the component's position and size in terms of fractions of its parent's size.
  15743. The values are factors of the parent's size, so for example
  15744. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15745. width and height of the parent, with its top-left position 20% of
  15746. the way across and down the parent.
  15747. */
  15748. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15749. const float proportionalWidth, const float proportionalHeight);
  15750. /** Changes the component's position and size based on the amount of space to leave around it.
  15751. This will position the component within its parent, leaving the specified number of
  15752. pixels around each edge.
  15753. */
  15754. void setBoundsInset (const BorderSize& borders);
  15755. /** Positions the component within a given rectangle, keeping its proportions
  15756. unchanged.
  15757. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15758. rectangle as possible without changing its aspect ratio (the component's
  15759. current size is used to determine its aspect ratio, so a zero-size component
  15760. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15761. too big to fit inside the rectangle.
  15762. It will then be positioned within the rectangle according to the justification flags
  15763. specified.
  15764. */
  15765. void setBoundsToFit (int x, int y, int width, int height,
  15766. const Justification& justification,
  15767. const bool onlyReduceInSize);
  15768. /** Changes the position of the component's centre.
  15769. Leaves the component's size unchanged, but sets the position of its centre
  15770. relative to its parent's top-left.
  15771. */
  15772. void setCentrePosition (const int x, const int y);
  15773. /** Changes the position of the component's centre.
  15774. Leaves the position unchanged, but positions its centre relative to its
  15775. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15776. its parent.
  15777. */
  15778. void setCentreRelative (const float x, const float y);
  15779. /** Changes the component's size and centres it within its parent.
  15780. After changing the size, the component will be moved so that it's
  15781. centred within its parent.
  15782. */
  15783. void centreWithSize (const int width, const int height);
  15784. /** Returns a proportion of the component's width.
  15785. This is a handy equivalent of (getWidth() * proportion).
  15786. */
  15787. int proportionOfWidth (const float proportion) const throw();
  15788. /** Returns a proportion of the component's height.
  15789. This is a handy equivalent of (getHeight() * proportion).
  15790. */
  15791. int proportionOfHeight (const float proportion) const throw();
  15792. /** Returns the width of the component's parent.
  15793. If the component has no parent (i.e. if it's on the desktop), this will return
  15794. the width of the screen.
  15795. */
  15796. int getParentWidth() const throw();
  15797. /** Returns the height of the component's parent.
  15798. If the component has no parent (i.e. if it's on the desktop), this will return
  15799. the height of the screen.
  15800. */
  15801. int getParentHeight() const throw();
  15802. /** Returns the screen co-ordinates of the monitor that contains this component.
  15803. If there's only one monitor, this will return its size - if there are multiple
  15804. monitors, it will return the area of the monitor that contains the component's
  15805. centre.
  15806. */
  15807. const Rectangle getParentMonitorArea() const throw();
  15808. /** Returns the number of child components that this component contains.
  15809. @see getChildComponent, getIndexOfChildComponent
  15810. */
  15811. int getNumChildComponents() const throw();
  15812. /** Returns one of this component's child components, by it index.
  15813. The component with index 0 is at the back of the z-order, the one at the
  15814. front will have index (getNumChildComponents() - 1).
  15815. If the index is out-of-range, this will return a null pointer.
  15816. @see getNumChildComponents, getIndexOfChildComponent
  15817. */
  15818. Component* getChildComponent (const int index) const throw();
  15819. /** Returns the index of this component in the list of child components.
  15820. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15821. values are further towards the front.
  15822. Returns -1 if the component passed-in is not a child of this component.
  15823. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15824. */
  15825. int getIndexOfChildComponent (const Component* const child) const throw();
  15826. /** Adds a child component to this one.
  15827. @param child the new component to add. If the component passed-in is already
  15828. the child of another component, it'll first be removed from that.
  15829. @param zOrder The index in the child-list at which this component should be inserted.
  15830. A value of -1 will insert it in front of the others, 0 is the back.
  15831. @see removeChildComponent, addAndMakeVisible, getChild,
  15832. ComponentListener::componentChildrenChanged
  15833. */
  15834. void addChildComponent (Component* const child,
  15835. int zOrder = -1);
  15836. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15837. Quite a useful function, this is just the same as calling addChildComponent()
  15838. followed by setVisible (true) on the child.
  15839. */
  15840. void addAndMakeVisible (Component* const child,
  15841. int zOrder = -1);
  15842. /** Removes one of this component's child-components.
  15843. If the child passed-in isn't actually a child of this component (either because
  15844. it's invalid or is the child of a different parent), then nothing is done.
  15845. Note that removing a child will not delete it!
  15846. @see addChildComponent, ComponentListener::componentChildrenChanged
  15847. */
  15848. void removeChildComponent (Component* const childToRemove);
  15849. /** Removes one of this component's child-components by index.
  15850. This will return a pointer to the component that was removed, or null if
  15851. the index was out-of-range.
  15852. Note that removing a child will not delete it!
  15853. @see addChildComponent, ComponentListener::componentChildrenChanged
  15854. */
  15855. Component* removeChildComponent (const int childIndexToRemove);
  15856. /** Removes all this component's children.
  15857. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  15858. */
  15859. void removeAllChildren();
  15860. /** Removes all this component's children, and deletes them.
  15861. @see removeAllChildren
  15862. */
  15863. void deleteAllChildren();
  15864. /** Returns the component which this component is inside.
  15865. If this is the highest-level component or hasn't yet been added to
  15866. a parent, this will return null.
  15867. */
  15868. Component* getParentComponent() const throw() { return parentComponent_; }
  15869. /** Searches the parent components for a component of a specified class.
  15870. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  15871. component that can be dynamically cast to a MyComp, or will return 0 if none
  15872. of the parents are suitable.
  15873. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  15874. */
  15875. template <class TargetClass>
  15876. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  15877. {
  15878. (void) dummyParameter;
  15879. Component* p = parentComponent_;
  15880. while (p != 0)
  15881. {
  15882. TargetClass* target = dynamic_cast <TargetClass*> (p);
  15883. if (target != 0)
  15884. return target;
  15885. p = p->parentComponent_;
  15886. }
  15887. return 0;
  15888. }
  15889. /** Returns the highest-level component which contains this one or its parents.
  15890. This will search upwards in the parent-hierarchy from this component, until it
  15891. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  15892. not yet added to a parent), and will return that.
  15893. */
  15894. Component* getTopLevelComponent() const throw();
  15895. /** Checks whether a component is anywhere inside this component or its children.
  15896. This will recursively check through this components children to see if the
  15897. given component is anywhere inside.
  15898. */
  15899. bool isParentOf (const Component* possibleChild) const throw();
  15900. /** Called to indicate that the component's parents have changed.
  15901. When a component is added or removed from its parent, this method will
  15902. be called on all of its children (recursively - so all children of its
  15903. children will also be called as well).
  15904. Subclasses can override this if they need to react to this in some way.
  15905. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  15906. */
  15907. virtual void parentHierarchyChanged();
  15908. /** Subclasses can use this callback to be told when children are added or removed.
  15909. @see parentHierarchyChanged
  15910. */
  15911. virtual void childrenChanged();
  15912. /** Tests whether a given point inside the component.
  15913. Overriding this method allows you to create components which only intercept
  15914. mouse-clicks within a user-defined area.
  15915. This is called to find out whether a particular x, y co-ordinate is
  15916. considered to be inside the component or not, and is used by methods such
  15917. as contains() and getComponentAt() to work out which component
  15918. the mouse is clicked on.
  15919. Components with custom shapes will probably want to override it to perform
  15920. some more complex hit-testing.
  15921. The default implementation of this method returns either true or false,
  15922. depending on the value that was set by calling setInterceptsMouseClicks() (true
  15923. is the default return value).
  15924. Note that the hit-test region is not related to the opacity with which
  15925. areas of a component are painted.
  15926. Applications should never call hitTest() directly - instead use the
  15927. contains() method, because this will also test for occlusion by the
  15928. component's parent.
  15929. Note that for components on the desktop, this method will be ignored, because it's
  15930. not always possible to implement this behaviour on all platforms.
  15931. @param x the x co-ordinate to test, relative to the left hand edge of this
  15932. component. This value is guaranteed to be greater than or equal to
  15933. zero, and less than the component's width
  15934. @param y the y co-ordinate to test, relative to the top edge of this
  15935. component. This value is guaranteed to be greater than or equal to
  15936. zero, and less than the component's height
  15937. @returns true if the click is considered to be inside the component
  15938. @see setInterceptsMouseClicks, contains
  15939. */
  15940. virtual bool hitTest (int x, int y);
  15941. /** Changes the default return value for the hitTest() method.
  15942. Setting this to false is an easy way to make a component pass its mouse-clicks
  15943. through to the components behind it.
  15944. When a component is created, the default setting for this is true.
  15945. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  15946. return false (or true for child components if allowClicksOnChildComponents
  15947. is true)
  15948. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  15949. components can be clicked on as normal but clicks on this component pass
  15950. straight through; if this is false and allowClicksOnThisComponent
  15951. is false, then neither this component nor any child components can
  15952. be clicked on
  15953. @see hitTest, getInterceptsMouseClicks
  15954. */
  15955. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  15956. const bool allowClicksOnChildComponents) throw();
  15957. /** Retrieves the current state of the mouse-click interception flags.
  15958. On return, the two parameters are set to the state used in the last call to
  15959. setInterceptsMouseClicks().
  15960. @see setInterceptsMouseClicks
  15961. */
  15962. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  15963. bool& allowsClicksOnChildComponents) const throw();
  15964. /** Returns true if a given point lies within this component or one of its children.
  15965. Never override this method! Use hitTest to create custom hit regions.
  15966. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15967. @param y the y co-ordinate to test, relative to this component's top edge.
  15968. @returns true if the point is within the component's hit-test area, but only if
  15969. that part of the component isn't clipped by its parent component. Note
  15970. that this won't take into account any overlapping sibling components
  15971. which might be in the way - for that, see reallyContains()
  15972. @see hitTest, reallyContains, getComponentAt
  15973. */
  15974. virtual bool contains (int x, int y);
  15975. /** Returns true if a given point lies in this component, taking any overlapping
  15976. siblings into account.
  15977. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15978. @param y the y co-ordinate to test, relative to this component's top edge.
  15979. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  15980. component, this determines the value that will
  15981. be returned.
  15982. @see contains, getComponentAt
  15983. */
  15984. bool reallyContains (int x, int y,
  15985. const bool returnTrueIfWithinAChild);
  15986. /** Returns the component at a certain point within this one.
  15987. @param x the x co-ordinate to test, relative to this component's left hand edge.
  15988. @param y the y co-ordinate to test, relative to this component's top edge.
  15989. @returns the component that is at this position - which may be 0, this component,
  15990. or one of its children. Note that overlapping siblings that might actually
  15991. be in the way are not taken into account by this method - to account for these,
  15992. instead call getComponentAt on the top-level parent of this component.
  15993. @see hitTest, contains, reallyContains
  15994. */
  15995. Component* getComponentAt (const int x, const int y);
  15996. /** Marks the whole component as needing to be redrawn.
  15997. Calling this will not do any repainting immediately, but will mark the component
  15998. as 'dirty'. At some point in the near future the operating system will send a paint
  15999. message, which will redraw all the dirty regions of all components.
  16000. There's no guarantee about how soon after calling repaint() the redraw will actually
  16001. happen, and other queued events may be delivered before a redraw is done.
  16002. If the setBufferedToImage() method has been used to cause this component
  16003. to use a buffer, the repaint() call will invalidate the component's buffer.
  16004. To redraw just a subsection of the component rather than the whole thing,
  16005. use the repaint (int, int, int, int) method.
  16006. @see paint
  16007. */
  16008. void repaint() throw();
  16009. /** Marks a subsection of this component as needing to be redrawn.
  16010. Calling this will not do any repainting immediately, but will mark the given region
  16011. of the component as 'dirty'. At some point in the near future the operating system
  16012. will send a paint message, which will redraw all the dirty regions of all components.
  16013. There's no guarantee about how soon after calling repaint() the redraw will actually
  16014. happen, and other queued events may be delivered before a redraw is done.
  16015. The region that is passed in will be clipped to keep it within the bounds of this
  16016. component.
  16017. @see repaint()
  16018. */
  16019. void repaint (const int x, const int y,
  16020. const int width, const int height) throw();
  16021. /** Makes the component use an internal buffer to optimise its redrawing.
  16022. Setting this flag to true will cause the component to allocate an
  16023. internal buffer into which it paints itself, so that when asked to
  16024. redraw itself, it can use this buffer rather than actually calling the
  16025. paint() method.
  16026. The buffer is kept until the repaint() method is called directly on
  16027. this component (or until it is resized), when the image is invalidated
  16028. and then redrawn the next time the component is painted.
  16029. Note that only the drawing that happens within the component's paint()
  16030. method is drawn into the buffer, it's child components are not buffered, and
  16031. nor is the paintOverChildren() method.
  16032. @see repaint, paint, createComponentSnapshot
  16033. */
  16034. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16035. /** Generates a snapshot of part of this component.
  16036. This will return a new Image, the size of the rectangle specified,
  16037. containing a snapshot of the specified area of the component and all
  16038. its children.
  16039. The image may or may not have an alpha-channel, depending on whether the
  16040. image is opaque or not.
  16041. If the clipImageToComponentBounds parameter is true and the area is greater than
  16042. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16043. then parts of the component beyond its bounds can be drawn.
  16044. The caller is responsible for deleting the image that is returned.
  16045. @see paintEntireComponent
  16046. */
  16047. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16048. const bool clipImageToComponentBounds = true);
  16049. /** Draws this component and all its subcomponents onto the specified graphics
  16050. context.
  16051. You should very rarely have to use this method, it's simply there in case you need
  16052. to draw a component with a custom graphics context for some reason, e.g. for
  16053. creating a snapshot of the component.
  16054. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16055. on its children in order to render the entire tree.
  16056. The graphics context may be left in an undefined state after this method returns,
  16057. so you may need to reset it if you're going to use it again.
  16058. */
  16059. void paintEntireComponent (Graphics& context);
  16060. /** Adds an effect filter to alter the component's appearance.
  16061. When a component has an effect filter set, then this is applied to the
  16062. results of its paint() method. There are a few preset effects, such as
  16063. a drop-shadow or glow, but they can be user-defined as well.
  16064. The effect that is passed in will not be deleted by the component - the
  16065. caller must take care of deleting it.
  16066. To remove an effect from a component, pass a null pointer in as the parameter.
  16067. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16068. */
  16069. void setComponentEffect (ImageEffectFilter* const newEffect);
  16070. /** Returns the current component effect.
  16071. @see setComponentEffect
  16072. */
  16073. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16074. /** Finds the appropriate look-and-feel to use for this component.
  16075. If the component hasn't had a look-and-feel explicitly set, this will
  16076. return the parent's look-and-feel, or just the default one if there's no
  16077. parent.
  16078. @see setLookAndFeel, lookAndFeelChanged
  16079. */
  16080. LookAndFeel& getLookAndFeel() const throw();
  16081. /** Sets the look and feel to use for this component.
  16082. This will also change the look and feel for any child components that haven't
  16083. had their look set explicitly.
  16084. The object passed in will not be deleted by the component, so it's the caller's
  16085. responsibility to manage it. It may be used at any time until this component
  16086. has been deleted.
  16087. Calling this method will also invoke the sendLookAndFeelChange() method.
  16088. @see getLookAndFeel, lookAndFeelChanged
  16089. */
  16090. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16091. /** Called to let the component react to a change in the look-and-feel setting.
  16092. When the look-and-feel is changed for a component, this will be called in
  16093. all its child components, recursively.
  16094. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16095. an application uses a LookAndFeel class that might have changed internally.
  16096. @see sendLookAndFeelChange, getLookAndFeel
  16097. */
  16098. virtual void lookAndFeelChanged();
  16099. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16100. This will recurse through the children and their children, calling lookAndFeelChanged()
  16101. on them all.
  16102. @see lookAndFeelChanged
  16103. */
  16104. void sendLookAndFeelChange();
  16105. /** Indicates whether any parts of the component might be transparent.
  16106. Components that always paint all of their contents with solid colour and
  16107. thus completely cover any components behind them should use this method
  16108. to tell the repaint system that they are opaque.
  16109. This information is used to optimise drawing, because it means that
  16110. objects underneath opaque windows don't need to be painted.
  16111. By default, components are considered transparent, unless this is used to
  16112. make it otherwise.
  16113. @see isOpaque, getVisibleArea
  16114. */
  16115. void setOpaque (const bool shouldBeOpaque) throw();
  16116. /** Returns true if no parts of this component are transparent.
  16117. @returns the value that was set by setOpaque, (the default being false)
  16118. @see setOpaque
  16119. */
  16120. bool isOpaque() const throw();
  16121. /** Indicates whether the component should be brought to the front when clicked.
  16122. Setting this flag to true will cause the component to be brought to the front
  16123. when the mouse is clicked somewhere inside it or its child components.
  16124. Note that a top-level desktop window might still be brought to the front by the
  16125. operating system when it's clicked, depending on how the OS works.
  16126. By default this is set to false.
  16127. @see setMouseClickGrabsKeyboardFocus
  16128. */
  16129. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16130. /** Indicates whether the component should be brought to the front when clicked-on.
  16131. @see setBroughtToFrontOnMouseClick
  16132. */
  16133. bool isBroughtToFrontOnMouseClick() const throw();
  16134. // Keyboard focus methods
  16135. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16136. By default components aren't actually interested in gaining the
  16137. focus, but this method can be used to turn this on.
  16138. See the grabKeyboardFocus() method for details about the way a component
  16139. is chosen to receive the focus.
  16140. @see grabKeyboardFocus, getWantsKeyboardFocus
  16141. */
  16142. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16143. /** Returns true if the component is interested in getting keyboard focus.
  16144. This returns the flag set by setWantsKeyboardFocus(). The default
  16145. setting is false.
  16146. @see setWantsKeyboardFocus
  16147. */
  16148. bool getWantsKeyboardFocus() const throw();
  16149. /** Chooses whether a click on this component automatically grabs the focus.
  16150. By default this is set to true, but you might want a component which can
  16151. be focused, but where you don't want the user to be able to affect it directly
  16152. by clicking.
  16153. */
  16154. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16155. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16156. See setMouseClickGrabsKeyboardFocus() for more info.
  16157. */
  16158. bool getMouseClickGrabsKeyboardFocus() const throw();
  16159. /** Tries to give keyboard focus to this component.
  16160. When the user clicks on a component or its grabKeyboardFocus()
  16161. method is called, the following procedure is used to work out which
  16162. component should get it:
  16163. - if the component that was clicked on actually wants focus (as indicated
  16164. by calling getWantsKeyboardFocus), it gets it.
  16165. - if the component itself doesn't want focus, it will try to pass it
  16166. on to whichever of its children is the default component, as determined by
  16167. KeyboardFocusTraverser::getDefaultComponent()
  16168. - if none of its children want focus at all, it will pass it up to its
  16169. parent instead, unless it's a top-level component without a parent,
  16170. in which case it just takes the focus itself.
  16171. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16172. getCurrentlyFocusedComponent, focusGained, focusLost,
  16173. keyPressed, keyStateChanged
  16174. */
  16175. void grabKeyboardFocus();
  16176. /** Returns true if this component currently has the keyboard focus.
  16177. @param trueIfChildIsFocused if this is true, then the method returns true if
  16178. either this component or any of its children (recursively)
  16179. have the focus. If false, the method only returns true if
  16180. this component has the focus.
  16181. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16182. focusGained, focusLost
  16183. */
  16184. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16185. /** Returns the component that currently has the keyboard focus.
  16186. @returns the focused component, or null if nothing is focused.
  16187. */
  16188. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16189. /** Tries to move the keyboard focus to one of this component's siblings.
  16190. This will try to move focus to either the next or previous component. (This
  16191. is the method that is used when shifting focus by pressing the tab key).
  16192. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16193. @param moveToNext if true, the focus will move forwards; if false, it will
  16194. move backwards
  16195. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16196. */
  16197. void moveKeyboardFocusToSibling (const bool moveToNext);
  16198. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16199. which focus should be passed from this component.
  16200. The default implementation of this method will return a default
  16201. KeyboardFocusTraverser if this component is a focus container (as determined
  16202. by the setFocusContainer() method). If the component isn't a focus
  16203. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16204. If you overrride this to return a custom KeyboardFocusTraverser, then
  16205. this component and all its sub-components will use the new object to
  16206. make their focusing decisions.
  16207. The method should return a new object, which the caller is required to
  16208. delete when no longer needed.
  16209. */
  16210. virtual KeyboardFocusTraverser* createFocusTraverser();
  16211. /** Returns the focus order of this component, if one has been specified.
  16212. By default components don't have a focus order - in that case, this
  16213. will return 0. Lower numbers indicate that the component will be
  16214. earlier in the focus traversal order.
  16215. To change the order, call setExplicitFocusOrder().
  16216. The focus order may be used by the KeyboardFocusTraverser class as part of
  16217. its algorithm for deciding the order in which components should be traversed.
  16218. See the KeyboardFocusTraverser class for more details on this.
  16219. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16220. */
  16221. int getExplicitFocusOrder() const throw();
  16222. /** Sets the index used in determining the order in which focusable components
  16223. should be traversed.
  16224. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16225. that traversal should use other factors, like the component's position.
  16226. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16227. */
  16228. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16229. /** Indicates whether this component is a parent for components that can have
  16230. their focus traversed.
  16231. This flag is used by the default implementation of the createFocusTraverser()
  16232. method, which uses the flag to find the first parent component (of the currently
  16233. focused one) which wants to be a focus container.
  16234. So using this method to set the flag to 'true' causes this component to
  16235. act as the top level within which focus is passed around.
  16236. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16237. */
  16238. void setFocusContainer (const bool isFocusContainer) throw();
  16239. /** Returns true if this component has been marked as a focus container.
  16240. See setFocusContainer() for more details.
  16241. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16242. */
  16243. bool isFocusContainer() const throw();
  16244. /** Returns true if the component (and all its parents) are enabled.
  16245. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16246. what difference this makes to the component depends on the type. E.g. buttons
  16247. and sliders will choose to draw themselves differently, etc.
  16248. Note that if one of this component's parents is disabled, this will always
  16249. return false, even if this component itself is enabled.
  16250. @see setEnabled, enablementChanged
  16251. */
  16252. bool isEnabled() const throw();
  16253. /** Enables or disables this component.
  16254. Disabling a component will also cause all of its child components to become
  16255. disabled.
  16256. Similarly, enabling a component which is inside a disabled parent
  16257. component won't make any difference until the parent is re-enabled.
  16258. @see isEnabled, enablementChanged
  16259. */
  16260. void setEnabled (const bool shouldBeEnabled);
  16261. /** Callback to indicate that this component has been enabled or disabled.
  16262. This can be triggered by one of the component's parent components
  16263. being enabled or disabled, as well as changes to the component itself.
  16264. The default implementation of this method does nothing; your class may
  16265. wish to repaint itself or something when this happens.
  16266. @see setEnabled, isEnabled
  16267. */
  16268. virtual void enablementChanged();
  16269. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16270. Note that the cursor set by this method can be overridden by the getMouseCursor
  16271. method.
  16272. @see MouseCursor
  16273. */
  16274. void setMouseCursor (const MouseCursor& cursorType) throw();
  16275. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16276. The default implementation will return the cursor that was set by setCursor()
  16277. but can be overridden for more specialised purposes, e.g. returning different
  16278. cursors depending on the mouse position.
  16279. @see MouseCursor
  16280. */
  16281. virtual const MouseCursor getMouseCursor();
  16282. /** Forces the current mouse cursor to be updated.
  16283. If you're overriding the getMouseCursor() method to control which cursor is
  16284. displayed, then this will only be checked each time the user moves the mouse. So
  16285. if you want to force the system to check that the cursor being displayed is
  16286. up-to-date (even if the mouse is just sitting there), call this method.
  16287. This isn't needed if you're only using setMouseCursor().
  16288. */
  16289. void updateMouseCursor() const throw();
  16290. /** Components can override this method to draw their content.
  16291. The paint() method gets called when a region of a component needs redrawing,
  16292. either because the component's repaint() method has been called, or because
  16293. something has happened on the screen that means a section of a window needs
  16294. to be redrawn.
  16295. Any child components will draw themselves over whatever this method draws. If
  16296. you need to paint over the top of your child components, you can also implement
  16297. the paintOverChildren() method to do this.
  16298. If you want to cause a component to redraw itself, this is done asynchronously -
  16299. calling the repaint() method marks a region of the component as "dirty", and the
  16300. paint() method will automatically be called sometime later, by the message thread,
  16301. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16302. you never redraw something synchronously.
  16303. You should never need to call this method directly - to take a snapshot of the
  16304. component you could use createComponentSnapshot() or paintEntireComponent().
  16305. @param g the graphics context that must be used to do the drawing operations.
  16306. @see repaint, paintOverChildren, Graphics
  16307. */
  16308. virtual void paint (Graphics& g);
  16309. /** Components can override this method to draw over the top of their children.
  16310. For most drawing operations, it's better to use the normal paint() method,
  16311. but if you need to overlay something on top of the children, this can be
  16312. used.
  16313. @see paint, Graphics
  16314. */
  16315. virtual void paintOverChildren (Graphics& g);
  16316. /** Called when the mouse moves inside this component.
  16317. If the mouse button isn't pressed and the mouse moves over a component,
  16318. this will be called to let the component react to this.
  16319. A component will always get a mouseEnter callback before a mouseMove.
  16320. @param e details about the position and status of the mouse event
  16321. @see mouseEnter, mouseExit, mouseDrag, contains
  16322. */
  16323. virtual void mouseMove (const MouseEvent& e);
  16324. /** Called when the mouse first enters this component.
  16325. If the mouse button isn't pressed and the mouse moves into a component,
  16326. this will be called to let the component react to this.
  16327. When the mouse button is pressed and held down while being moved in
  16328. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16329. mouseDrag messages are sent to the component that the mouse was originally
  16330. clicked on, until the button is released.
  16331. If you're writing a component that needs to repaint itself when the mouse
  16332. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16333. method.
  16334. @param e details about the position and status of the mouse event
  16335. @see mouseExit, mouseDrag, mouseMove, contains
  16336. */
  16337. virtual void mouseEnter (const MouseEvent& e);
  16338. /** Called when the mouse moves out of this component.
  16339. This will be called when the mouse moves off the edge of this
  16340. component.
  16341. If the mouse button was pressed, and it was then dragged off the
  16342. edge of the component and released, then this callback will happen
  16343. when the button is released, after the mouseUp callback.
  16344. If you're writing a component that needs to repaint itself when the mouse
  16345. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16346. method.
  16347. @param e details about the position and status of the mouse event
  16348. @see mouseEnter, mouseDrag, mouseMove, contains
  16349. */
  16350. virtual void mouseExit (const MouseEvent& e);
  16351. /** Called when a mouse button is pressed while it's over this component.
  16352. The MouseEvent object passed in contains lots of methods for finding out
  16353. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16354. were held down at the time.
  16355. Once a button is held down, the mouseDrag method will be called when the
  16356. mouse moves, until the button is released.
  16357. @param e details about the position and status of the mouse event
  16358. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16359. */
  16360. virtual void mouseDown (const MouseEvent& e);
  16361. /** Called when the mouse is moved while a button is held down.
  16362. When a mouse button is pressed inside a component, that component
  16363. receives mouseDrag callbacks each time the mouse moves, even if the
  16364. mouse strays outside the component's bounds.
  16365. If you want to be able to drag things off the edge of a component
  16366. and have the component scroll when you get to the edges, the
  16367. beginDragAutoRepeat() method might be useful.
  16368. @param e details about the position and status of the mouse event
  16369. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16370. */
  16371. virtual void mouseDrag (const MouseEvent& e);
  16372. /** Called when a mouse button is released.
  16373. A mouseUp callback is sent to the component in which a button was pressed
  16374. even if the mouse is actually over a different component when the
  16375. button is released.
  16376. The MouseEvent object passed in contains lots of methods for finding out
  16377. which buttons were down just before they were released.
  16378. @param e details about the position and status of the mouse event
  16379. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16380. */
  16381. virtual void mouseUp (const MouseEvent& e);
  16382. /** Called when a mouse button has been double-clicked in this component.
  16383. The MouseEvent object passed in contains lots of methods for finding out
  16384. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16385. were held down at the time.
  16386. For altering the time limit used to detect double-clicks,
  16387. see MouseEvent::setDoubleClickTimeout.
  16388. @param e details about the position and status of the mouse event
  16389. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16390. MouseEvent::getDoubleClickTimeout
  16391. */
  16392. virtual void mouseDoubleClick (const MouseEvent& e);
  16393. /** Called when the mouse-wheel is moved.
  16394. This callback is sent to the component that the mouse is over when the
  16395. wheel is moved.
  16396. If not overridden, the component will forward this message to its parent, so
  16397. that parent components can collect mouse-wheel messages that happen to
  16398. child components which aren't interested in them.
  16399. @param e details about the position and status of the mouse event
  16400. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16401. value means the wheel has been pushed to the right, negative means it
  16402. was pushed to the left
  16403. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16404. value means the wheel has been pushed upwards, negative means it
  16405. was pushed downwards
  16406. */
  16407. virtual void mouseWheelMove (const MouseEvent& e,
  16408. float wheelIncrementX,
  16409. float wheelIncrementY);
  16410. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16411. next mouse-drag operation.
  16412. This allows you to make sure that mouseDrag() events sent continuously, even
  16413. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16414. components when the mouse is near an edge.
  16415. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16416. minimum interval between consecutive mouse drag callbacks. The callbacks
  16417. will continue until the mouse is released, and then the interval will be reset,
  16418. so you need to make sure it's called every time you begin a drag event. If it
  16419. is called when the mouse isn't actually being pressed, it will apply to the next
  16420. mouse-drag operation that happens.
  16421. Passing an interval of 0 or less will cancel the auto-repeat.
  16422. @see mouseDrag
  16423. */
  16424. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16425. /** Causes automatic repaints when the mouse enters or exits this component.
  16426. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16427. on the component, it will trigger a repaint.
  16428. This is handy for things like buttons that need to draw themselves differently when
  16429. the mouse moves over them, and it avoids having to override all the different mouse
  16430. callbacks and call repaint().
  16431. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16432. */
  16433. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16434. /** Registers a listener to be told when mouse events occur in this component.
  16435. If you need to get informed about mouse events in a component but can't or
  16436. don't want to override its methods, you can attach any number of listeners
  16437. to the component, and these will get told about the events in addition to
  16438. the component's own callbacks being called.
  16439. Note that a MouseListener can also be attached to more than one component.
  16440. @param newListener the listener to register
  16441. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16442. for events that happen to any child component
  16443. within this component, including deeply-nested
  16444. child components. If false, it will only be
  16445. told about events that this component handles.
  16446. @see MouseListener, removeMouseListener
  16447. */
  16448. void addMouseListener (MouseListener* const newListener,
  16449. const bool wantsEventsForAllNestedChildComponents) throw();
  16450. /** Deregisters a mouse listener.
  16451. @see addMouseListener, MouseListener
  16452. */
  16453. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16454. /** Adds a listener that wants to hear about keypresses that this component receives.
  16455. The listeners that are registered with a component are called by its keyPressed() or
  16456. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16457. If you add an object as a key listener, be careful to remove it when the object
  16458. is deleted, or the component will be left with a dangling pointer.
  16459. @see keyPressed, keyStateChanged, removeKeyListener
  16460. */
  16461. void addKeyListener (KeyListener* const newListener) throw();
  16462. /** Removes a previously-registered key listener.
  16463. @see addKeyListener
  16464. */
  16465. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16466. /** Called when a key is pressed.
  16467. When a key is pressed, the component that has the keyboard focus will have this
  16468. method called. Remember that a component will only be given the focus if its
  16469. setWantsKeyboardFocus() method has been used to enable this.
  16470. If your implementation returns true, the event will be consumed and not passed
  16471. on to any other listeners. If it returns false, the key will be passed to any
  16472. KeyListeners that have been registered with this component. As soon as one of these
  16473. returns true, the process will stop, but if they all return false, the event will
  16474. be passed upwards to this component's parent, and so on.
  16475. The default implementation of this method does nothing and returns false.
  16476. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16477. */
  16478. virtual bool keyPressed (const KeyPress& key);
  16479. /** Called when a key is pressed or released.
  16480. Whenever a key on the keyboard is pressed or released (including modifier keys
  16481. like shift and ctrl), this method will be called on the component that currently
  16482. has the keyboard focus. Remember that a component will only be given the focus if
  16483. its setWantsKeyboardFocus() method has been used to enable this.
  16484. If your implementation returns true, the event will be consumed and not passed
  16485. on to any other listeners. If it returns false, then any KeyListeners that have
  16486. been registered with this component will have their keyStateChanged methods called.
  16487. As soon as one of these returns true, the process will stop, but if they all return
  16488. false, the event will be passed upwards to this component's parent, and so on.
  16489. The default implementation of this method does nothing and returns false.
  16490. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16491. method.
  16492. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16493. */
  16494. virtual bool keyStateChanged();
  16495. /** Called when a modifier key is pressed or released.
  16496. Whenever the shift, control, alt or command keys are pressed or released,
  16497. this method will be called on the component that currently has the keyboard focus.
  16498. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16499. method has been used to enable this.
  16500. The default implementation of this method actually calls its parent's modifierKeysChanged
  16501. method, so that focused components which aren't interested in this will give their
  16502. parents a chance to act on the event instead.
  16503. @see keyStateChanged, ModifierKeys
  16504. */
  16505. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16506. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16507. enum FocusChangeType
  16508. {
  16509. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16510. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16511. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16512. };
  16513. /** Called to indicate that this component has just acquired the keyboard focus.
  16514. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16515. */
  16516. virtual void focusGained (FocusChangeType cause);
  16517. /** Called to indicate that this component has just lost the keyboard focus.
  16518. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16519. */
  16520. virtual void focusLost (FocusChangeType cause);
  16521. /** Called to indicate that one of this component's children has been focused or unfocused.
  16522. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16523. changed. It happens when focus moves from one of this component's children (at any depth)
  16524. to a component that isn't contained in this one, (or vice-versa).
  16525. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16526. */
  16527. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16528. /** Returns true if the mouse is currently over this component.
  16529. If the mouse isn't over the component, this will return false, even if the
  16530. mouse is currently being dragged - so you can use this in your mouseDrag
  16531. method to find out whether it's really over the component or not.
  16532. Note that when the mouse button is being held down, then the only component
  16533. for which this method will return true is the one that was originally
  16534. clicked on.
  16535. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16536. */
  16537. bool isMouseOver() const throw();
  16538. /** Returns true if the mouse button is currently held down in this component.
  16539. Note that this is a test to see whether the mouse is being pressed in this
  16540. component, so it'll return false if called on component A when the mouse
  16541. is actually being dragged in component B.
  16542. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16543. */
  16544. bool isMouseButtonDown() const throw();
  16545. /** True if the mouse is over this component, or if it's being dragged in this component.
  16546. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16547. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16548. */
  16549. bool isMouseOverOrDragging() const throw();
  16550. /** Returns true if a mouse button is currently down.
  16551. Unlike isMouseButtonDown, this will test the current state of the
  16552. buttons without regard to which component (if any) it has been
  16553. pressed in.
  16554. @see isMouseButtonDown, ModifierKeys
  16555. */
  16556. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16557. /** Returns the mouse's current position, relative to this component.
  16558. The co-ordinates are relative to the component's top-left corner.
  16559. */
  16560. void getMouseXYRelative (int& x, int& y) const throw();
  16561. /** Returns the component that's currently underneath the mouse.
  16562. @returns the component or 0 if there isn't one.
  16563. @see contains, getComponentAt
  16564. */
  16565. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16566. /** Allows the mouse to move beyond the edges of the screen.
  16567. Calling this method when the mouse button is currently pressed inside this component
  16568. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16569. the edges of the screen.
  16570. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16571. can be used for things like custom slider controls or dragging objects around, where
  16572. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16573. The unbounded mode is automatically turned off when the mouse button is released, or
  16574. it can be turned off explicitly by calling this method again.
  16575. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16576. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16577. hidden; if true, it will only be hidden when it
  16578. is moved beyond the edge of the screen
  16579. */
  16580. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16581. bool keepCursorVisibleUntilOffscreen = false) throw();
  16582. /** Called when this component's size has been changed.
  16583. A component can implement this method to do things such as laying out its
  16584. child components when its width or height changes.
  16585. The method is called synchronously as a result of the setBounds or setSize
  16586. methods, so repeatedly changing a components size will repeatedly call its
  16587. resized method (unlike things like repainting, where multiple calls to repaint
  16588. are coalesced together).
  16589. If the component is a top-level window on the desktop, its size could also
  16590. be changed by operating-system factors beyond the application's control.
  16591. @see moved, setSize
  16592. */
  16593. virtual void resized();
  16594. /** Called when this component's position has been changed.
  16595. This is called when the position relative to its parent changes, not when
  16596. its absolute position on the screen changes (so it won't be called for
  16597. all child components when a parent component is moved).
  16598. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16599. or any of the other repositioning methods, and like resized(), it will be
  16600. called each time those methods are called.
  16601. If the component is a top-level window on the desktop, its position could also
  16602. be changed by operating-system factors beyond the application's control.
  16603. @see resized, setBounds
  16604. */
  16605. virtual void moved();
  16606. /** Called when one of this component's children is moved or resized.
  16607. If the parent wants to know about changes to its immediate children (not
  16608. to children of its children), this is the method to override.
  16609. @see moved, resized, parentSizeChanged
  16610. */
  16611. virtual void childBoundsChanged (Component* child);
  16612. /** Called when this component's immediate parent has been resized.
  16613. If the component is a top-level window, this indicates that the screen size
  16614. has changed.
  16615. @see childBoundsChanged, moved, resized
  16616. */
  16617. virtual void parentSizeChanged();
  16618. /** Called when this component has been moved to the front of its siblings.
  16619. The component may have been brought to the front by the toFront() method, or
  16620. by the operating system if it's a top-level window.
  16621. @see toFront
  16622. */
  16623. virtual void broughtToFront();
  16624. /** Adds a listener to be told about changes to the component hierarchy or position.
  16625. Component listeners get called when this component's size, position or children
  16626. change - see the ComponentListener class for more details.
  16627. @param newListener the listener to register - if this is already registered, it
  16628. will be ignored.
  16629. @see ComponentListener, removeComponentListener
  16630. */
  16631. void addComponentListener (ComponentListener* const newListener) throw();
  16632. /** Removes a component listener.
  16633. @see addComponentListener
  16634. */
  16635. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16636. /** Dispatches a numbered message to this component.
  16637. This is a quick and cheap way of allowing simple asynchronous messages to
  16638. be sent to components. It's also safe, because if the component that you
  16639. send the message to is a null or dangling pointer, this won't cause an error.
  16640. The command ID is later delivered to the component's handleCommandMessage() method by
  16641. the application's message queue.
  16642. @see handleCommandMessage
  16643. */
  16644. void postCommandMessage (const int commandId) throw();
  16645. /** Called to handle a command that was sent by postCommandMessage().
  16646. This is called by the message thread when a command message arrives, and
  16647. the component can override this method to process it in any way it needs to.
  16648. @see postCommandMessage
  16649. */
  16650. virtual void handleCommandMessage (int commandId);
  16651. /** Runs a component modally, waiting until the loop terminates.
  16652. This method first makes the component visible, brings it to the front and
  16653. gives it the keyboard focus.
  16654. It then runs a loop, dispatching messages from the system message queue, but
  16655. blocking all mouse or keyboard messages from reaching any components other
  16656. than this one and its children.
  16657. This loop continues until the component's exitModalState() method is called (or
  16658. the component is deleted), and then this method returns, returning the value
  16659. passed into exitModalState().
  16660. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16661. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16662. */
  16663. int runModalLoop();
  16664. /** Puts the component into a modal state.
  16665. This makes the component modal, so that messages are blocked from reaching
  16666. any components other than this one and its children, but unlike runModalLoop(),
  16667. this method returns immediately.
  16668. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16669. get the focus, which is usually what you'll want it to do. If not, it will leave
  16670. the focus unchanged.
  16671. @see exitModalState, runModalLoop
  16672. */
  16673. void enterModalState (const bool takeKeyboardFocus = true);
  16674. /** Ends a component's modal state.
  16675. If this component is currently modal, this will turn of its modalness, and return
  16676. a value to the runModalLoop() method that might have be running its modal loop.
  16677. @see runModalLoop, enterModalState, isCurrentlyModal
  16678. */
  16679. void exitModalState (const int returnValue);
  16680. /** Returns true if this component is the modal one.
  16681. It's possible to have nested modal components, e.g. a pop-up dialog box
  16682. that launches another pop-up, but this will only return true for
  16683. the one at the top of the stack.
  16684. @see getCurrentlyModalComponent
  16685. */
  16686. bool isCurrentlyModal() const throw();
  16687. /** Returns the component that is currently modal.
  16688. @returns the modal component, or null if no components are modal
  16689. @see runModalLoop, isCurrentlyModal
  16690. */
  16691. static Component* JUCE_CALLTYPE getCurrentlyModalComponent() throw();
  16692. /** Checks whether there's a modal component somewhere that's stopping this one
  16693. from receiving messages.
  16694. If there is a modal component, its canModalEventBeSentToComponent() method
  16695. will be called to see if it will still allow this component to receive events.
  16696. @see runModalLoop, getCurrentlyModalComponent
  16697. */
  16698. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16699. /** When a component is modal, this callback allows it to choose which other
  16700. components can still receive events.
  16701. When a modal component is active and the user clicks on a non-modal component,
  16702. this method is called on the modal component, and if it returns true, the
  16703. event is allowed to reach its target. If it returns false, the event is blocked
  16704. and the inputAttemptWhenModal() callback is made.
  16705. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16706. implementation just returns false in all cases.
  16707. */
  16708. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16709. /** Called when the user tries to click on a component that is blocked by another
  16710. modal component.
  16711. When a component is modal and the user clicks on one of the other components,
  16712. the modal component will receive this callback.
  16713. The default implementation of this method will play a beep, and bring the currently
  16714. modal component to the front, but it can be overridden to do other tasks.
  16715. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16716. */
  16717. virtual void inputAttemptWhenModal();
  16718. /** Returns one of the component's properties as a string.
  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 value to return if the named property doesn't actually exist
  16724. */
  16725. const String getComponentProperty (const String& keyName,
  16726. const bool useParentComponentIfNotFound,
  16727. const String& defaultReturnValue = String::empty) const throw();
  16728. /** Returns one of the properties as an integer.
  16729. @param keyName the name of the property to retrieve
  16730. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16731. properties, then it will check whether the parent component has
  16732. the key.
  16733. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16734. */
  16735. int getComponentPropertyInt (const String& keyName,
  16736. const bool useParentComponentIfNotFound,
  16737. const int defaultReturnValue = 0) const throw();
  16738. /** Returns one of the properties as an double.
  16739. @param keyName the name of the property to retrieve
  16740. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16741. properties, then it will check whether the parent component has
  16742. the key.
  16743. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16744. */
  16745. double getComponentPropertyDouble (const String& keyName,
  16746. const bool useParentComponentIfNotFound,
  16747. const double defaultReturnValue = 0.0) const throw();
  16748. /** Returns one of the properties as an boolean.
  16749. The result will be true if the string found for this key name can be parsed as a non-zero
  16750. integer.
  16751. @param keyName the name of the property to retrieve
  16752. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16753. properties, then it will check whether the parent component has
  16754. the key.
  16755. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16756. */
  16757. bool getComponentPropertyBool (const String& keyName,
  16758. const bool useParentComponentIfNotFound,
  16759. const bool defaultReturnValue = false) const throw();
  16760. /** Returns one of the properties as an colour.
  16761. @param keyName the name of the property to retrieve
  16762. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16763. properties, then it will check whether the parent component has
  16764. the key.
  16765. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16766. */
  16767. const Colour getComponentPropertyColour (const String& keyName,
  16768. const bool useParentComponentIfNotFound,
  16769. const Colour& defaultReturnValue = Colours::black) const throw();
  16770. /** Sets a named property as a string.
  16771. @param keyName the name of the property to set. (This mustn't be an empty string)
  16772. @param value the new value to set it to
  16773. @see removeComponentProperty
  16774. */
  16775. void setComponentProperty (const String& keyName, const String& value) throw();
  16776. /** Sets a named property to an integer.
  16777. @param keyName the name of the property to set. (This mustn't be an empty string)
  16778. @param value the new value to set it to
  16779. @see removeComponentProperty
  16780. */
  16781. void setComponentProperty (const String& keyName, const int value) throw();
  16782. /** Sets a named property to a double.
  16783. @param keyName the name of the property to set. (This mustn't be an empty string)
  16784. @param value the new value to set it to
  16785. @see removeComponentProperty
  16786. */
  16787. void setComponentProperty (const String& keyName, const double value) throw();
  16788. /** Sets a named property to a boolean.
  16789. @param keyName the name of the property to set. (This mustn't be an empty string)
  16790. @param value the new value to set it to
  16791. @see removeComponentProperty
  16792. */
  16793. void setComponentProperty (const String& keyName, const bool value) throw();
  16794. /** Sets a named property to a colour.
  16795. @param keyName the name of the property to set. (This mustn't be an empty string)
  16796. @param newColour the new colour to set it to
  16797. @see removeComponentProperty
  16798. */
  16799. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16800. /** Deletes a named component property.
  16801. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16802. @see setComponentProperty, getComponentProperty
  16803. */
  16804. void removeComponentProperty (const String& keyName) throw();
  16805. /** Returns the complete set of properties that have been set for this component.
  16806. If no properties have been set, this will return a null pointer.
  16807. @see getComponentProperty, setComponentProperty
  16808. */
  16809. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16810. /** Looks for a colour that has been registered with the given colour ID number.
  16811. If a colour has been set for this ID number using setColour(), then it is
  16812. returned. If none has been set, the method will try calling the component's
  16813. LookAndFeel class's findColour() method. If none has been registered with the
  16814. look-and-feel either, it will just return black.
  16815. The colour IDs for various purposes are stored as enums in the components that
  16816. they are relevent to - for an example, see Slider::ColourIds,
  16817. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16818. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16819. */
  16820. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16821. /** Registers a colour to be used for a particular purpose.
  16822. Changing a colour will cause a synchronous callback to the colourChanged()
  16823. method, which your component can override if it needs to do something when
  16824. colours are altered.
  16825. For more details about colour IDs, see the comments for findColour().
  16826. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16827. */
  16828. void setColour (const int colourId, const Colour& colour);
  16829. /** If a colour has been set with setColour(), this will remove it.
  16830. This allows you to make a colour revert to its default state.
  16831. */
  16832. void removeColour (const int colourId);
  16833. /** Returns true if the specified colour ID has been explicitly set for this
  16834. component using the setColour() method.
  16835. */
  16836. bool isColourSpecified (const int colourId) const throw();
  16837. /** This looks for any colours that have been specified for this component,
  16838. and copies them to the specified target component.
  16839. */
  16840. void copyAllExplicitColoursTo (Component& target) const throw();
  16841. /** This method is called when a colour is changed by the setColour() method.
  16842. @see setColour, findColour
  16843. */
  16844. virtual void colourChanged();
  16845. /** Returns the underlying native window handle for this component.
  16846. This is platform-dependent and strictly for power-users only!
  16847. */
  16848. void* getWindowHandle() const throw();
  16849. /** When created, each component is given a number to uniquely identify it.
  16850. The number is incremented each time a new component is created, so it's a more
  16851. unique way of identifying a component than using its memory location (which
  16852. may be reused after the component is deleted, of course).
  16853. */
  16854. uint32 getComponentUID() const throw() { return componentUID; }
  16855. juce_UseDebuggingNewOperator
  16856. private:
  16857. friend class ComponentPeer;
  16858. friend class InternalDragRepeater;
  16859. static Component* currentlyFocusedComponent;
  16860. static Component* componentUnderMouse;
  16861. String componentName_;
  16862. Component* parentComponent_;
  16863. uint32 componentUID;
  16864. Rectangle bounds_;
  16865. unsigned short numDeepMouseListeners;
  16866. Array <Component*> childComponentList_;
  16867. LookAndFeel* lookAndFeel_;
  16868. MouseCursor cursor_;
  16869. ImageEffectFilter* effect_;
  16870. Image* bufferedImage_;
  16871. VoidArray* mouseListeners_;
  16872. VoidArray* keyListeners_;
  16873. VoidArray* componentListeners_;
  16874. PropertySet* propertySet_;
  16875. struct ComponentFlags
  16876. {
  16877. bool hasHeavyweightPeerFlag : 1;
  16878. bool visibleFlag : 1;
  16879. bool opaqueFlag : 1;
  16880. bool ignoresMouseClicksFlag : 1;
  16881. bool allowChildMouseClicksFlag : 1;
  16882. bool wantsFocusFlag : 1;
  16883. bool isFocusContainerFlag : 1;
  16884. bool dontFocusOnMouseClickFlag : 1;
  16885. bool alwaysOnTopFlag : 1;
  16886. bool bufferToImageFlag : 1;
  16887. bool bringToFrontOnClickFlag : 1;
  16888. bool repaintOnMouseActivityFlag : 1;
  16889. bool draggingFlag : 1;
  16890. bool mouseOverFlag : 1;
  16891. bool mouseInsideFlag : 1;
  16892. bool currentlyModalFlag : 1;
  16893. bool isDisabledFlag : 1;
  16894. bool childCompFocusedFlag : 1;
  16895. #ifdef JUCE_DEBUG
  16896. bool isInsidePaintCall : 1;
  16897. #endif
  16898. };
  16899. union
  16900. {
  16901. uint32 componentFlags_;
  16902. ComponentFlags flags;
  16903. };
  16904. void internalMouseEnter (int x, int y, const int64 time);
  16905. void internalMouseExit (int x, int y, const int64 time);
  16906. void internalMouseDown (int x, int y);
  16907. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16908. void internalMouseDrag (int x, int y, const int64 time);
  16909. void internalMouseMove (int x, int y, const int64 time);
  16910. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  16911. void internalBroughtToFront();
  16912. void internalFocusGain (const FocusChangeType cause);
  16913. void internalFocusLoss (const FocusChangeType cause);
  16914. void internalChildFocusChange (FocusChangeType cause);
  16915. void internalModalInputAttempt();
  16916. void internalModifierKeysChanged();
  16917. void internalChildrenChanged();
  16918. void internalHierarchyChanged();
  16919. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  16920. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  16921. void repaintParent() throw();
  16922. void sendFakeMouseMove() const;
  16923. void takeKeyboardFocus (const FocusChangeType cause);
  16924. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  16925. static void giveAwayFocus();
  16926. void sendEnablementChangeMessage();
  16927. static void* runModalLoopCallback (void*);
  16928. void subtractObscuredRegions (RectangleList& result,
  16929. const int deltaX, const int deltaY,
  16930. const Rectangle& clipRect,
  16931. const Component* const compToAvoid) const throw();
  16932. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  16933. const int deltaX, const int deltaY) const throw();
  16934. // how much of the component is not off the edges of its parents
  16935. const Rectangle getUnclippedArea() const;
  16936. void sendVisibilityChangeMessage();
  16937. // This is included here just to cause a compile error if your code is still handling
  16938. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  16939. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  16940. // implement its methods instead of this Component method).
  16941. virtual void filesDropped (const StringArray&, int, int) {}
  16942. // components aren't allowed to have copy constructors, as this would mess up parent
  16943. // hierarchies. You might need to give your subclasses a private dummy constructor like
  16944. // this one to avoid compiler warnings.
  16945. Component (const Component&);
  16946. const Component& operator= (const Component&);
  16947. protected:
  16948. /** @internal */
  16949. virtual void internalRepaint (int x, int y, int w, int h);
  16950. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  16951. /** Overridden from the MessageListener parent class.
  16952. You can override this if you really need to, but be sure to pass your unwanted messages up
  16953. to this base class implementation, as the Component class needs to send itself messages
  16954. to work properly.
  16955. */
  16956. void handleMessage (const Message&);
  16957. };
  16958. #endif // __JUCE_COMPONENT_JUCEHEADER__
  16959. /********* End of inlined file: juce_Component.h *********/
  16960. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  16961. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16962. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  16963. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  16964. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16965. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  16966. /** A type used to hold the unique ID for an application command.
  16967. This is a numeric type, so it can be stored as an integer.
  16968. @see ApplicationCommandInfo, ApplicationCommandManager,
  16969. ApplicationCommandTarget, KeyPressMappingSet
  16970. */
  16971. typedef int CommandID;
  16972. /** A set of general-purpose application command IDs.
  16973. Because these commands are likely to be used in most apps, they're defined
  16974. here to help different apps to use the same numeric values for them.
  16975. Of course you don't have to use these, but some of them are used internally by
  16976. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  16977. @see ApplicationCommandInfo, ApplicationCommandManager,
  16978. ApplicationCommandTarget, KeyPressMappingSet
  16979. */
  16980. namespace StandardApplicationCommandIDs
  16981. {
  16982. /** This command ID should be used to send a "Quit the App" command.
  16983. This command is recognised by the JUCEApplication class, so if it is invoked
  16984. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  16985. object will catch it and call JUCEApplication::systemRequestedQuit().
  16986. */
  16987. static const CommandID quit = 0x1001;
  16988. /** The command ID that should be used to send a "Delete" command. */
  16989. static const CommandID del = 0x1002;
  16990. /** The command ID that should be used to send a "Cut" command. */
  16991. static const CommandID cut = 0x1003;
  16992. /** The command ID that should be used to send a "Copy to clipboard" command. */
  16993. static const CommandID copy = 0x1004;
  16994. /** The command ID that should be used to send a "Paste from clipboard" command. */
  16995. static const CommandID paste = 0x1005;
  16996. /** The command ID that should be used to send a "Select all" command. */
  16997. static const CommandID selectAll = 0x1006;
  16998. /** The command ID that should be used to send a "Deselect all" command. */
  16999. static const CommandID deselectAll = 0x1007;
  17000. }
  17001. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17002. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  17003. /**
  17004. Holds information describing an application command.
  17005. This object is used to pass information about a particular command, such as its
  17006. name, description and other usage flags.
  17007. When an ApplicationCommandTarget is asked to provide information about the commands
  17008. it can perform, this is the structure gets filled-in to describe each one.
  17009. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  17010. ApplicationCommandManager
  17011. */
  17012. struct JUCE_API ApplicationCommandInfo
  17013. {
  17014. ApplicationCommandInfo (const CommandID commandID) throw();
  17015. /** Sets a number of the structures values at once.
  17016. The meanings of each of the parameters is described below, in the appropriate
  17017. member variable's description.
  17018. */
  17019. void setInfo (const String& shortName,
  17020. const String& description,
  17021. const String& categoryName,
  17022. const int flags) throw();
  17023. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17024. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17025. is false, the bit is set.
  17026. */
  17027. void setActive (const bool isActive) throw();
  17028. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17029. */
  17030. void setTicked (const bool isTicked) throw();
  17031. /** Handy method for adding a keypress to the defaultKeypresses array.
  17032. This is just so you can write things like:
  17033. @code
  17034. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17035. @endcode
  17036. instead of
  17037. @code
  17038. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17039. @endcode
  17040. */
  17041. void addDefaultKeypress (const int keyCode,
  17042. const ModifierKeys& modifiers) throw();
  17043. /** The command's unique ID number.
  17044. */
  17045. CommandID commandID;
  17046. /** A short name to describe the command.
  17047. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17048. You can use the setInfo() method to quickly set this and some of the command's
  17049. other properties.
  17050. */
  17051. String shortName;
  17052. /** A longer description of the command.
  17053. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17054. pop-up tooltip describing what the command does.
  17055. You can use the setInfo() method to quickly set this and some of the command's
  17056. other properties.
  17057. */
  17058. String description;
  17059. /** A named category that the command fits into.
  17060. You can give your commands any category you like, and these will be displayed in
  17061. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17062. commands together.
  17063. You can use the setInfo() method to quickly set this and some of the command's
  17064. other properties.
  17065. */
  17066. String categoryName;
  17067. /** A list of zero or more keypresses that should be used as the default keys for
  17068. this command.
  17069. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17070. this list to initialise the default set of key-to-command mappings.
  17071. @see addDefaultKeypress
  17072. */
  17073. Array <KeyPress> defaultKeypresses;
  17074. /** Flags describing the ways in which this command should be used.
  17075. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17076. variable.
  17077. */
  17078. enum CommandFlags
  17079. {
  17080. /** Indicates that the command can't currently be performed.
  17081. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17082. not currently permissable to perform the command. If the flag is set, then
  17083. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17084. command or show themselves as not being enabled.
  17085. @see ApplicationCommandInfo::setActive
  17086. */
  17087. isDisabled = 1 << 0,
  17088. /** Indicates that the command should have a tick next to it on a menu.
  17089. If your command is shown on a menu and this is set, it'll show a tick next to
  17090. it. Other components such as buttons may also use this flag to indicate that it
  17091. is a value that can be toggled, and is currently in the 'on' state.
  17092. @see ApplicationCommandInfo::setTicked
  17093. */
  17094. isTicked = 1 << 1,
  17095. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17096. it will call the command twice, once on key-down and again on key-up.
  17097. @see ApplicationCommandTarget::InvocationInfo
  17098. */
  17099. wantsKeyUpDownCallbacks = 1 << 2,
  17100. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17101. command in its list.
  17102. */
  17103. hiddenFromKeyEditor = 1 << 3,
  17104. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17105. command in its list, but won't allow the assigned keypress to be changed.
  17106. */
  17107. readOnlyInKeyEditor = 1 << 4,
  17108. /** If this flag is present and the command is invoked from a keypress, then any
  17109. buttons or menus that are also connected to the command will not flash to
  17110. indicate that they've been triggered.
  17111. */
  17112. dontTriggerVisualFeedback = 1 << 5
  17113. };
  17114. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17115. You can use the setInfo() method to quickly set this and some of the command's
  17116. other properties.
  17117. */
  17118. int flags;
  17119. };
  17120. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17121. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17122. /**
  17123. A command target publishes a list of command IDs that it can perform.
  17124. An ApplicationCommandManager despatches commands to targets, which must be
  17125. able to provide information about what commands they can handle.
  17126. To create a target, you'll need to inherit from this class, implementing all of
  17127. its pure virtual methods.
  17128. For info about how a target is chosen to receive a command, see
  17129. ApplicationCommandManager::getFirstCommandTarget().
  17130. @see ApplicationCommandManager, ApplicationCommandInfo
  17131. */
  17132. class JUCE_API ApplicationCommandTarget
  17133. {
  17134. public:
  17135. /** Creates a command target. */
  17136. ApplicationCommandTarget();
  17137. /** Destructor. */
  17138. virtual ~ApplicationCommandTarget();
  17139. /**
  17140. */
  17141. struct JUCE_API InvocationInfo
  17142. {
  17143. InvocationInfo (const CommandID commandID) throw();
  17144. /** The UID of the command that should be performed. */
  17145. CommandID commandID;
  17146. /** The command's flags.
  17147. See ApplicationCommandInfo for a description of these flag values.
  17148. */
  17149. int commandFlags;
  17150. /** The types of context in which the command might be called. */
  17151. enum InvocationMethod
  17152. {
  17153. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17154. fromKeyPress, /**< The command is being invoked by a key-press. */
  17155. fromMenu, /**< The command is being invoked by a menu selection. */
  17156. fromButton /**< The command is being invoked by a button click. */
  17157. };
  17158. /** The type of event that triggered this command. */
  17159. InvocationMethod invocationMethod;
  17160. /** If triggered by a keypress or menu, this will be the component that had the
  17161. keyboard focus at the time.
  17162. If triggered by a button, it may be set to that component, or it may be null.
  17163. */
  17164. Component* originatingComponent;
  17165. /** The keypress that was used to invoke it.
  17166. Note that this will be an invalid keypress if the command was invoked
  17167. by some other means than a keyboard shortcut.
  17168. */
  17169. KeyPress keyPress;
  17170. /** True if the callback is being invoked when the key is pressed,
  17171. false if the key is being released.
  17172. @see KeyPressMappingSet::addCommand()
  17173. */
  17174. bool isKeyDown;
  17175. /** If the key is being released, this indicates how long it had been held
  17176. down for.
  17177. (Only relevant if isKeyDown is false.)
  17178. */
  17179. int millisecsSinceKeyPressed;
  17180. };
  17181. /** This must return the next target to try after this one.
  17182. When a command is being sent, and the first target can't handle
  17183. that command, this method is used to determine the next target that should
  17184. be tried.
  17185. It may return 0 if it doesn't know of another target.
  17186. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17187. method to return a parent component that might want to handle it.
  17188. @see invoke
  17189. */
  17190. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17191. /** This must return a complete list of commands that this target can handle.
  17192. Your target should add all the command IDs that it handles to the array that is
  17193. passed-in.
  17194. */
  17195. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17196. /** This must provide details about one of the commands that this target can perform.
  17197. This will be called with one of the command IDs that the target provided in its
  17198. getAllCommands() methods.
  17199. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17200. suitable information about the command. (The commandID field will already have been filled-in
  17201. by the caller).
  17202. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17203. set all the fields at once.
  17204. If the command is currently inactive for some reason, this method must use
  17205. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17206. bit of the ApplicationCommandInfo::flags field).
  17207. Any default key-presses for the command should be appended to the
  17208. ApplicationCommandInfo::defaultKeypresses field.
  17209. Note that if you change something that affects the status of the commands
  17210. that would be returned by this method (e.g. something that makes some commands
  17211. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17212. to cause the manager to refresh its status.
  17213. */
  17214. virtual void getCommandInfo (const CommandID commandID,
  17215. ApplicationCommandInfo& result) = 0;
  17216. /** This must actually perform the specified command.
  17217. If this target is able to perform the command specified by the commandID field of the
  17218. InvocationInfo structure, then it should do so, and must return true.
  17219. If it can't handle this command, it should return false, which tells the caller to pass
  17220. the command on to the next target in line.
  17221. @see invoke, ApplicationCommandManager::invoke
  17222. */
  17223. virtual bool perform (const InvocationInfo& info) = 0;
  17224. /** Makes this target invoke a command.
  17225. Your code can call this method to invoke a command on this target, but normally
  17226. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17227. ApplicationCommandManager::invokeDirectly().
  17228. If this target can perform the given command, it will call its perform() method to
  17229. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17230. to try, and the command will be passed along to it.
  17231. @param invocationInfo this must be correctly filled-in, describing the context for
  17232. the invocation.
  17233. @param asynchronously if false, the command will be performed before this method returns.
  17234. If true, a message will be posted so that the command will be performed
  17235. later on the message thread, and this method will return immediately.
  17236. @see perform, ApplicationCommandManager::invoke
  17237. */
  17238. bool invoke (const InvocationInfo& invocationInfo,
  17239. const bool asynchronously);
  17240. /** Invokes a given command directly on this target.
  17241. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17242. structure.
  17243. */
  17244. bool invokeDirectly (const CommandID commandID,
  17245. const bool asynchronously);
  17246. /** Searches this target and all subsequent ones for the first one that can handle
  17247. the specified command.
  17248. This will use getNextCommandTarget() to determine the chain of targets to try
  17249. after this one.
  17250. */
  17251. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17252. /** Checks whether this command can currently be performed by this target.
  17253. This will return true only if a call to getCommandInfo() doesn't set the
  17254. isDisabled flag to indicate that the command is inactive.
  17255. */
  17256. bool isCommandActive (const CommandID commandID);
  17257. /** If this object is a Component, this method will seach upwards in its current
  17258. UI hierarchy for the next parent component that implements the
  17259. ApplicationCommandTarget class.
  17260. If your target is a Component, this is a very handy method to use in your
  17261. getNextCommandTarget() implementation.
  17262. */
  17263. ApplicationCommandTarget* findFirstTargetParentComponent();
  17264. juce_UseDebuggingNewOperator
  17265. private:
  17266. // (for async invocation of commands)
  17267. class CommandTargetMessageInvoker : public MessageListener
  17268. {
  17269. public:
  17270. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17271. ~CommandTargetMessageInvoker();
  17272. void handleMessage (const Message& message);
  17273. private:
  17274. ApplicationCommandTarget* const owner;
  17275. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17276. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17277. };
  17278. CommandTargetMessageInvoker* messageInvoker;
  17279. friend class CommandTargetMessageInvoker;
  17280. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17281. };
  17282. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17283. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17284. /********* Start of inlined file: juce_ActionListener.h *********/
  17285. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17286. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17287. /**
  17288. Receives callbacks to indicate that some kind of event has occurred.
  17289. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17290. about something that's happened.
  17291. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17292. */
  17293. class JUCE_API ActionListener
  17294. {
  17295. public:
  17296. /** Destructor. */
  17297. virtual ~ActionListener() {}
  17298. /** Overridden by your subclass to receive the callback.
  17299. @param message the string that was specified when the event was triggered
  17300. by a call to ActionListenerList::sendActionMessage()
  17301. */
  17302. virtual void actionListenerCallback (const String& message) = 0;
  17303. };
  17304. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17305. /********* End of inlined file: juce_ActionListener.h *********/
  17306. /**
  17307. An instance of this class is used to specify initialisation and shutdown
  17308. code for the application.
  17309. An application that wants to run in the JUCE framework needs to declare a
  17310. subclass of JUCEApplication and implement its various pure virtual methods.
  17311. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17312. to declare an instance of this class and generate a suitable platform-specific
  17313. main() function.
  17314. e.g. @code
  17315. class MyJUCEApp : public JUCEApplication
  17316. {
  17317. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17318. // objects, which you must create in the initialise() method.
  17319. MyApplicationWindow* myMainWindow;
  17320. public:
  17321. MyJUCEApp()
  17322. : myMainWindow (0)
  17323. {
  17324. // never create any Juce objects in the constructor - do all your initialisation
  17325. // in the initialise() method.
  17326. }
  17327. ~MyJUCEApp()
  17328. {
  17329. // all your shutdown code must have already been done in the shutdown() method -
  17330. // nothing should happen in this destructor.
  17331. }
  17332. void initialise (const String& commandLine)
  17333. {
  17334. myMainWindow = new MyApplicationWindow();
  17335. myMainWindow->setBounds (100, 100, 400, 500);
  17336. myMainWindow->setVisible (true);
  17337. }
  17338. void shutdown()
  17339. {
  17340. delete myMainWindow;
  17341. }
  17342. const String getApplicationName()
  17343. {
  17344. return T("Super JUCE-o-matic");
  17345. }
  17346. const String getApplicationVersion()
  17347. {
  17348. return T("1.0");
  17349. }
  17350. };
  17351. // this creates wrapper code to actually launch the app properly.
  17352. START_JUCE_APPLICATION (MyJUCEApp)
  17353. @endcode
  17354. Because this object will be created before Juce has properly initialised, you must
  17355. NEVER add any member variable objects that will be automatically constructed. Likewise
  17356. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17357. you want to add to the class must be pointers, which you should instantiate during the
  17358. initialise() method, and delete in the shutdown() method.
  17359. @see MessageManager, DeletedAtShutdown
  17360. */
  17361. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17362. private ActionListener
  17363. {
  17364. protected:
  17365. /** Constructs a JUCE app object.
  17366. If subclasses implement a constructor or destructor, they shouldn't call any
  17367. JUCE code in there - put your startup/shutdown code in initialise() and
  17368. shutdown() instead.
  17369. */
  17370. JUCEApplication();
  17371. public:
  17372. /** Destructor.
  17373. If subclasses implement a constructor or destructor, they shouldn't call any
  17374. JUCE code in there - put your startup/shutdown code in initialise() and
  17375. shutdown() instead.
  17376. */
  17377. virtual ~JUCEApplication();
  17378. /** Returns the global instance of the application object being run. */
  17379. static JUCEApplication* getInstance() throw();
  17380. /** Called when the application starts.
  17381. This will be called once to let the application do whatever initialisation
  17382. it needs, create its windows, etc.
  17383. After the method returns, the normal event-dispatch loop will be run,
  17384. until the quit() method is called, at which point the shutdown()
  17385. method will be called to let the application clear up anything it needs
  17386. to delete.
  17387. If during the initialise() method, the application decides not to start-up
  17388. after all, it can just call the quit() method and the event loop won't be run.
  17389. @param commandLineParameters the line passed in does not include the
  17390. name of the executable, just the parameter list.
  17391. @see shutdown, quit
  17392. */
  17393. virtual void initialise (const String& commandLineParameters) = 0;
  17394. /** Returns true if the application hasn't yet completed its initialise() method
  17395. and entered the main event loop.
  17396. This is handy for things like splash screens to know when the app's up-and-running
  17397. properly.
  17398. */
  17399. bool isInitialising() const throw();
  17400. /* Called to allow the application to clear up before exiting.
  17401. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17402. terminate, and this method will get called to allow the app to sort itself
  17403. out.
  17404. Be careful that nothing happens in this method that might rely on messages
  17405. being sent, or any kind of window activity, because the message loop is no
  17406. longer running at this point.
  17407. @see DeletedAtShutdown
  17408. */
  17409. virtual void shutdown() = 0;
  17410. /** Returns the application's name.
  17411. An application must implement this to name itself.
  17412. */
  17413. virtual const String getApplicationName() = 0;
  17414. /** Returns the application's version number.
  17415. An application can implement this to give itself a version.
  17416. (The default implementation of this just returns an empty string).
  17417. */
  17418. virtual const String getApplicationVersion();
  17419. /** Checks whether multiple instances of the app are allowed.
  17420. If you application class returns true for this, more than one instance is
  17421. permitted to run (except on the Mac where this isn't possible).
  17422. If it's false, the second instance won't start, but it you will still get a
  17423. callback to anotherInstanceStarted() to tell you about this - which
  17424. gives you a chance to react to what the user was trying to do.
  17425. */
  17426. virtual bool moreThanOneInstanceAllowed();
  17427. /** Indicates that the user has tried to start up another instance of the app.
  17428. This will get called even if moreThanOneInstanceAllowed() is false.
  17429. */
  17430. virtual void anotherInstanceStarted (const String& commandLine);
  17431. /** Called when the operating system is trying to close the application.
  17432. The default implementation of this method is to call quit(), but it may
  17433. be overloaded to ignore the request or do some other special behaviour
  17434. instead. For example, you might want to offer the user the chance to save
  17435. their changes before quitting, and give them the chance to cancel.
  17436. If you want to send a quit signal to your app, this is the correct method
  17437. to call, because it means that requests that come from the system get handled
  17438. in the same way as those from your own application code. So e.g. you'd
  17439. call this method from a "quit" item on a menu bar.
  17440. */
  17441. virtual void systemRequestedQuit();
  17442. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17443. callback will be triggered, in case you want to log them or do some other
  17444. type of error-handling.
  17445. If the type of exception is derived from the std::exception class, the pointer
  17446. passed-in will be valid. If the exception is of unknown type, this pointer
  17447. will be null.
  17448. */
  17449. virtual void unhandledException (const std::exception* e,
  17450. const String& sourceFilename,
  17451. const int lineNumber);
  17452. /** Signals that the main message loop should stop and the application should terminate.
  17453. This isn't synchronous, it just posts a quit message to the main queue, and
  17454. when this message arrives, the message loop will stop, the shutdown() method
  17455. will be called, and the app will exit.
  17456. Note that this will cause an unconditional quit to happen, so if you need an
  17457. extra level before this, e.g. to give the user the chance to save their work
  17458. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17459. method - see that method's help for more info.
  17460. @see MessageManager, DeletedAtShutdown
  17461. */
  17462. static void quit();
  17463. /** Sets the value that should be returned as the application's exit code when the
  17464. app quits.
  17465. This is the value that's returned by the main() function. Normally you'd leave this
  17466. as 0 unless you want to indicate an error code.
  17467. @see getApplicationReturnValue
  17468. */
  17469. void setApplicationReturnValue (const int newReturnValue) throw();
  17470. /** Returns the value that has been set as the application's exit code.
  17471. @see setApplicationReturnValue
  17472. */
  17473. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17474. /** Returns the application's command line params.
  17475. */
  17476. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  17477. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17478. /** @internal */
  17479. static int main (String& commandLine, JUCEApplication* const newApp);
  17480. /** @internal */
  17481. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17482. /** @internal */
  17483. static void sendUnhandledException (const std::exception* const e,
  17484. const char* const sourceFile,
  17485. const int lineNumber);
  17486. /** @internal */
  17487. ApplicationCommandTarget* getNextCommandTarget();
  17488. /** @internal */
  17489. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17490. /** @internal */
  17491. void getAllCommands (Array <CommandID>& commands);
  17492. /** @internal */
  17493. bool perform (const InvocationInfo& info);
  17494. /** @internal */
  17495. void actionListenerCallback (const String& message);
  17496. private:
  17497. String commandLineParameters;
  17498. int appReturnValue;
  17499. bool stillInitialising;
  17500. static int shutdownAppAndClearUp();
  17501. };
  17502. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17503. /********* End of inlined file: juce_Application.h *********/
  17504. #endif
  17505. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17506. #endif
  17507. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17508. #endif
  17509. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17510. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17511. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17512. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17513. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17514. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17515. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17516. /**
  17517. Has a callback method that is triggered asynchronously.
  17518. This object allows an asynchronous callback function to be triggered, for
  17519. tasks such as coalescing multiple updates into a single callback later on.
  17520. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17521. message thread calling handleAsyncUpdate() as soon as it can.
  17522. */
  17523. class JUCE_API AsyncUpdater
  17524. {
  17525. public:
  17526. /** Creates an AsyncUpdater object. */
  17527. AsyncUpdater() throw();
  17528. /** Destructor.
  17529. If there are any pending callbacks when the object is deleted, these are lost.
  17530. */
  17531. virtual ~AsyncUpdater();
  17532. /** Causes the callback to be triggered at a later time.
  17533. This method returns immediately, having made sure that a callback
  17534. to the handleAsyncUpdate() method will occur as soon as possible.
  17535. If an update callback is already pending but hasn't happened yet, calls
  17536. to this method will be ignored.
  17537. It's thread-safe to call this method from any number of threads without
  17538. needing to worry about locking.
  17539. */
  17540. void triggerAsyncUpdate() throw();
  17541. /** This will stop any pending updates from happening.
  17542. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17543. callback happens, this will cancel the handleAsyncUpdate() callback.
  17544. */
  17545. void cancelPendingUpdate() throw();
  17546. /** If an update has been triggered and is pending, this will invoke it
  17547. synchronously.
  17548. Use this as a kind of "flush" operation - if an update is pending, the
  17549. handleAsyncUpdate() method will be called immediately; if no update is
  17550. pending, then nothing will be done.
  17551. */
  17552. void handleUpdateNowIfNeeded();
  17553. /** Called back to do whatever your class needs to do.
  17554. This method is called by the message thread at the next convenient time
  17555. after the triggerAsyncUpdate() method has been called.
  17556. */
  17557. virtual void handleAsyncUpdate() = 0;
  17558. private:
  17559. class AsyncUpdaterInternal : public MessageListener
  17560. {
  17561. public:
  17562. AsyncUpdaterInternal() throw() {}
  17563. ~AsyncUpdaterInternal() {}
  17564. void handleMessage (const Message&);
  17565. AsyncUpdater* owner;
  17566. private:
  17567. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17568. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17569. };
  17570. AsyncUpdaterInternal internalAsyncHandler;
  17571. bool asyncMessagePending;
  17572. };
  17573. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17574. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17575. /********* Start of inlined file: juce_Desktop.h *********/
  17576. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17577. #define __JUCE_DESKTOP_JUCEHEADER__
  17578. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17579. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17580. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17581. /**
  17582. Classes derived from this will be automatically deleted when the application exits.
  17583. After JUCEApplication::shutdown() has been called, any objects derived from
  17584. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17585. order to that in which they were created.
  17586. So if you've got a singleton and don't want to have to explicitly delete it, just
  17587. inherit from this and it'll be taken care of.
  17588. */
  17589. class JUCE_API DeletedAtShutdown
  17590. {
  17591. protected:
  17592. /** Creates a DeletedAtShutdown object. */
  17593. DeletedAtShutdown() throw();
  17594. /** Destructor.
  17595. It's ok to delete these objects explicitly - it's only the ones left
  17596. dangling at the end that will be deleted automatically.
  17597. */
  17598. virtual ~DeletedAtShutdown();
  17599. public:
  17600. /** Deletes all extant objects.
  17601. This shouldn't be used by applications, as it's called automatically
  17602. in the shutdown code of the JUCEApplication class.
  17603. */
  17604. static void deleteAll();
  17605. private:
  17606. DeletedAtShutdown (const DeletedAtShutdown&);
  17607. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17608. };
  17609. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17610. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17611. /********* Start of inlined file: juce_Timer.h *********/
  17612. #ifndef __JUCE_TIMER_JUCEHEADER__
  17613. #define __JUCE_TIMER_JUCEHEADER__
  17614. class InternalTimerThread;
  17615. /**
  17616. Repeatedly calls a user-defined method at a specified time interval.
  17617. A Timer's timerCallback() method will be repeatedly called at a given
  17618. interval. Initially when a Timer object is created, they will do nothing
  17619. until the startTimer() method is called, then the message thread will
  17620. start calling it back until stopTimer() is called.
  17621. The time interval isn't guaranteed to be precise to any more than maybe
  17622. 10-20ms, and the intervals may end up being much longer than requested if the
  17623. system is busy. Because it's the message thread that is doing the callbacks,
  17624. any messages that take a significant amount of time to process will block
  17625. all the timers for that period.
  17626. If you need to have a single callback that is shared by multiple timers with
  17627. different frequencies, then the MultiTimer class allows you to do that - its
  17628. structure is very similar to the Timer class, but contains multiple timers
  17629. internally, each one identified by an ID number.
  17630. @see MultiTimer
  17631. */
  17632. class JUCE_API Timer
  17633. {
  17634. protected:
  17635. /** Creates a Timer.
  17636. When created, the timer is stopped, so use startTimer() to get it going.
  17637. */
  17638. Timer() throw();
  17639. /** Creates a copy of another timer.
  17640. Note that this timer won't be started, even if the one you're copying
  17641. is running.
  17642. */
  17643. Timer (const Timer& other) throw();
  17644. public:
  17645. /** Destructor. */
  17646. virtual ~Timer();
  17647. /** The user-defined callback routine that actually gets called periodically.
  17648. It's perfectly ok to call startTimer() or stopTimer() from within this
  17649. callback to change the subsequent intervals.
  17650. */
  17651. virtual void timerCallback() = 0;
  17652. /** Starts the timer and sets the length of interval required.
  17653. If the timer is already started, this will reset it, so the
  17654. time between calling this method and the next timer callback
  17655. will not be less than the interval length passed in.
  17656. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17657. rounded up to 1)
  17658. */
  17659. void startTimer (const int intervalInMilliseconds) throw();
  17660. /** Stops the timer.
  17661. No more callbacks will be made after this method returns.
  17662. If this is called from a different thread, any callbacks that may
  17663. be currently executing may be allowed to finish before the method
  17664. returns.
  17665. */
  17666. void stopTimer() throw();
  17667. /** Checks if the timer has been started.
  17668. @returns true if the timer is running.
  17669. */
  17670. bool isTimerRunning() const throw() { return periodMs > 0; }
  17671. /** Returns the timer's interval.
  17672. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17673. */
  17674. int getTimerInterval() const throw() { return periodMs; }
  17675. private:
  17676. friend class InternalTimerThread;
  17677. int countdownMs, periodMs;
  17678. Timer* previous;
  17679. Timer* next;
  17680. const Timer& operator= (const Timer&);
  17681. };
  17682. #endif // __JUCE_TIMER_JUCEHEADER__
  17683. /********* End of inlined file: juce_Timer.h *********/
  17684. /**
  17685. Classes can implement this interface and register themselves with the Desktop class
  17686. to receive callbacks when the currently focused component changes.
  17687. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17688. */
  17689. class JUCE_API FocusChangeListener
  17690. {
  17691. public:
  17692. /** Destructor. */
  17693. virtual ~FocusChangeListener() {}
  17694. /** Callback to indicate that the currently focused component has changed. */
  17695. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17696. };
  17697. /**
  17698. Describes and controls aspects of the computer's desktop.
  17699. */
  17700. class JUCE_API Desktop : private DeletedAtShutdown,
  17701. private Timer,
  17702. private AsyncUpdater
  17703. {
  17704. public:
  17705. /** There's only one dektop object, and this method will return it.
  17706. */
  17707. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17708. /** Returns a list of the positions of all the monitors available.
  17709. The first rectangle in the list will be the main monitor area.
  17710. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17711. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17712. */
  17713. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17714. /** Returns the position and size of the main monitor.
  17715. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17716. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17717. */
  17718. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17719. /** Returns the position and size of the monitor which contains this co-ordinate.
  17720. If none of the monitors contains the point, this will just return the
  17721. main monitor.
  17722. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17723. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17724. */
  17725. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17726. /** Returns the mouse position.
  17727. The co-ordinates are relative to the top-left of the main monitor.
  17728. */
  17729. static void getMousePosition (int& x, int& y) throw();
  17730. /** Makes the mouse pointer jump to a given location.
  17731. The co-ordinates are relative to the top-left of the main monitor.
  17732. */
  17733. static void setMousePosition (int x, int y) throw();
  17734. /** Returns the last position at which a mouse button was pressed.
  17735. */
  17736. static void getLastMouseDownPosition (int& x, int& y) throw();
  17737. /** Returns the number of times the mouse button has been clicked since the
  17738. app started.
  17739. Each mouse-down event increments this number by 1.
  17740. */
  17741. static int getMouseButtonClickCounter() throw();
  17742. /** This lets you prevent the screensaver from becoming active.
  17743. Handy if you're running some sort of presentation app where having a screensaver
  17744. appear would be annoying.
  17745. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17746. won't enable a screensaver unless the user has actually set one up).
  17747. The disablement will only happen while the Juce application is the foreground
  17748. process - if another task is running in front of it, then the screensaver will
  17749. be unaffected.
  17750. @see isScreenSaverEnabled
  17751. */
  17752. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17753. /** Returns true if the screensaver has not been turned off.
  17754. This will return the last value passed into setScreenSaverEnabled(). Note that
  17755. it won't tell you whether the user is actually using a screen saver, just
  17756. whether this app is deliberately preventing one from running.
  17757. @see setScreenSaverEnabled
  17758. */
  17759. static bool isScreenSaverEnabled() throw();
  17760. /** Registers a MouseListener that will receive all mouse events that occur on
  17761. any component.
  17762. @see removeGlobalMouseListener
  17763. */
  17764. void addGlobalMouseListener (MouseListener* const listener) throw();
  17765. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17766. method.
  17767. @see addGlobalMouseListener
  17768. */
  17769. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17770. /** Registers a MouseListener that will receive a callback whenever the focused
  17771. component changes.
  17772. */
  17773. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17774. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17775. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17776. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  17777. The component must already be on the desktop for this method to work. It will
  17778. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  17779. etc will be hidden.
  17780. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  17781. the component that's currently being used will be resized back to the size
  17782. and position it was in before being put into this mode.
  17783. */
  17784. void setKioskModeComponent (Component* componentToUse);
  17785. /** Returns the component that is currently being used in kiosk-mode.
  17786. This is the component that was last set by setKioskModeComponent(). If none
  17787. has been set, this returns 0.
  17788. */
  17789. Component* getKioskModeComponent() const { return kioskModeComponent; }
  17790. /** Returns the number of components that are currently active as top-level
  17791. desktop windows.
  17792. @see getComponent, Component::addToDesktop
  17793. */
  17794. int getNumComponents() const throw();
  17795. /** Returns one of the top-level desktop window components.
  17796. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17797. index is out-of-range.
  17798. @see getNumComponents, Component::addToDesktop
  17799. */
  17800. Component* getComponent (const int index) const throw();
  17801. /** Finds the component at a given screen location.
  17802. This will drill down into top-level windows to find the child component at
  17803. the given position.
  17804. Returns 0 if the co-ordinates are inside a non-Juce window.
  17805. */
  17806. Component* findComponentAt (const int screenX,
  17807. const int screenY) const;
  17808. juce_UseDebuggingNewOperator
  17809. /** Tells this object to refresh its idea of what the screen resolution is.
  17810. (Called internally by the native code).
  17811. */
  17812. void refreshMonitorSizes() throw();
  17813. /** True if the OS supports semitransparent windows */
  17814. static bool canUseSemiTransparentWindows() throw();
  17815. private:
  17816. friend class Component;
  17817. friend class ComponentPeer;
  17818. SortedSet <void*> mouseListeners, focusListeners;
  17819. VoidArray desktopComponents;
  17820. friend class DeletedAtShutdown;
  17821. friend class TopLevelWindowManager;
  17822. Desktop() throw();
  17823. ~Desktop() throw();
  17824. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17825. int lastMouseX, lastMouseY;
  17826. Component* kioskModeComponent;
  17827. Rectangle kioskComponentOriginalBounds;
  17828. void timerCallback();
  17829. void sendMouseMove();
  17830. void resetTimer() throw();
  17831. int getNumDisplayMonitors() const throw();
  17832. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17833. void addDesktopComponent (Component* const c) throw();
  17834. void removeDesktopComponent (Component* const c) throw();
  17835. void componentBroughtToFront (Component* const c) throw();
  17836. void triggerFocusCallback() throw();
  17837. void handleAsyncUpdate();
  17838. Desktop (const Desktop&);
  17839. const Desktop& operator= (const Desktop&);
  17840. };
  17841. #endif // __JUCE_DESKTOP_JUCEHEADER__
  17842. /********* End of inlined file: juce_Desktop.h *********/
  17843. class KeyPressMappingSet;
  17844. class ApplicationCommandManagerListener;
  17845. /**
  17846. One of these objects holds a list of all the commands your app can perform,
  17847. and despatches these commands when needed.
  17848. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  17849. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  17850. to invoke automatically, which means you don't have to handle the result of a menu
  17851. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  17852. which can choose which events they want to handle.
  17853. This architecture also allows for nested ApplicationCommandTargets, so that for example
  17854. you could have two different objects, one inside the other, both of which can respond to
  17855. a "delete" command. Depending on which one has focus, the command will be sent to the
  17856. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  17857. method.
  17858. To set up your app to use commands, you'll need to do the following:
  17859. - Create a global ApplicationCommandManager to hold the list of all possible
  17860. commands. (This will also manage a set of key-mappings for them).
  17861. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  17862. This allows the object to provide a list of commands that it can perform, and
  17863. to handle them.
  17864. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  17865. or ApplicationCommandManager::registerCommand().
  17866. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  17867. method to access the key-mapper object, which you will need to register as a key-listener
  17868. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  17869. about setting this up.
  17870. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  17871. cause these commands to be invoked automatically.
  17872. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  17873. When a command is invoked, the ApplicationCommandManager will try to choose the best
  17874. ApplicationCommandTarget to receive the specified command. To do this it will use the
  17875. current keyboard focus to see which component might be interested, and will search the
  17876. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  17877. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  17878. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  17879. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  17880. point if the command still hasn't been performed, it will be passed to the current
  17881. JUCEApplication object (which is itself an ApplicationCommandTarget).
  17882. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  17883. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  17884. the object yourself.
  17885. @see ApplicationCommandTarget, ApplicationCommandInfo
  17886. */
  17887. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  17888. private FocusChangeListener
  17889. {
  17890. public:
  17891. /** Creates an ApplicationCommandManager.
  17892. Once created, you'll need to register all your app's commands with it, using
  17893. ApplicationCommandManager::registerAllCommandsForTarget() or
  17894. ApplicationCommandManager::registerCommand().
  17895. */
  17896. ApplicationCommandManager();
  17897. /** Destructor.
  17898. Make sure that you don't delete this if pointers to it are still being used by
  17899. objects such as PopupMenus or Buttons.
  17900. */
  17901. virtual ~ApplicationCommandManager();
  17902. /** Clears the current list of all commands.
  17903. Note that this will also clear the contents of the KeyPressMappingSet.
  17904. */
  17905. void clearCommands();
  17906. /** Adds a command to the list of registered commands.
  17907. @see registerAllCommandsForTarget
  17908. */
  17909. void registerCommand (const ApplicationCommandInfo& newCommand);
  17910. /** Adds all the commands that this target publishes to the manager's list.
  17911. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  17912. to get details about all the commands that this target can do, and will call
  17913. registerCommand() to add each one to the manger's list.
  17914. @see registerCommand
  17915. */
  17916. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  17917. /** Removes the command with a specified ID.
  17918. Note that this will also remove any key mappings that are mapped to the command.
  17919. */
  17920. void removeCommand (const CommandID commandID);
  17921. /** This should be called to tell the manager that one of its registered commands may have changed
  17922. its active status.
  17923. Because the command manager only finds out whether a command is active or inactive by querying
  17924. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  17925. allows things like buttons to update their enablement, etc.
  17926. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  17927. for any registered listeners.
  17928. */
  17929. void commandStatusChanged();
  17930. /** Returns the number of commands that have been registered.
  17931. @see registerCommand
  17932. */
  17933. int getNumCommands() const throw() { return commands.size(); }
  17934. /** Returns the details about one of the registered commands.
  17935. The index is between 0 and (getNumCommands() - 1).
  17936. */
  17937. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  17938. /** Returns the details about a given command ID.
  17939. This will search the list of registered commands for one with the given command
  17940. ID number, and return its associated info. If no matching command is found, this
  17941. will return 0.
  17942. */
  17943. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  17944. /** Returns the name field for a command.
  17945. An empty string is returned if no command with this ID has been registered.
  17946. @see getDescriptionOfCommand
  17947. */
  17948. const String getNameOfCommand (const CommandID commandID) const throw();
  17949. /** Returns the description field for a command.
  17950. An empty string is returned if no command with this ID has been registered. If the
  17951. command has no description, this will return its short name field instead.
  17952. @see getNameOfCommand
  17953. */
  17954. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  17955. /** Returns the list of categories.
  17956. This will go through all registered commands, and return a list of all the distict
  17957. categoryName values from their ApplicationCommandInfo structure.
  17958. @see getCommandsInCategory()
  17959. */
  17960. const StringArray getCommandCategories() const throw();
  17961. /** Returns a list of all the command UIDs in a particular category.
  17962. @see getCommandCategories()
  17963. */
  17964. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  17965. /** Returns the manager's internal set of key mappings.
  17966. This object can be used to edit the keypresses. To actually link this object up
  17967. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  17968. class.
  17969. @see KeyPressMappingSet
  17970. */
  17971. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  17972. /** Invokes the given command directly, sending it to the default target.
  17973. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17974. structure.
  17975. */
  17976. bool invokeDirectly (const CommandID commandID,
  17977. const bool asynchronously);
  17978. /** Sends a command to the default target.
  17979. This will choose a target using getFirstCommandTarget(), and send the specified command
  17980. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  17981. first target can't handle the command, it will be passed on to targets further down the
  17982. chain (see ApplicationCommandTarget::invoke() for more info).
  17983. @param invocationInfo this must be correctly filled-in, describing the context for
  17984. the invocation.
  17985. @param asynchronously if false, the command will be performed before this method returns.
  17986. If true, a message will be posted so that the command will be performed
  17987. later on the message thread, and this method will return immediately.
  17988. @see ApplicationCommandTarget::invoke
  17989. */
  17990. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  17991. const bool asynchronously);
  17992. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  17993. Whenever the manager needs to know which target a command should be sent to, it calls
  17994. this method to determine the first one to try.
  17995. By default, this method will return the target that was set by calling setFirstCommandTarget().
  17996. If no target is set, it will return the result of findDefaultComponentTarget().
  17997. If you need to make sure all commands go via your own custom target, then you can
  17998. either use setFirstCommandTarget() to specify a single target, or override this method
  17999. if you need more complex logic to choose one.
  18000. It may return 0 if no targets are available.
  18001. @see getTargetForCommand, invoke, invokeDirectly
  18002. */
  18003. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  18004. /** Sets a target to be returned by getFirstCommandTarget().
  18005. If this is set to 0, then getFirstCommandTarget() will by default return the
  18006. result of findDefaultComponentTarget().
  18007. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  18008. deleting the target object.
  18009. */
  18010. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  18011. /** Tries to find the best target to use to perform a given command.
  18012. This will call getFirstCommandTarget() to find the preferred target, and will
  18013. check whether that target can handle the given command. If it can't, then it'll use
  18014. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  18015. so on until no more are available.
  18016. If no targets are found that can perform the command, this method will return 0.
  18017. If a target is found, then it will get the target to fill-in the upToDateInfo
  18018. structure with the latest info about that command, so that the caller can see
  18019. whether the command is disabled, ticked, etc.
  18020. */
  18021. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18022. ApplicationCommandInfo& upToDateInfo);
  18023. /** Registers a listener that will be called when various events occur. */
  18024. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18025. /** Deregisters a previously-added listener. */
  18026. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18027. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18028. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18029. but is exposed here in case it's useful.
  18030. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18031. windows, etc., and using the findTargetForComponent() method.
  18032. */
  18033. static ApplicationCommandTarget* findDefaultComponentTarget();
  18034. /** Examines this component and all its parents in turn, looking for the first one
  18035. which is a ApplicationCommandTarget.
  18036. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18037. that class.
  18038. */
  18039. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18040. juce_UseDebuggingNewOperator
  18041. private:
  18042. OwnedArray <ApplicationCommandInfo> commands;
  18043. SortedSet <void*> listeners;
  18044. KeyPressMappingSet* keyMappings;
  18045. ApplicationCommandTarget* firstTarget;
  18046. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18047. void handleAsyncUpdate();
  18048. void globalFocusChanged (Component*);
  18049. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18050. // version of this method.
  18051. virtual short getFirstCommandTarget() { return 0; }
  18052. };
  18053. /**
  18054. A listener that receives callbacks from an ApplicationCommandManager when
  18055. commands are invoked or the command list is changed.
  18056. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18057. */
  18058. class JUCE_API ApplicationCommandManagerListener
  18059. {
  18060. public:
  18061. /** Destructor. */
  18062. virtual ~ApplicationCommandManagerListener() {}
  18063. /** Called when an app command is about to be invoked. */
  18064. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18065. /** Called when commands are registered or deregistered from the
  18066. command manager, or when commands are made active or inactive.
  18067. Note that if you're using this to watch for changes to whether a command is disabled,
  18068. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18069. whenever the status of your command might have changed.
  18070. */
  18071. virtual void applicationCommandListChanged() = 0;
  18072. };
  18073. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18074. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18075. #endif
  18076. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18077. #endif
  18078. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18079. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18080. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18081. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18082. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18083. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18084. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18085. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18086. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18087. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18088. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18089. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18090. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18091. /********* Start of inlined file: juce_ChangeListener.h *********/
  18092. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18093. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18094. /**
  18095. Receives callbacks about changes to some kind of object.
  18096. Many objects use a ChangeListenerList to keep a set of listeners which they
  18097. will inform when something changes. A subclass of ChangeListener
  18098. is used to receive these callbacks.
  18099. Note that the major difference between an ActionListener and a ChangeListener
  18100. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18101. callbacks, but ActionListeners perform one callback for every event posted.
  18102. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18103. */
  18104. class JUCE_API ChangeListener
  18105. {
  18106. public:
  18107. /** Destructor. */
  18108. virtual ~ChangeListener() {}
  18109. /** Overridden by your subclass to receive the callback.
  18110. @param objectThatHasChanged the value that was passed to the
  18111. ChangeListenerList::sendChangeMessage() method
  18112. */
  18113. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18114. };
  18115. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18116. /********* End of inlined file: juce_ChangeListener.h *********/
  18117. /**
  18118. A set of ChangeListeners.
  18119. Listeners can be added and removed from the list, and change messages can be
  18120. broadcast to all the listeners.
  18121. @see ChangeListener, ChangeBroadcaster
  18122. */
  18123. class JUCE_API ChangeListenerList : public MessageListener
  18124. {
  18125. public:
  18126. /** Creates an empty list. */
  18127. ChangeListenerList() throw();
  18128. /** Destructor. */
  18129. ~ChangeListenerList() throw();
  18130. /** Adds a listener to the list.
  18131. (Trying to add a listener that's already on the list will have no effect).
  18132. */
  18133. void addChangeListener (ChangeListener* const listener) throw();
  18134. /** Removes a listener from the list.
  18135. If the listener isn't on the list, this won't have any effect.
  18136. */
  18137. void removeChangeListener (ChangeListener* const listener) throw();
  18138. /** Removes all listeners from the list. */
  18139. void removeAllChangeListeners() throw();
  18140. /** Posts an asynchronous change message to all the listeners.
  18141. If a message has already been sent and hasn't yet been delivered, this
  18142. method won't send another - in this way it coalesces multiple frequent
  18143. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18144. with the ActionListener, which posts a new event for every call to its
  18145. sendActionMessage() method.
  18146. Only listeners which are on the list when the change event is delivered
  18147. will receive the event - and this may include listeners that weren't on
  18148. the list when the change message was sent.
  18149. @param objectThatHasChanged this pointer is passed to the
  18150. ChangeListener::changeListenerCallback() method,
  18151. and can be any value the application needs
  18152. @see sendSynchronousChangeMessage
  18153. */
  18154. void sendChangeMessage (void* objectThatHasChanged) throw();
  18155. /** This will synchronously callback all the ChangeListeners.
  18156. Use this if you need to synchronously force a call to all the
  18157. listeners' ChangeListener::changeListenerCallback() methods.
  18158. */
  18159. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18160. /** If a change message has been sent but not yet dispatched, this will
  18161. use sendSynchronousChangeMessage() to make the callback immediately.
  18162. */
  18163. void dispatchPendingMessages();
  18164. /** @internal */
  18165. void handleMessage (const Message&);
  18166. juce_UseDebuggingNewOperator
  18167. private:
  18168. SortedSet <void*> listeners;
  18169. CriticalSection lock;
  18170. void* lastChangedObject;
  18171. bool messagePending;
  18172. ChangeListenerList (const ChangeListenerList&);
  18173. const ChangeListenerList& operator= (const ChangeListenerList&);
  18174. };
  18175. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18176. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18177. /** Manages a list of ChangeListeners, and can send them messages.
  18178. To quickly add methods to your class that can add/remove change
  18179. listeners and broadcast to them, you can derive from this.
  18180. @see ChangeListenerList, ChangeListener
  18181. */
  18182. class JUCE_API ChangeBroadcaster
  18183. {
  18184. public:
  18185. /** Creates an ChangeBroadcaster. */
  18186. ChangeBroadcaster() throw();
  18187. /** Destructor. */
  18188. virtual ~ChangeBroadcaster();
  18189. /** Adds a listener to the list.
  18190. (Trying to add a listener that's already on the list will have no effect).
  18191. */
  18192. void addChangeListener (ChangeListener* const listener) throw();
  18193. /** Removes a listener from the list.
  18194. If the listener isn't on the list, this won't have any effect.
  18195. */
  18196. void removeChangeListener (ChangeListener* const listener) throw();
  18197. /** Removes all listeners from the list. */
  18198. void removeAllChangeListeners() throw();
  18199. /** Broadcasts a change message to all the registered listeners.
  18200. The message will be delivered asynchronously by the event thread, so this
  18201. method will not directly call any of the listeners. For a synchronous
  18202. message, use sendSynchronousChangeMessage().
  18203. @see ChangeListenerList::sendActionMessage
  18204. */
  18205. void sendChangeMessage (void* objectThatHasChanged) throw();
  18206. /** Sends a synchronous change message to all the registered listeners.
  18207. @see ChangeListenerList::sendSynchronousChangeMessage
  18208. */
  18209. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18210. /** If a change message has been sent but not yet dispatched, this will
  18211. use sendSynchronousChangeMessage() to make the callback immediately.
  18212. */
  18213. void dispatchPendingMessages();
  18214. private:
  18215. ChangeListenerList changeListenerList;
  18216. ChangeBroadcaster (const ChangeBroadcaster&);
  18217. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18218. };
  18219. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18220. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18221. /** Wrapper on a file that stores a list of key/value data pairs.
  18222. Useful for storing application settings, etc. See the PropertySet class for
  18223. the interfaces that read and write values.
  18224. Not designed for very large amounts of data, as it keeps all the values in
  18225. memory and writes them out to disk lazily when they are changed.
  18226. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18227. with it, and these will be signalled when a value changes.
  18228. @see PropertySet
  18229. */
  18230. class JUCE_API PropertiesFile : public PropertySet,
  18231. public ChangeBroadcaster,
  18232. private Timer
  18233. {
  18234. public:
  18235. enum FileFormatOptions
  18236. {
  18237. ignoreCaseOfKeyNames = 1,
  18238. storeAsBinary = 2,
  18239. storeAsCompressedBinary = 4,
  18240. storeAsXML = 8
  18241. };
  18242. /**
  18243. Creates a PropertiesFile object.
  18244. @param file the file to use
  18245. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18246. is changed, the object will wait for this amount
  18247. of time and then save the file. If zero, the file
  18248. will be written to disk immediately on being changed
  18249. (which might be slow, as it'll re-write synchronously
  18250. each time a value-change method is called). If it is
  18251. less than zero, the file won't be saved until
  18252. save() or saveIfNeeded() are explicitly called.
  18253. @param options a combination of the flags in the FileFormatOptions
  18254. enum, which specify the type of file to save, and other
  18255. options.
  18256. */
  18257. PropertiesFile (const File& file,
  18258. const int millisecondsBeforeSaving,
  18259. const int options) throw();
  18260. /** Destructor.
  18261. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18262. */
  18263. ~PropertiesFile();
  18264. /** This will flush all the values to disk if they've changed since the last
  18265. time they were saved.
  18266. Returns false if it fails to write to the file for some reason (maybe because
  18267. it's read-only or the directory doesn't exist or something).
  18268. @see save
  18269. */
  18270. bool saveIfNeeded();
  18271. /** This will force a write-to-disk of the current values, regardless of whether
  18272. anything has changed since the last save.
  18273. Returns false if it fails to write to the file for some reason (maybe because
  18274. it's read-only or the directory doesn't exist or something).
  18275. @see saveIfNeeded
  18276. */
  18277. bool save();
  18278. /** Returns true if the properties have been altered since the last time they were
  18279. saved.
  18280. */
  18281. bool needsToBeSaved() const throw();
  18282. /** Returns the file that's being used. */
  18283. const File getFile() const throw();
  18284. /** Handy utility to create a properties file in whatever the standard OS-specific
  18285. location is for these things.
  18286. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18287. creates a PropertiesFile object with the specified properties. See
  18288. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18289. what the parameters do.
  18290. @see getDefaultAppSettingsFile
  18291. */
  18292. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18293. const String& fileNameSuffix,
  18294. const String& folderName,
  18295. const bool commonToAllUsers,
  18296. const int millisecondsBeforeSaving,
  18297. const int propertiesFileOptions);
  18298. /** Handy utility to choose a file in the standard OS-dependent location for application
  18299. settings files.
  18300. So on a Mac, this will return a file called:
  18301. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18302. On Windows it'll return something like:
  18303. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18304. On Linux it'll return
  18305. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18306. If you pass an empty string as the folder name, it'll use the app name for this (or
  18307. omit the folder name on the Mac).
  18308. If commonToAllUsers is true, then this will return the same file for all users of the
  18309. computer, regardless of the current user. If it is false, the file will be specific to
  18310. only the current user. Use this to choose whether you're saving settings that are common
  18311. or user-specific.
  18312. */
  18313. static const File getDefaultAppSettingsFile (const String& applicationName,
  18314. const String& fileNameSuffix,
  18315. const String& folderName,
  18316. const bool commonToAllUsers);
  18317. juce_UseDebuggingNewOperator
  18318. protected:
  18319. virtual void propertyChanged();
  18320. private:
  18321. File file;
  18322. int timerInterval;
  18323. const int options;
  18324. bool needsWriting;
  18325. void timerCallback();
  18326. PropertiesFile (const PropertiesFile&);
  18327. const PropertiesFile& operator= (const PropertiesFile&);
  18328. };
  18329. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18330. /********* End of inlined file: juce_PropertiesFile.h *********/
  18331. /**
  18332. Manages a collection of properties.
  18333. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18334. as a singleton.
  18335. It holds two different PropertiesFile objects internally, one for user-specific
  18336. settings (stored in your user directory), and one for settings that are common to
  18337. all users (stored in a folder accessible to all users).
  18338. The class manages the creation of these files on-demand, allowing access via the
  18339. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18340. methods like testWriteAccess() to check that the files can be saved.
  18341. If you're using one of these as a singleton, then your app's start-up code should
  18342. first of all call setStorageParameters() to tell it the parameters to use to create
  18343. the properties files.
  18344. @see PropertiesFile
  18345. */
  18346. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18347. {
  18348. public:
  18349. /**
  18350. Creates an ApplicationProperties object.
  18351. Before using it, you must call setStorageParameters() to give it the info
  18352. it needs to create the property files.
  18353. */
  18354. ApplicationProperties() throw();
  18355. /** Destructor.
  18356. */
  18357. ~ApplicationProperties();
  18358. juce_DeclareSingleton (ApplicationProperties, false)
  18359. /** Gives the object the information it needs to create the appropriate properties files.
  18360. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18361. info about how these parameters are used.
  18362. */
  18363. void setStorageParameters (const String& applicationName,
  18364. const String& fileNameSuffix,
  18365. const String& folderName,
  18366. const int millisecondsBeforeSaving,
  18367. const int propertiesFileOptions) throw();
  18368. /** Tests whether the files can be successfully written to, and can show
  18369. an error message if not.
  18370. Returns true if none of the tests fail.
  18371. @param testUserSettings if true, the user settings file will be tested
  18372. @param testCommonSettings if true, the common settings file will be tested
  18373. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18374. message box if either of the tests fail
  18375. */
  18376. bool testWriteAccess (const bool testUserSettings,
  18377. const bool testCommonSettings,
  18378. const bool showWarningDialogOnFailure);
  18379. /** Returns the user settings file.
  18380. The first time this is called, it will create and load the properties file.
  18381. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18382. the common settings are used as a second-chance place to look. This is done via the
  18383. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18384. to the fallback for the user settings.
  18385. @see getCommonSettings
  18386. */
  18387. PropertiesFile* getUserSettings() throw();
  18388. /** Returns the common settings file.
  18389. The first time this is called, it will create and load the properties file.
  18390. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18391. read-only (e.g. because the user doesn't have permission to write
  18392. to shared files), then this will return the user settings instead,
  18393. (like getUserSettings() would do). This is handy if you'd like to
  18394. write a value to the common settings, but if that's no possible,
  18395. then you'd rather write to the user settings than none at all.
  18396. If returnUserPropsIfReadOnly is false, this method will always return
  18397. the common settings, even if any changes to them can't be saved.
  18398. @see getUserSettings
  18399. */
  18400. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18401. /** Saves both files if they need to be saved.
  18402. @see PropertiesFile::saveIfNeeded
  18403. */
  18404. bool saveIfNeeded();
  18405. /** Flushes and closes both files if they are open.
  18406. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18407. and closes both files. They will then be re-opened the next time getUserSettings()
  18408. or getCommonSettings() is called.
  18409. */
  18410. void closeFiles();
  18411. juce_UseDebuggingNewOperator
  18412. private:
  18413. PropertiesFile* userProps;
  18414. PropertiesFile* commonProps;
  18415. String appName, fileSuffix, folderName;
  18416. int msBeforeSaving, options;
  18417. int commonSettingsAreReadOnly;
  18418. ApplicationProperties (const ApplicationProperties&);
  18419. const ApplicationProperties& operator= (const ApplicationProperties&);
  18420. void openFiles() throw();
  18421. };
  18422. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18423. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18424. #endif
  18425. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18426. #endif
  18427. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18428. #endif
  18429. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18430. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18431. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18432. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18433. /**
  18434. Handles reading/writing to the system's clipboard.
  18435. */
  18436. class JUCE_API SystemClipboard
  18437. {
  18438. public:
  18439. /** Copies a string of text onto the clipboard */
  18440. static void copyTextToClipboard (const String& text) throw();
  18441. /** Gets the current clipboard's contents.
  18442. Obviously this might have come from another app, so could contain
  18443. anything..
  18444. */
  18445. static const String getTextFromClipboard() throw();
  18446. };
  18447. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18448. /********* End of inlined file: juce_SystemClipboard.h *********/
  18449. #endif
  18450. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18451. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18452. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18453. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18454. /********* Start of inlined file: juce_MidiMessage.h *********/
  18455. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18456. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18457. /**
  18458. Encapsulates a MIDI message.
  18459. @see MidiMessageSequence, MidiOutput, MidiInput
  18460. */
  18461. class JUCE_API MidiMessage
  18462. {
  18463. public:
  18464. /** Creates a 3-byte short midi message.
  18465. @param byte1 message byte 1
  18466. @param byte2 message byte 2
  18467. @param byte3 message byte 3
  18468. @param timeStamp the time to give the midi message - this value doesn't
  18469. use any particular units, so will be application-specific
  18470. */
  18471. MidiMessage (const int byte1,
  18472. const int byte2,
  18473. const int byte3,
  18474. const double timeStamp = 0) throw();
  18475. /** Creates a 2-byte short midi message.
  18476. @param byte1 message byte 1
  18477. @param byte2 message byte 2
  18478. @param timeStamp the time to give the midi message - this value doesn't
  18479. use any particular units, so will be application-specific
  18480. */
  18481. MidiMessage (const int byte1,
  18482. const int byte2,
  18483. const double timeStamp = 0) throw();
  18484. /** Creates a 1-byte short midi message.
  18485. @param byte1 message byte 1
  18486. @param timeStamp the time to give the midi message - this value doesn't
  18487. use any particular units, so will be application-specific
  18488. */
  18489. MidiMessage (const int byte1,
  18490. const double timeStamp = 0) throw();
  18491. /** Creates a midi message from a block of data. */
  18492. MidiMessage (const uint8* const data,
  18493. const int dataSize,
  18494. const double timeStamp = 0) throw();
  18495. /** Reads the next midi message from some data.
  18496. This will read as many bytes from a data stream as it needs to make a
  18497. complete message, and will return the number of bytes it used. This lets
  18498. you read a sequence of midi messages from a file or stream.
  18499. @param data the data to read from
  18500. @param size the maximum number of bytes it's allowed to read
  18501. @param numBytesUsed returns the number of bytes that were actually needed
  18502. @param lastStatusByte in a sequence of midi messages, the initial byte
  18503. can be dropped from a message if it's the same as the
  18504. first byte of the previous message, so this lets you
  18505. supply the byte to use if the first byte of the message
  18506. has in fact been dropped.
  18507. @param timeStamp the time to give the midi message - this value doesn't
  18508. use any particular units, so will be application-specific
  18509. */
  18510. MidiMessage (const uint8* data,
  18511. int size,
  18512. int& numBytesUsed,
  18513. uint8 lastStatusByte,
  18514. double timeStamp = 0) throw();
  18515. /** Creates a copy of another midi message. */
  18516. MidiMessage (const MidiMessage& other) throw();
  18517. /** Creates a copy of another midi message, with a different timestamp. */
  18518. MidiMessage (const MidiMessage& other,
  18519. const double newTimeStamp) throw();
  18520. /** Destructor. */
  18521. ~MidiMessage() throw();
  18522. /** Copies this message from another one. */
  18523. const MidiMessage& operator= (const MidiMessage& other) throw();
  18524. /** Returns a pointer to the raw midi data.
  18525. @see getRawDataSize
  18526. */
  18527. uint8* getRawData() const throw() { return data; }
  18528. /** Returns the number of bytes of data in the message.
  18529. @see getRawData
  18530. */
  18531. int getRawDataSize() const throw() { return size; }
  18532. /** Returns the timestamp associated with this message.
  18533. The units for the timestamp will be application-specific.
  18534. @see setTimeStamp, addToTimeStamp
  18535. */
  18536. double getTimeStamp() const throw() { return timeStamp; }
  18537. /** Changes the message's associated timestamp.
  18538. The units for the timestamp will be application-specific.
  18539. @see addToTimeStamp, getTimeStamp
  18540. */
  18541. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18542. /** Adds a value to the message's timestamp.
  18543. The units for the timestamp will be application-specific.
  18544. */
  18545. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18546. /** Returns the midi channel associated with the message.
  18547. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18548. if it's a sysex)
  18549. @see isForChannel, setChannel
  18550. */
  18551. int getChannel() const throw();
  18552. /** Returns true if the message applies to the given midi channel.
  18553. @param channelNumber the channel number to look for, in the range 1 to 16
  18554. @see getChannel, setChannel
  18555. */
  18556. bool isForChannel (const int channelNumber) const throw();
  18557. /** Changes the message's midi channel.
  18558. This won't do anything for non-channel messages like sysexes.
  18559. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18560. */
  18561. void setChannel (const int newChannelNumber) throw();
  18562. /** Returns true if this is a system-exclusive message.
  18563. */
  18564. bool isSysEx() const throw();
  18565. /** Returns a pointer to the sysex data inside the message.
  18566. If this event isn't a sysex event, it'll return 0.
  18567. @see getSysExDataSize
  18568. */
  18569. const uint8* getSysExData() const throw();
  18570. /** Returns the size of the sysex data.
  18571. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18572. @see getSysExData
  18573. */
  18574. int getSysExDataSize() const throw();
  18575. /** Returns true if this message is a 'key-down' event.
  18576. This will return false for a note-on event with a velocity of 0.
  18577. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18578. */
  18579. bool isNoteOn() const throw();
  18580. /** Creates a key-down message (using a floating-point velocity).
  18581. @param channel the midi channel, in the range 1 to 16
  18582. @param noteNumber the key number, 0 to 127
  18583. @param velocity in the range 0 to 1.0
  18584. @see isNoteOn
  18585. */
  18586. static const MidiMessage noteOn (const int channel,
  18587. const int noteNumber,
  18588. const float velocity) throw();
  18589. /** Creates a key-down message (using an integer velocity).
  18590. @param channel the midi channel, in the range 1 to 16
  18591. @param noteNumber the key number, 0 to 127
  18592. @param velocity in the range 0 to 127
  18593. @see isNoteOn
  18594. */
  18595. static const MidiMessage noteOn (const int channel,
  18596. const int noteNumber,
  18597. const uint8 velocity) throw();
  18598. /** Returns true if this message is a 'key-up' event.
  18599. This will also return true for a note-on event with a velocity of 0.
  18600. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18601. */
  18602. bool isNoteOff() const throw();
  18603. /** Creates a key-up message.
  18604. @param channel the midi channel, in the range 1 to 16
  18605. @param noteNumber the key number, 0 to 127
  18606. @see isNoteOff
  18607. */
  18608. static const MidiMessage noteOff (const int channel,
  18609. const int noteNumber) throw();
  18610. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18611. @see isNoteOn, isNoteOff
  18612. */
  18613. bool isNoteOnOrOff() const throw();
  18614. /** Returns the midi note number for note-on and note-off messages.
  18615. If the message isn't a note-on or off, the value returned will be
  18616. meaningless.
  18617. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18618. */
  18619. int getNoteNumber() const throw();
  18620. /** Changes the midi note number of a note-on or note-off message.
  18621. If the message isn't a note on or off, this will do nothing.
  18622. */
  18623. void setNoteNumber (const int newNoteNumber) throw();
  18624. /** Returns the velocity of a note-on or note-off message.
  18625. The value returned will be in the range 0 to 127.
  18626. If the message isn't a note-on or off event, it will return 0.
  18627. @see getFloatVelocity
  18628. */
  18629. uint8 getVelocity() const throw();
  18630. /** Returns the velocity of a note-on or note-off message.
  18631. The value returned will be in the range 0 to 1.0
  18632. If the message isn't a note-on or off event, it will return 0.
  18633. @see getVelocity, setVelocity
  18634. */
  18635. float getFloatVelocity() const throw();
  18636. /** Changes the velocity of a note-on or note-off message.
  18637. If the message isn't a note on or off, this will do nothing.
  18638. @param newVelocity the new velocity, in the range 0 to 1.0
  18639. @see getFloatVelocity, multiplyVelocity
  18640. */
  18641. void setVelocity (const float newVelocity) throw();
  18642. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18643. If the message isn't a note on or off, this will do nothing.
  18644. @param scaleFactor the value by which to multiply the velocity
  18645. @see setVelocity
  18646. */
  18647. void multiplyVelocity (const float scaleFactor) throw();
  18648. /** Returns true if the message is a program (patch) change message.
  18649. @see getProgramChangeNumber, getGMInstrumentName
  18650. */
  18651. bool isProgramChange() const throw();
  18652. /** Returns the new program number of a program change message.
  18653. If the message isn't a program change, the value returned will be
  18654. nonsense.
  18655. @see isProgramChange, getGMInstrumentName
  18656. */
  18657. int getProgramChangeNumber() const throw();
  18658. /** Creates a program-change message.
  18659. @param channel the midi channel, in the range 1 to 16
  18660. @param programNumber the midi program number, 0 to 127
  18661. @see isProgramChange, getGMInstrumentName
  18662. */
  18663. static const MidiMessage programChange (const int channel,
  18664. const int programNumber) throw();
  18665. /** Returns true if the message is a pitch-wheel move.
  18666. @see getPitchWheelValue, pitchWheel
  18667. */
  18668. bool isPitchWheel() const throw();
  18669. /** Returns the pitch wheel position from a pitch-wheel move message.
  18670. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18671. If called for messages which aren't pitch wheel events, the number returned will be
  18672. nonsense.
  18673. @see isPitchWheel
  18674. */
  18675. int getPitchWheelValue() const throw();
  18676. /** Creates a pitch-wheel move message.
  18677. @param channel the midi channel, in the range 1 to 16
  18678. @param position the wheel position, in the range 0 to 16383
  18679. @see isPitchWheel
  18680. */
  18681. static const MidiMessage pitchWheel (const int channel,
  18682. const int position) throw();
  18683. /** Returns true if the message is an aftertouch event.
  18684. For aftertouch events, use the getNoteNumber() method to find out the key
  18685. that it applies to, and getAftertouchValue() to find out the amount. Use
  18686. getChannel() to find out the channel.
  18687. @see getAftertouchValue, getNoteNumber
  18688. */
  18689. bool isAftertouch() const throw();
  18690. /** Returns the amount of aftertouch from an aftertouch messages.
  18691. The value returned is in the range 0 to 127, and will be nonsense for messages
  18692. other than aftertouch messages.
  18693. @see isAftertouch
  18694. */
  18695. int getAfterTouchValue() const throw();
  18696. /** Creates an aftertouch message.
  18697. @param channel the midi channel, in the range 1 to 16
  18698. @param noteNumber the key number, 0 to 127
  18699. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18700. @see isAftertouch
  18701. */
  18702. static const MidiMessage aftertouchChange (const int channel,
  18703. const int noteNumber,
  18704. const int aftertouchAmount) throw();
  18705. /** Returns true if the message is a channel-pressure change event.
  18706. This is like aftertouch, but common to the whole channel rather than a specific
  18707. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18708. to find out the channel.
  18709. @see channelPressureChange
  18710. */
  18711. bool isChannelPressure() const throw();
  18712. /** Returns the pressure from a channel pressure change message.
  18713. @returns the pressure, in the range 0 to 127
  18714. @see isChannelPressure, channelPressureChange
  18715. */
  18716. int getChannelPressureValue() const throw();
  18717. /** Creates a channel-pressure change event.
  18718. @param channel the midi channel: 1 to 16
  18719. @param pressure the pressure, 0 to 127
  18720. @see isChannelPressure
  18721. */
  18722. static const MidiMessage channelPressureChange (const int channel,
  18723. const int pressure) throw();
  18724. /** Returns true if this is a midi controller message.
  18725. @see getControllerNumber, getControllerValue, controllerEvent
  18726. */
  18727. bool isController() const throw();
  18728. /** Returns the controller number of a controller message.
  18729. The name of the controller can be looked up using the getControllerName() method.
  18730. Note that the value returned is invalid for messages that aren't controller changes.
  18731. @see isController, getControllerName, getControllerValue
  18732. */
  18733. int getControllerNumber() const throw();
  18734. /** Returns the controller value from a controller message.
  18735. A value 0 to 127 is returned to indicate the new controller position.
  18736. Note that the value returned is invalid for messages that aren't controller changes.
  18737. @see isController, getControllerNumber
  18738. */
  18739. int getControllerValue() const throw();
  18740. /** Creates a controller message.
  18741. @param channel the midi channel, in the range 1 to 16
  18742. @param controllerType the type of controller
  18743. @param value the controller value
  18744. @see isController
  18745. */
  18746. static const MidiMessage controllerEvent (const int channel,
  18747. const int controllerType,
  18748. const int value) throw();
  18749. /** Checks whether this message is an all-notes-off message.
  18750. @see allNotesOff
  18751. */
  18752. bool isAllNotesOff() const throw();
  18753. /** Checks whether this message is an all-sound-off message.
  18754. @see allSoundOff
  18755. */
  18756. bool isAllSoundOff() const throw();
  18757. /** Creates an all-notes-off message.
  18758. @param channel the midi channel, in the range 1 to 16
  18759. @see isAllNotesOff
  18760. */
  18761. static const MidiMessage allNotesOff (const int channel) throw();
  18762. /** Creates an all-sound-off message.
  18763. @param channel the midi channel, in the range 1 to 16
  18764. @see isAllSoundOff
  18765. */
  18766. static const MidiMessage allSoundOff (const int channel) throw();
  18767. /** Creates an all-controllers-off message.
  18768. @param channel the midi channel, in the range 1 to 16
  18769. */
  18770. static const MidiMessage allControllersOff (const int channel) throw();
  18771. /** Returns true if this event is a meta-event.
  18772. Meta-events are things like tempo changes, track names, etc.
  18773. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18774. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18775. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18776. */
  18777. bool isMetaEvent() const throw();
  18778. /** Returns a meta-event's type number.
  18779. If the message isn't a meta-event, this will return -1.
  18780. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18781. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18782. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18783. */
  18784. int getMetaEventType() const throw();
  18785. /** Returns a pointer to the data in a meta-event.
  18786. @see isMetaEvent, getMetaEventLength
  18787. */
  18788. const uint8* getMetaEventData() const throw();
  18789. /** Returns the length of the data for a meta-event.
  18790. @see isMetaEvent, getMetaEventData
  18791. */
  18792. int getMetaEventLength() const throw();
  18793. /** Returns true if this is a 'track' meta-event. */
  18794. bool isTrackMetaEvent() const throw();
  18795. /** Returns true if this is an 'end-of-track' meta-event. */
  18796. bool isEndOfTrackMetaEvent() const throw();
  18797. /** Creates an end-of-track meta-event.
  18798. @see isEndOfTrackMetaEvent
  18799. */
  18800. static const MidiMessage endOfTrack() throw();
  18801. /** Returns true if this is an 'track name' meta-event.
  18802. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18803. */
  18804. bool isTrackNameEvent() const throw();
  18805. /** Returns true if this is a 'text' meta-event.
  18806. @see getTextFromTextMetaEvent
  18807. */
  18808. bool isTextMetaEvent() const throw();
  18809. /** Returns the text from a text meta-event.
  18810. @see isTextMetaEvent
  18811. */
  18812. const String getTextFromTextMetaEvent() const throw();
  18813. /** Returns true if this is a 'tempo' meta-event.
  18814. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18815. */
  18816. bool isTempoMetaEvent() const throw();
  18817. /** Returns the tick length from a tempo meta-event.
  18818. @param timeFormat the 16-bit time format value from the midi file's header.
  18819. @returns the tick length (in seconds).
  18820. @see isTempoMetaEvent
  18821. */
  18822. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18823. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18824. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18825. */
  18826. double getTempoSecondsPerQuarterNote() const throw();
  18827. /** Creates a tempo meta-event.
  18828. @see isTempoMetaEvent
  18829. */
  18830. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18831. /** Returns true if this is a 'time-signature' meta-event.
  18832. @see getTimeSignatureInfo
  18833. */
  18834. bool isTimeSignatureMetaEvent() const throw();
  18835. /** Returns the time-signature values from a time-signature meta-event.
  18836. @see isTimeSignatureMetaEvent
  18837. */
  18838. void getTimeSignatureInfo (int& numerator,
  18839. int& denominator) const throw();
  18840. /** Creates a time-signature meta-event.
  18841. @see isTimeSignatureMetaEvent
  18842. */
  18843. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  18844. const int denominator) throw();
  18845. /** Returns true if this is a 'key-signature' meta-event.
  18846. @see getKeySignatureNumberOfSharpsOrFlats
  18847. */
  18848. bool isKeySignatureMetaEvent() const throw();
  18849. /** Returns the key from a key-signature meta-event.
  18850. @see isKeySignatureMetaEvent
  18851. */
  18852. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  18853. /** Returns true if this is a 'channel' meta-event.
  18854. A channel meta-event specifies the midi channel that should be used
  18855. for subsequent meta-events.
  18856. @see getMidiChannelMetaEventChannel
  18857. */
  18858. bool isMidiChannelMetaEvent() const throw();
  18859. /** Returns the channel number from a channel meta-event.
  18860. @returns the channel, in the range 1 to 16.
  18861. @see isMidiChannelMetaEvent
  18862. */
  18863. int getMidiChannelMetaEventChannel() const throw();
  18864. /** Creates a midi channel meta-event.
  18865. @param channel the midi channel, in the range 1 to 16
  18866. @see isMidiChannelMetaEvent
  18867. */
  18868. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  18869. /** Returns true if this is an active-sense message. */
  18870. bool isActiveSense() const throw();
  18871. /** Returns true if this is a midi start event.
  18872. @see midiStart
  18873. */
  18874. bool isMidiStart() const throw();
  18875. /** Creates a midi start event. */
  18876. static const MidiMessage midiStart() throw();
  18877. /** Returns true if this is a midi continue event.
  18878. @see midiContinue
  18879. */
  18880. bool isMidiContinue() const throw();
  18881. /** Creates a midi continue event. */
  18882. static const MidiMessage midiContinue() throw();
  18883. /** Returns true if this is a midi stop event.
  18884. @see midiStop
  18885. */
  18886. bool isMidiStop() const throw();
  18887. /** Creates a midi stop event. */
  18888. static const MidiMessage midiStop() throw();
  18889. /** Returns true if this is a midi clock event.
  18890. @see midiClock, songPositionPointer
  18891. */
  18892. bool isMidiClock() const throw();
  18893. /** Creates a midi clock event. */
  18894. static const MidiMessage midiClock() throw();
  18895. /** Returns true if this is a song-position-pointer message.
  18896. @see getSongPositionPointerMidiBeat, songPositionPointer
  18897. */
  18898. bool isSongPositionPointer() const throw();
  18899. /** Returns the midi beat-number of a song-position-pointer message.
  18900. @see isSongPositionPointer, songPositionPointer
  18901. */
  18902. int getSongPositionPointerMidiBeat() const throw();
  18903. /** Creates a song-position-pointer message.
  18904. The position is a number of midi beats from the start of the song, where 1 midi
  18905. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  18906. are 4 midi beats in a quarter-note.
  18907. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  18908. */
  18909. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  18910. /** Returns true if this is a quarter-frame midi timecode message.
  18911. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  18912. */
  18913. bool isQuarterFrame() const throw();
  18914. /** Returns the sequence number of a quarter-frame midi timecode message.
  18915. This will be a value between 0 and 7.
  18916. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  18917. */
  18918. int getQuarterFrameSequenceNumber() const throw();
  18919. /** Returns the value from a quarter-frame message.
  18920. This will be the lower nybble of the message's data-byte, a value
  18921. between 0 and 15
  18922. */
  18923. int getQuarterFrameValue() const throw();
  18924. /** Creates a quarter-frame MTC message.
  18925. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  18926. @param value a value 0 to 15 for the lower nybble of the message's data byte
  18927. */
  18928. static const MidiMessage quarterFrame (const int sequenceNumber,
  18929. const int value) throw();
  18930. /** SMPTE timecode types.
  18931. Used by the getFullFrameParameters() and fullFrame() methods.
  18932. */
  18933. enum SmpteTimecodeType
  18934. {
  18935. fps24 = 0,
  18936. fps25 = 1,
  18937. fps30drop = 2,
  18938. fps30 = 3
  18939. };
  18940. /** Returns true if this is a full-frame midi timecode message.
  18941. */
  18942. bool isFullFrame() const throw();
  18943. /** Extracts the timecode information from a full-frame midi timecode message.
  18944. You should only call this on messages where you've used isFullFrame() to
  18945. check that they're the right kind.
  18946. */
  18947. void getFullFrameParameters (int& hours,
  18948. int& minutes,
  18949. int& seconds,
  18950. int& frames,
  18951. SmpteTimecodeType& timecodeType) const throw();
  18952. /** Creates a full-frame MTC message.
  18953. */
  18954. static const MidiMessage fullFrame (const int hours,
  18955. const int minutes,
  18956. const int seconds,
  18957. const int frames,
  18958. SmpteTimecodeType timecodeType);
  18959. /** Types of MMC command.
  18960. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  18961. */
  18962. enum MidiMachineControlCommand
  18963. {
  18964. mmc_stop = 1,
  18965. mmc_play = 2,
  18966. mmc_deferredplay = 3,
  18967. mmc_fastforward = 4,
  18968. mmc_rewind = 5,
  18969. mmc_recordStart = 6,
  18970. mmc_recordStop = 7,
  18971. mmc_pause = 9
  18972. };
  18973. /** Checks whether this is an MMC message.
  18974. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  18975. */
  18976. bool isMidiMachineControlMessage() const throw();
  18977. /** For an MMC message, this returns its type.
  18978. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  18979. calling this method.
  18980. */
  18981. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  18982. /** Creates an MMC message.
  18983. */
  18984. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  18985. /** Checks whether this is an MMC "goto" message.
  18986. If it is, the parameters passed-in are set to the time that the message contains.
  18987. @see midiMachineControlGoto
  18988. */
  18989. bool isMidiMachineControlGoto (int& hours,
  18990. int& minutes,
  18991. int& seconds,
  18992. int& frames) const throw();
  18993. /** Creates an MMC "goto" message.
  18994. This messages tells the device to go to a specific frame.
  18995. @see isMidiMachineControlGoto
  18996. */
  18997. static const MidiMessage midiMachineControlGoto (int hours,
  18998. int minutes,
  18999. int seconds,
  19000. int frames);
  19001. /** Creates a master-volume change message.
  19002. @param volume the volume, 0 to 1.0
  19003. */
  19004. static const MidiMessage masterVolume (const float volume) throw();
  19005. /** Creates a system-exclusive message.
  19006. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19007. */
  19008. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19009. const int dataSize) throw();
  19010. /** Reads a midi variable-length integer.
  19011. @param data the data to read the number from
  19012. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19013. */
  19014. static int readVariableLengthVal (const uint8* data,
  19015. int& numBytesUsed) throw();
  19016. /** Based on the first byte of a short midi message, this uses a lookup table
  19017. to return the message length (either 1, 2, or 3 bytes).
  19018. The value passed in must be 0x80 or higher.
  19019. */
  19020. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19021. /** Returns the name of a midi note number.
  19022. E.g "C", "D#", etc.
  19023. @param noteNumber the midi note number, 0 to 127
  19024. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19025. they'll be flattened, e.g. "Db"
  19026. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19027. e.g. "C#4"
  19028. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19029. number that will be used for middle C's octave
  19030. @see getMidiNoteInHertz
  19031. */
  19032. static const String getMidiNoteName (int noteNumber,
  19033. bool useSharps,
  19034. bool includeOctaveNumber,
  19035. int octaveNumForMiddleC) throw();
  19036. /** Returns the frequency of a midi note number.
  19037. @see getMidiNoteName
  19038. */
  19039. static const double getMidiNoteInHertz (int noteNumber) throw();
  19040. /** Returns the standard name of a GM instrument.
  19041. @param midiInstrumentNumber the program number 0 to 127
  19042. @see getProgramChangeNumber
  19043. */
  19044. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19045. /** Returns the name of a bank of GM instruments.
  19046. @param midiBankNumber the bank, 0 to 15
  19047. */
  19048. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19049. /** Returns the standard name of a channel 10 percussion sound.
  19050. @param midiNoteNumber the key number, 35 to 81
  19051. */
  19052. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19053. /** Returns the name of a controller type number.
  19054. @see getControllerNumber
  19055. */
  19056. static const String getControllerName (int controllerNumber) throw();
  19057. juce_UseDebuggingNewOperator
  19058. private:
  19059. double timeStamp;
  19060. uint8* data;
  19061. int message, size;
  19062. };
  19063. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19064. /********* End of inlined file: juce_MidiMessage.h *********/
  19065. /**
  19066. Holds a sequence of time-stamped midi events.
  19067. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19068. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19069. @see MidiMessage
  19070. */
  19071. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19072. {
  19073. public:
  19074. /** Creates an empty MidiBuffer. */
  19075. MidiBuffer() throw();
  19076. /** Creates a copy of another MidiBuffer. */
  19077. MidiBuffer (const MidiBuffer& other) throw();
  19078. /** Makes a copy of another MidiBuffer. */
  19079. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19080. /** Destructor */
  19081. ~MidiBuffer() throw();
  19082. /** Removes all events from the buffer. */
  19083. void clear() throw();
  19084. /** Removes all events between two times from the buffer.
  19085. All events for which (start <= event position < start + numSamples) will
  19086. be removed.
  19087. */
  19088. void clear (const int start,
  19089. const int numSamples) throw();
  19090. /** Returns true if the buffer is empty.
  19091. To actually retrieve the events, use a MidiBuffer::Iterator object
  19092. */
  19093. bool isEmpty() const throw();
  19094. /** Counts the number of events in the buffer.
  19095. This is actually quite a slow operation, as it has to iterate through all
  19096. the events, so you might prefer to call isEmpty() if that's all you need
  19097. to know.
  19098. */
  19099. int getNumEvents() const throw();
  19100. /** Adds an event to the buffer.
  19101. The sample number will be used to determine the position of the event in
  19102. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19103. ignored.
  19104. If an event is added whose sample position is the same as one or more events
  19105. already in the buffer, the new event will be placed after the existing ones.
  19106. To retrieve events, use a MidiBuffer::Iterator object
  19107. */
  19108. void addEvent (const MidiMessage& midiMessage,
  19109. const int sampleNumber) throw();
  19110. /** Adds an event to the buffer from raw midi data.
  19111. The sample number will be used to determine the position of the event in
  19112. the buffer, which is always kept sorted.
  19113. If an event is added whose sample position is the same as one or more events
  19114. already in the buffer, the new event will be placed after the existing ones.
  19115. The event data will be inspected to calculate the number of bytes in length that
  19116. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19117. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19118. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19119. add an event at all.
  19120. To retrieve events, use a MidiBuffer::Iterator object
  19121. */
  19122. void addEvent (const uint8* const rawMidiData,
  19123. const int maxBytesOfMidiData,
  19124. const int sampleNumber) throw();
  19125. /** Adds some events from another buffer to this one.
  19126. @param otherBuffer the buffer containing the events you want to add
  19127. @param startSample the lowest sample number in the source buffer for which
  19128. events should be added. Any source events whose timestamp is
  19129. less than this will be ignored
  19130. @param numSamples the valid range of samples from the source buffer for which
  19131. events should be added - i.e. events in the source buffer whose
  19132. timestamp is greater than or equal to (startSample + numSamples)
  19133. will be ignored. If this value is less than 0, all events after
  19134. startSample will be taken.
  19135. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19136. that are added to this buffer
  19137. */
  19138. void addEvents (const MidiBuffer& otherBuffer,
  19139. const int startSample,
  19140. const int numSamples,
  19141. const int sampleDeltaToAdd) throw();
  19142. /** Returns the sample number of the first event in the buffer.
  19143. If the buffer's empty, this will just return 0.
  19144. */
  19145. int getFirstEventTime() const throw();
  19146. /** Returns the sample number of the last event in the buffer.
  19147. If the buffer's empty, this will just return 0.
  19148. */
  19149. int getLastEventTime() const throw();
  19150. /**
  19151. Used to iterate through the events in a MidiBuffer.
  19152. Note that altering the buffer while an iterator is using it isn't a
  19153. safe operation.
  19154. @see MidiBuffer
  19155. */
  19156. class Iterator
  19157. {
  19158. public:
  19159. /** Creates an Iterator for this MidiBuffer. */
  19160. Iterator (const MidiBuffer& buffer) throw();
  19161. /** Destructor. */
  19162. ~Iterator() throw();
  19163. /** Repositions the iterator so that the next event retrieved will be the first
  19164. one whose sample position is at greater than or equal to the given position.
  19165. */
  19166. void setNextSamplePosition (const int samplePosition) throw();
  19167. /** Retrieves a copy of the next event from the buffer.
  19168. @param result on return, this will be the message (the MidiMessage's timestamp
  19169. is not set)
  19170. @param samplePosition on return, this will be the position of the event
  19171. @returns true if an event was found, or false if the iterator has reached
  19172. the end of the buffer
  19173. */
  19174. bool getNextEvent (MidiMessage& result,
  19175. int& samplePosition) throw();
  19176. /** Retrieves the next event from the buffer.
  19177. @param midiData on return, this pointer will be set to a block of data containing
  19178. the midi message. Note that to make it fast, this is a pointer
  19179. directly into the MidiBuffer's internal data, so is only valid
  19180. temporarily until the MidiBuffer is altered.
  19181. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19182. midi message
  19183. @param samplePosition on return, this will be the position of the event
  19184. @returns true if an event was found, or false if the iterator has reached
  19185. the end of the buffer
  19186. */
  19187. bool getNextEvent (const uint8* &midiData,
  19188. int& numBytesOfMidiData,
  19189. int& samplePosition) throw();
  19190. juce_UseDebuggingNewOperator
  19191. private:
  19192. const MidiBuffer& buffer;
  19193. const uint8* data;
  19194. Iterator (const Iterator&);
  19195. const Iterator& operator= (const Iterator&);
  19196. };
  19197. juce_UseDebuggingNewOperator
  19198. private:
  19199. friend class MidiBuffer::Iterator;
  19200. int bytesUsed;
  19201. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19202. };
  19203. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19204. /********* End of inlined file: juce_MidiBuffer.h *********/
  19205. #endif
  19206. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19207. /********* Start of inlined file: juce_MidiFile.h *********/
  19208. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19209. #define __JUCE_MIDIFILE_JUCEHEADER__
  19210. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19211. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19212. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19213. /**
  19214. A sequence of timestamped midi messages.
  19215. This allows the sequence to be manipulated, and also to be read from and
  19216. written to a standard midi file.
  19217. @see MidiMessage, MidiFile
  19218. */
  19219. class JUCE_API MidiMessageSequence
  19220. {
  19221. public:
  19222. /** Creates an empty midi sequence object. */
  19223. MidiMessageSequence();
  19224. /** Creates a copy of another sequence. */
  19225. MidiMessageSequence (const MidiMessageSequence& other);
  19226. /** Replaces this sequence with another one. */
  19227. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19228. /** Destructor. */
  19229. ~MidiMessageSequence();
  19230. /** Structure used to hold midi events in the sequence.
  19231. These structures act as 'handles' on the events as they are moved about in
  19232. the list, and make it quick to find the matching note-offs for note-on events.
  19233. @see MidiMessageSequence::getEventPointer
  19234. */
  19235. class MidiEventHolder
  19236. {
  19237. public:
  19238. /** Destructor. */
  19239. ~MidiEventHolder();
  19240. /** The message itself, whose timestamp is used to specify the event's time.
  19241. */
  19242. MidiMessage message;
  19243. /** The matching note-off event (if this is a note-on event).
  19244. If this isn't a note-on, this pointer will be null.
  19245. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19246. note-offs up-to-date after events have been moved around in the sequence
  19247. or deleted.
  19248. */
  19249. MidiEventHolder* noteOffObject;
  19250. juce_UseDebuggingNewOperator
  19251. private:
  19252. friend class MidiMessageSequence;
  19253. MidiEventHolder (const MidiMessage& message);
  19254. };
  19255. /** Clears the sequence. */
  19256. void clear();
  19257. /** Returns the number of events in the sequence. */
  19258. int getNumEvents() const;
  19259. /** Returns a pointer to one of the events. */
  19260. MidiEventHolder* getEventPointer (const int index) const;
  19261. /** Returns the time of the note-up that matches the note-on at this index.
  19262. If the event at this index isn't a note-on, it'll just return 0.
  19263. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19264. */
  19265. double getTimeOfMatchingKeyUp (const int index) const;
  19266. /** Returns the index of the note-up that matches the note-on at this index.
  19267. If the event at this index isn't a note-on, it'll just return -1.
  19268. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19269. */
  19270. int getIndexOfMatchingKeyUp (const int index) const;
  19271. /** Returns the index of an event. */
  19272. int getIndexOf (MidiEventHolder* const event) const;
  19273. /** Returns the index of the first event on or after the given timestamp.
  19274. If the time is beyond the end of the sequence, this will return the
  19275. number of events.
  19276. */
  19277. int getNextIndexAtTime (const double timeStamp) const;
  19278. /** Returns the timestamp of the first event in the sequence.
  19279. @see getEndTime
  19280. */
  19281. double getStartTime() const;
  19282. /** Returns the timestamp of the last event in the sequence.
  19283. @see getStartTime
  19284. */
  19285. double getEndTime() const;
  19286. /** Returns the timestamp of the event at a given index.
  19287. If the index is out-of-range, this will return 0.0
  19288. */
  19289. double getEventTime (const int index) const;
  19290. /** Inserts a midi message into the sequence.
  19291. The index at which the new message gets inserted will depend on its timestamp,
  19292. because the sequence is kept sorted.
  19293. Remember to call updateMatchedPairs() after adding note-on events.
  19294. @param newMessage the new message to add (an internal copy will be made)
  19295. @param timeAdjustment an optional value to add to the timestamp of the message
  19296. that will be inserted
  19297. @see updateMatchedPairs
  19298. */
  19299. void addEvent (const MidiMessage& newMessage,
  19300. double timeAdjustment = 0);
  19301. /** Deletes one of the events in the sequence.
  19302. Remember to call updateMatchedPairs() after removing events.
  19303. @param index the index of the event to delete
  19304. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19305. if the event you're removing is a note-on
  19306. */
  19307. void deleteEvent (const int index,
  19308. const bool deleteMatchingNoteUp);
  19309. /** Merges another sequence into this one.
  19310. Remember to call updateMatchedPairs() after using this method.
  19311. @param other the sequence to add from
  19312. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19313. as they are read from the other sequence
  19314. @param firstAllowableDestTime events will not be added if their time is earlier
  19315. than this time. (This is after their time has been adjusted
  19316. by the timeAdjustmentDelta)
  19317. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19318. or greater than this time. (This is after their time has
  19319. been adjusted by the timeAdjustmentDelta)
  19320. */
  19321. void addSequence (const MidiMessageSequence& other,
  19322. double timeAdjustmentDelta,
  19323. double firstAllowableDestTime,
  19324. double endOfAllowableDestTimes);
  19325. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19326. Call this after moving messages about or deleting/adding messages, and it
  19327. will scan the list and make sure all the note-offs in the MidiEventHolder
  19328. structures are pointing at the correct ones.
  19329. */
  19330. void updateMatchedPairs();
  19331. /** Copies all the messages for a particular midi channel to another sequence.
  19332. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19333. @param destSequence the sequence that the chosen events should be copied to
  19334. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19335. channel) will also be copied across.
  19336. @see extractSysExMessages
  19337. */
  19338. void extractMidiChannelMessages (const int channelNumberToExtract,
  19339. MidiMessageSequence& destSequence,
  19340. const bool alsoIncludeMetaEvents) const;
  19341. /** Copies all midi sys-ex messages to another sequence.
  19342. @param destSequence this is the sequence to which any sys-exes in this sequence
  19343. will be added
  19344. @see extractMidiChannelMessages
  19345. */
  19346. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19347. /** Removes any messages in this sequence that have a specific midi channel.
  19348. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19349. */
  19350. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19351. /** Removes any sys-ex messages from this sequence.
  19352. */
  19353. void deleteSysExMessages();
  19354. /** Adds an offset to the timestamps of all events in the sequence.
  19355. @param deltaTime the amount to add to each timestamp.
  19356. */
  19357. void addTimeToMessages (const double deltaTime);
  19358. /** Scans through the sequence to determine the state of any midi controllers at
  19359. a given time.
  19360. This will create a sequence of midi controller changes that can be
  19361. used to set all midi controllers to the state they would be in at the
  19362. specified time within this sequence.
  19363. As well as controllers, it will also recreate the midi program number
  19364. and pitch bend position.
  19365. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19366. for other channels will be ignored.
  19367. @param time the time at which you want to find out the state - there are
  19368. no explicit units for this time measurement, it's the same units
  19369. as used for the timestamps of the messages
  19370. @param resultMessages an array to which midi controller-change messages will be added. This
  19371. will be the minimum number of controller changes to recreate the
  19372. state at the required time.
  19373. */
  19374. void createControllerUpdatesForTime (const int channelNumber,
  19375. const double time,
  19376. OwnedArray<MidiMessage>& resultMessages);
  19377. juce_UseDebuggingNewOperator
  19378. /** @internal */
  19379. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19380. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19381. private:
  19382. friend class MidiComparator;
  19383. friend class MidiFile;
  19384. OwnedArray <MidiEventHolder> list;
  19385. void sort();
  19386. };
  19387. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19388. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19389. /**
  19390. Reads/writes standard midi format files.
  19391. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19392. can then get the individual midi tracks from it using the getTrack() method.
  19393. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19394. to it using the addTrack() method, and then call its writeTo() method to stream
  19395. it out.
  19396. @see MidiMessageSequence
  19397. */
  19398. class JUCE_API MidiFile
  19399. {
  19400. public:
  19401. /** Creates an empty MidiFile object.
  19402. */
  19403. MidiFile() throw();
  19404. /** Destructor. */
  19405. ~MidiFile() throw();
  19406. /** Returns the number of tracks in the file.
  19407. @see getTrack, addTrack
  19408. */
  19409. int getNumTracks() const throw();
  19410. /** Returns a pointer to one of the tracks in the file.
  19411. @returns a pointer to the track, or 0 if the index is out-of-range
  19412. @see getNumTracks, addTrack
  19413. */
  19414. const MidiMessageSequence* getTrack (const int index) const throw();
  19415. /** Adds a midi track to the file.
  19416. This will make its own internal copy of the sequence that is passed-in.
  19417. @see getNumTracks, getTrack
  19418. */
  19419. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19420. /** Removes all midi tracks from the file.
  19421. @see getNumTracks
  19422. */
  19423. void clear() throw();
  19424. /** Returns the raw time format code that will be written to a stream.
  19425. After reading a midi file, this method will return the time-format that
  19426. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19427. or setSmpteTimeFormat() methods.
  19428. If the value returned is positive, it indicates the number of midi ticks
  19429. per quarter-note - see setTicksPerQuarterNote().
  19430. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19431. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19432. */
  19433. short getTimeFormat() const throw();
  19434. /** Sets the time format to use when this file is written to a stream.
  19435. If this is called, the file will be written as bars/beats using the
  19436. specified resolution, rather than SMPTE absolute times, as would be
  19437. used if setSmpteTimeFormat() had been called instead.
  19438. @param ticksPerQuarterNote e.g. 96, 960
  19439. @see setSmpteTimeFormat
  19440. */
  19441. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19442. /** Sets the time format to use when this file is written to a stream.
  19443. If this is called, the file will be written using absolute times, rather
  19444. than bars/beats as would be the case if setTicksPerBeat() had been called
  19445. instead.
  19446. @param framesPerSecond must be 24, 25, 29 or 30
  19447. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19448. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19449. timing, setSmpteTimeFormat (25, 40)
  19450. @see setTicksPerBeat
  19451. */
  19452. void setSmpteTimeFormat (const int framesPerSecond,
  19453. const int subframeResolution) throw();
  19454. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19455. Useful for finding the positions of all the tempo changes in a file.
  19456. @param tempoChangeEvents a list to which all the events will be added
  19457. */
  19458. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19459. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19460. Useful for finding the positions of all the tempo changes in a file.
  19461. @param timeSigEvents a list to which all the events will be added
  19462. */
  19463. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19464. /** Returns the latest timestamp in any of the tracks.
  19465. (Useful for finding the length of the file).
  19466. */
  19467. double getLastTimestamp() const;
  19468. /** Reads a midi file format stream.
  19469. After calling this, you can get the tracks that were read from the file by using the
  19470. getNumTracks() and getTrack() methods.
  19471. The timestamps of the midi events in the tracks will represent their positions in
  19472. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19473. method.
  19474. @returns true if the stream was read successfully
  19475. */
  19476. bool readFrom (InputStream& sourceStream);
  19477. /** Writes the midi tracks as a standard midi file.
  19478. @returns true if the operation succeeded.
  19479. */
  19480. bool writeTo (OutputStream& destStream);
  19481. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19482. This will use the midi time format and tempo/time signature info in the
  19483. tracks to convert all the timestamps to absolute values in seconds.
  19484. */
  19485. void convertTimestampTicksToSeconds();
  19486. juce_UseDebuggingNewOperator
  19487. /** @internal */
  19488. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19489. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19490. private:
  19491. MidiMessageSequence* tracks [128];
  19492. short numTracks, timeFormat;
  19493. MidiFile (const MidiFile&);
  19494. const MidiFile& operator= (const MidiFile&);
  19495. void readNextTrack (const char* data, int size);
  19496. void writeTrack (OutputStream& mainOut, const int trackNum);
  19497. };
  19498. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19499. /********* End of inlined file: juce_MidiFile.h *********/
  19500. #endif
  19501. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19502. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19503. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19504. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19505. class MidiKeyboardState;
  19506. /**
  19507. Receives events from a MidiKeyboardState object.
  19508. @see MidiKeyboardState
  19509. */
  19510. class JUCE_API MidiKeyboardStateListener
  19511. {
  19512. public:
  19513. MidiKeyboardStateListener() throw() {}
  19514. virtual ~MidiKeyboardStateListener() {}
  19515. /** Called when one of the MidiKeyboardState's keys is pressed.
  19516. This will be called synchronously when the state is either processing a
  19517. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19518. when a note is being played with its MidiKeyboardState::noteOn() method.
  19519. Note that this callback could happen from an audio callback thread, so be
  19520. careful not to block, and avoid any UI activity in the callback.
  19521. */
  19522. virtual void handleNoteOn (MidiKeyboardState* source,
  19523. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19524. /** Called when one of the MidiKeyboardState's keys is released.
  19525. This will be called synchronously when the state is either processing a
  19526. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19527. when a note is being played with its MidiKeyboardState::noteOff() method.
  19528. Note that this callback could happen from an audio callback thread, so be
  19529. careful not to block, and avoid any UI activity in the callback.
  19530. */
  19531. virtual void handleNoteOff (MidiKeyboardState* source,
  19532. int midiChannel, int midiNoteNumber) = 0;
  19533. };
  19534. /**
  19535. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19536. This object can parse a stream of midi events, using them to update its idea
  19537. of which keys are pressed for each individiual midi channel.
  19538. When keys go up or down, it can broadcast these events to listener objects.
  19539. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19540. methods, and midi messages for these events will be merged into the
  19541. midi stream that gets processed by processNextMidiBuffer().
  19542. */
  19543. class JUCE_API MidiKeyboardState
  19544. {
  19545. public:
  19546. MidiKeyboardState();
  19547. ~MidiKeyboardState();
  19548. /** Resets the state of the object.
  19549. All internal data for all the channels is reset, but no events are sent as a
  19550. result.
  19551. If you want to release any keys that are currently down, and to send out note-up
  19552. midi messages for this, use the allNotesOff() method instead.
  19553. */
  19554. void reset();
  19555. /** Returns true if the given midi key is currently held down for the given midi channel.
  19556. The channel number must be between 1 and 16. If you want to see if any notes are
  19557. on for a range of channels, use the isNoteOnForChannels() method.
  19558. */
  19559. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19560. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19561. The channel mask has a bit set for each midi channel you want to test for - bit
  19562. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19563. If a note is on for at least one of the specified channels, this returns true.
  19564. */
  19565. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19566. /** Turns a specified note on.
  19567. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19568. next call to processNextMidiBuffer().
  19569. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19570. gone down.
  19571. */
  19572. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19573. /** Turns a specified note off.
  19574. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19575. next call to processNextMidiBuffer().
  19576. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19577. gone up.
  19578. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19579. */
  19580. void noteOff (const int midiChannel, const int midiNoteNumber);
  19581. /** This will turn off any currently-down notes for the given midi channel.
  19582. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19583. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19584. and events being added to the midi stream.
  19585. */
  19586. void allNotesOff (const int midiChannel);
  19587. /** Looks at a key-up/down event and uses it to update the state of this object.
  19588. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19589. instead.
  19590. */
  19591. void processNextMidiEvent (const MidiMessage& message);
  19592. /** Scans a midi stream for up/down events and adds its own events to it.
  19593. This will look for any up/down events and use them to update the internal state,
  19594. synchronously making suitable callbacks to the listeners.
  19595. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19596. and noteOff() calls will be added into the buffer.
  19597. Only the section of the buffer whose timestamps are between startSample and
  19598. (startSample + numSamples) will be affected, and any events added will be placed
  19599. between these times.
  19600. If you're going to use this method, you'll need to keep calling it regularly for
  19601. it to work satisfactorily.
  19602. To process a single midi event at a time, use the processNextMidiEvent() method
  19603. instead.
  19604. */
  19605. void processNextMidiBuffer (MidiBuffer& buffer,
  19606. const int startSample,
  19607. const int numSamples,
  19608. const bool injectIndirectEvents);
  19609. /** Registers a listener for callbacks when keys go up or down.
  19610. @see removeListener
  19611. */
  19612. void addListener (MidiKeyboardStateListener* const listener) throw();
  19613. /** Deregisters a listener.
  19614. @see addListener
  19615. */
  19616. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19617. juce_UseDebuggingNewOperator
  19618. private:
  19619. CriticalSection lock;
  19620. uint16 noteStates [128];
  19621. MidiBuffer eventsToAdd;
  19622. VoidArray listeners;
  19623. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19624. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19625. MidiKeyboardState (const MidiKeyboardState&);
  19626. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19627. };
  19628. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19629. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19630. #endif
  19631. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19632. #endif
  19633. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19634. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19635. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19636. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19637. /********* Start of inlined file: juce_MidiInput.h *********/
  19638. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19639. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19640. class MidiInput;
  19641. /**
  19642. Receives midi messages from a midi input device.
  19643. This class is overridden to handle incoming midi messages. See the MidiInput
  19644. class for more details.
  19645. @see MidiInput
  19646. */
  19647. class JUCE_API MidiInputCallback
  19648. {
  19649. public:
  19650. /** Destructor. */
  19651. virtual ~MidiInputCallback() {}
  19652. /** Receives an incoming message.
  19653. A MidiInput object will call this method when a midi event arrives. It'll be
  19654. called on a high-priority system thread, so avoid doing anything time-consuming
  19655. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19656. for queueing incoming messages for use later.
  19657. @param source the MidiInput object that generated the message
  19658. @param message the incoming message. The message's timestamp is set to a value
  19659. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19660. time when the message arrived.
  19661. */
  19662. virtual void handleIncomingMidiMessage (MidiInput* source,
  19663. const MidiMessage& message) = 0;
  19664. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19665. If a long sysex message is broken up into multiple packets, this callback is made
  19666. for each packet that arrives until the message is finished, at which point
  19667. the normal handleIncomingMidiMessage() callback will be made with the entire
  19668. message.
  19669. The message passed in will contain the start of a sysex, but won't be finished
  19670. with the terminating 0xf7 byte.
  19671. */
  19672. virtual void handlePartialSysexMessage (MidiInput* source,
  19673. const uint8* messageData,
  19674. const int numBytesSoFar,
  19675. const double timestamp)
  19676. {
  19677. // (this bit is just to avoid compiler warnings about unused variables)
  19678. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19679. }
  19680. };
  19681. /**
  19682. Represents a midi input device.
  19683. To create one of these, use the static getDevices() method to find out what inputs are
  19684. available, and then use the openDevice() method to try to open one.
  19685. @see MidiOutput
  19686. */
  19687. class JUCE_API MidiInput
  19688. {
  19689. public:
  19690. /** Returns a list of the available midi input devices.
  19691. You can open one of the devices by passing its index into the
  19692. openDevice() method.
  19693. @see getDefaultDeviceIndex, openDevice
  19694. */
  19695. static const StringArray getDevices();
  19696. /** Returns the index of the default midi input device to use.
  19697. This refers to the index in the list returned by getDevices().
  19698. */
  19699. static int getDefaultDeviceIndex();
  19700. /** Tries to open one of the midi input devices.
  19701. This will return a MidiInput object if it manages to open it. You can then
  19702. call start() and stop() on this device, and delete it when no longer needed.
  19703. If the device can't be opened, this will return a null pointer.
  19704. @param deviceIndex the index of a device from the list returned by getDevices()
  19705. @param callback the object that will receive the midi messages from this device.
  19706. @see MidiInputCallback, getDevices
  19707. */
  19708. static MidiInput* openDevice (int deviceIndex,
  19709. MidiInputCallback* callback);
  19710. #if JUCE_LINUX || DOXYGEN
  19711. /** LINUX ONLY - This will try to create a new midi input device.
  19712. This will attempt to create a new midi input device with the specified name,
  19713. for other apps to connect to.
  19714. Returns 0 if a device can't be created.
  19715. @param deviceName the name to use for the new device
  19716. @param callback the object that will receive the midi messages from this device.
  19717. */
  19718. static MidiInput* createNewDevice (const String& deviceName,
  19719. MidiInputCallback* callback);
  19720. #endif
  19721. /** Destructor. */
  19722. ~MidiInput();
  19723. /** Returns the name of this device.
  19724. */
  19725. const String getName() const throw() { return name; }
  19726. /** Allows you to set a custom name for the device, in case you don't like the name
  19727. it was given when created.
  19728. */
  19729. void setName (const String& newName) throw() { name = newName; }
  19730. /** Starts the device running.
  19731. After calling this, the device will start sending midi messages to the
  19732. MidiInputCallback object that was specified when the openDevice() method
  19733. was called.
  19734. @see stop
  19735. */
  19736. void start();
  19737. /** Stops the device running.
  19738. @see start
  19739. */
  19740. void stop();
  19741. juce_UseDebuggingNewOperator
  19742. private:
  19743. String name;
  19744. void* internal;
  19745. MidiInput (const String& name);
  19746. MidiInput (const MidiInput&);
  19747. };
  19748. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19749. /********* End of inlined file: juce_MidiInput.h *********/
  19750. /**
  19751. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19752. processing by a block-based audio callback.
  19753. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19754. so it can easily use a midi input or keyboard component as its source.
  19755. @see MidiMessage, MidiInput
  19756. */
  19757. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19758. public MidiInputCallback
  19759. {
  19760. public:
  19761. /** Creates a MidiMessageCollector. */
  19762. MidiMessageCollector();
  19763. /** Destructor. */
  19764. ~MidiMessageCollector();
  19765. /** Clears any messages from the queue.
  19766. You need to call this method before starting to use the collector, so that
  19767. it knows the correct sample rate to use.
  19768. */
  19769. void reset (const double sampleRate);
  19770. /** Takes an incoming real-time message and adds it to the queue.
  19771. The message's timestamp is taken, and it will be ready for retrieval as part
  19772. of the block returned by the next call to removeNextBlockOfMessages().
  19773. This method is fully thread-safe when overlapping calls are made with
  19774. removeNextBlockOfMessages().
  19775. */
  19776. void addMessageToQueue (const MidiMessage& message);
  19777. /** Removes all the pending messages from the queue as a buffer.
  19778. This will also correct the messages' timestamps to make sure they're in
  19779. the range 0 to numSamples - 1.
  19780. This call should be made regularly by something like an audio processing
  19781. callback, because the time that it happens is used in calculating the
  19782. midi event positions.
  19783. This method is fully thread-safe when overlapping calls are made with
  19784. addMessageToQueue().
  19785. */
  19786. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19787. const int numSamples);
  19788. /** @internal */
  19789. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19790. /** @internal */
  19791. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19792. /** @internal */
  19793. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19794. juce_UseDebuggingNewOperator
  19795. private:
  19796. double lastCallbackTime;
  19797. CriticalSection midiCallbackLock;
  19798. MidiBuffer incomingMessages;
  19799. double sampleRate;
  19800. MidiMessageCollector (const MidiMessageCollector&);
  19801. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19802. };
  19803. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19804. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19805. #endif
  19806. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19807. #endif
  19808. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19809. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19810. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19811. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19812. /**
  19813. A set of routines to convert buffers of 32-bit floating point data to and from
  19814. various integer formats.
  19815. */
  19816. class JUCE_API AudioDataConverters
  19817. {
  19818. public:
  19819. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19820. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19821. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19822. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19823. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19824. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19825. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19826. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19827. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19828. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19829. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19830. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19831. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19832. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19833. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19834. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19835. enum DataFormat
  19836. {
  19837. int16LE,
  19838. int16BE,
  19839. int24LE,
  19840. int24BE,
  19841. int32LE,
  19842. int32BE,
  19843. float32LE,
  19844. float32BE,
  19845. };
  19846. static void convertFloatToFormat (const DataFormat destFormat,
  19847. const float* source, void* dest, int numSamples);
  19848. static void convertFormatToFloat (const DataFormat sourceFormat,
  19849. const void* source, float* dest, int numSamples);
  19850. static void interleaveSamples (const float** source, float* dest,
  19851. const int numSamples, const int numChannels);
  19852. static void deinterleaveSamples (const float* source, float** dest,
  19853. const int numSamples, const int numChannels);
  19854. };
  19855. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19856. /********* End of inlined file: juce_AudioDataConverters.h *********/
  19857. #endif
  19858. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19859. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  19860. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19861. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19862. class AudioFormatReader;
  19863. class AudioFormatWriter;
  19864. /**
  19865. A multi-channel buffer of 32-bit floating point audio samples.
  19866. */
  19867. class JUCE_API AudioSampleBuffer
  19868. {
  19869. public:
  19870. /** Creates a buffer with a specified number of channels and samples.
  19871. The contents of the buffer will initially be undefined, so use clear() to
  19872. set all the samples to zero.
  19873. The buffer will allocate its memory internally, and this will be released
  19874. when the buffer is deleted.
  19875. */
  19876. AudioSampleBuffer (const int numChannels,
  19877. const int numSamples) throw();
  19878. /** Creates a buffer using a pre-allocated block of memory.
  19879. Note that if the buffer is resized or its number of channels is changed, it
  19880. will re-allocate memory internally and copy the existing data to this new area,
  19881. so it will then stop directly addressing this memory.
  19882. @param dataToReferTo a pre-allocated array containing pointers to the data
  19883. for each channel that should be used by this buffer. The
  19884. buffer will only refer to this memory, it won't try to delete
  19885. it when the buffer is deleted or resized.
  19886. @param numChannels the number of channels to use - this must correspond to the
  19887. number of elements in the array passed in
  19888. @param numSamples the number of samples to use - this must correspond to the
  19889. size of the arrays passed in
  19890. */
  19891. AudioSampleBuffer (float** dataToReferTo,
  19892. const int numChannels,
  19893. const int numSamples) throw();
  19894. /** Copies another buffer.
  19895. This buffer will make its own copy of the other's data, unless the buffer was created
  19896. using an external data buffer, in which case boths buffers will just point to the same
  19897. shared block of data.
  19898. */
  19899. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  19900. /** Copies another buffer onto this one.
  19901. This buffer's size will be changed to that of the other buffer.
  19902. */
  19903. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  19904. /** Destructor.
  19905. This will free any memory allocated by the buffer.
  19906. */
  19907. virtual ~AudioSampleBuffer() throw();
  19908. /** Returns the number of channels of audio data that this buffer contains.
  19909. @see getSampleData
  19910. */
  19911. int getNumChannels() const throw() { return numChannels; }
  19912. /** Returns the number of samples allocated in each of the buffer's channels.
  19913. @see getSampleData
  19914. */
  19915. int getNumSamples() const throw() { return size; }
  19916. /** Returns a pointer to a sample in one of the buffer's channels.
  19917. For speed, this doesn't check whether the channel and sample number
  19918. are legal, so be careful when using it!
  19919. */
  19920. float* getSampleData (const int channelNumber,
  19921. const int sampleOffset = 0) const throw();
  19922. /** Chages the buffer's size or number of channels.
  19923. This can expand or contract the buffer's length, and add or remove channels.
  19924. If keepExistingContent is true, it will try to preserve as much of the
  19925. old data as it can in the new buffer.
  19926. If clearExtraSpace is true, then any extra channels or space that is
  19927. allocated will be also be cleared. If false, then this space is left
  19928. uninitialised.
  19929. If avoidReallocating is true, then changing the buffer's size won't reduce the
  19930. amount of memory that is currently allocated (but it will still increase it if
  19931. the new size is bigger than the amount it currently has). If this is false, then
  19932. a new allocation will be done so that the buffer uses takes up the minimum amount
  19933. of memory that it needs.
  19934. */
  19935. void setSize (const int newNumChannels,
  19936. const int newNumSamples,
  19937. const bool keepExistingContent = false,
  19938. const bool clearExtraSpace = false,
  19939. const bool avoidReallocating = false) throw();
  19940. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  19941. There's also a constructor that lets you specify arrays like this, but this
  19942. lets you change the channels dynamically.
  19943. Note that if the buffer is resized or its number of channels is changed, it
  19944. will re-allocate memory internally and copy the existing data to this new area,
  19945. so it will then stop directly addressing this memory.
  19946. @param dataToReferTo a pre-allocated array containing pointers to the data
  19947. for each channel that should be used by this buffer. The
  19948. buffer will only refer to this memory, it won't try to delete
  19949. it when the buffer is deleted or resized.
  19950. @param numChannels the number of channels to use - this must correspond to the
  19951. number of elements in the array passed in
  19952. @param numSamples the number of samples to use - this must correspond to the
  19953. size of the arrays passed in
  19954. */
  19955. void setDataToReferTo (float** dataToReferTo,
  19956. const int numChannels,
  19957. const int numSamples) throw();
  19958. /** Clears all the samples in all channels. */
  19959. void clear() throw();
  19960. /** Clears a specified region of all the channels.
  19961. For speed, this doesn't check whether the channel and sample number
  19962. are in-range, so be careful!
  19963. */
  19964. void clear (const int startSample,
  19965. const int numSamples) throw();
  19966. /** Clears a specified region of just one channel.
  19967. For speed, this doesn't check whether the channel and sample number
  19968. are in-range, so be careful!
  19969. */
  19970. void clear (const int channel,
  19971. const int startSample,
  19972. const int numSamples) throw();
  19973. /** Applies a gain multiple to a region of one channel.
  19974. For speed, this doesn't check whether the channel and sample number
  19975. are in-range, so be careful!
  19976. */
  19977. void applyGain (const int channel,
  19978. const int startSample,
  19979. int numSamples,
  19980. const float gain) throw();
  19981. /** Applies a gain multiple to a region of all the channels.
  19982. For speed, this doesn't check whether the sample numbers
  19983. are in-range, so be careful!
  19984. */
  19985. void applyGain (const int startSample,
  19986. const int numSamples,
  19987. const float gain) throw();
  19988. /** Applies a range of gains to a region of a channel.
  19989. The gain that is applied to each sample will vary from
  19990. startGain on the first sample to endGain on the last Sample,
  19991. so it can be used to do basic fades.
  19992. For speed, this doesn't check whether the sample numbers
  19993. are in-range, so be careful!
  19994. */
  19995. void applyGainRamp (const int channel,
  19996. const int startSample,
  19997. int numSamples,
  19998. float startGain,
  19999. float endGain) throw();
  20000. /** Adds samples from another buffer to this one.
  20001. @param destChannel the channel within this buffer to add the samples to
  20002. @param destStartSample the start sample within this buffer's channel
  20003. @param source the source buffer to add from
  20004. @param sourceChannel the channel within the source buffer to read from
  20005. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20006. @param numSamples the number of samples to process
  20007. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20008. added to this buffer's samples
  20009. @see copyFrom
  20010. */
  20011. void addFrom (const int destChannel,
  20012. const int destStartSample,
  20013. const AudioSampleBuffer& source,
  20014. const int sourceChannel,
  20015. const int sourceStartSample,
  20016. int numSamples,
  20017. const float gainToApplyToSource = 1.0f) throw();
  20018. /** Adds samples from an array of floats to one of the channels.
  20019. @param destChannel the channel within this buffer to add the samples to
  20020. @param destStartSample the start sample within this buffer's channel
  20021. @param source the source data to use
  20022. @param numSamples the number of samples to process
  20023. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20024. added to this buffer's samples
  20025. @see copyFrom
  20026. */
  20027. void addFrom (const int destChannel,
  20028. const int destStartSample,
  20029. const float* source,
  20030. int numSamples,
  20031. const float gainToApplyToSource = 1.0f) throw();
  20032. /** Adds samples from an array of floats, applying a gain ramp to them.
  20033. @param destChannel the channel within this buffer to add the samples to
  20034. @param destStartSample the start sample within this buffer's channel
  20035. @param source the source data to use
  20036. @param numSamples the number of samples to process
  20037. @param startGain the gain to apply to the first sample (this is multiplied with
  20038. the source samples before they are added to this buffer)
  20039. @param endGain the gain to apply to the final sample. The gain is linearly
  20040. interpolated between the first and last samples.
  20041. */
  20042. void addFromWithRamp (const int destChannel,
  20043. const int destStartSample,
  20044. const float* source,
  20045. int numSamples,
  20046. float startGain,
  20047. float endGain) throw();
  20048. /** Copies samples from another buffer to this one.
  20049. @param destChannel the channel within this buffer to copy the samples to
  20050. @param destStartSample the start sample within this buffer's channel
  20051. @param source the source buffer to read from
  20052. @param sourceChannel the channel within the source buffer to read from
  20053. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20054. @param numSamples the number of samples to process
  20055. @see addFrom
  20056. */
  20057. void copyFrom (const int destChannel,
  20058. const int destStartSample,
  20059. const AudioSampleBuffer& source,
  20060. const int sourceChannel,
  20061. const int sourceStartSample,
  20062. int numSamples) throw();
  20063. /** Copies samples from an array of floats into one of the channels.
  20064. @param destChannel the channel within this buffer to copy the samples to
  20065. @param destStartSample the start sample within this buffer's channel
  20066. @param source the source buffer to read from
  20067. @param numSamples the number of samples to process
  20068. @see addFrom
  20069. */
  20070. void copyFrom (const int destChannel,
  20071. const int destStartSample,
  20072. const float* source,
  20073. int numSamples) throw();
  20074. /** Finds the highest and lowest sample values in a given range.
  20075. @param channel the channel to read from
  20076. @param startSample the start sample within the channel
  20077. @param numSamples the number of samples to check
  20078. @param minVal on return, the lowest value that was found
  20079. @param maxVal on return, the highest value that was found
  20080. */
  20081. void findMinMax (const int channel,
  20082. const int startSample,
  20083. int numSamples,
  20084. float& minVal,
  20085. float& maxVal) const throw();
  20086. /** Finds the highest absolute sample value within a region of a channel.
  20087. */
  20088. float getMagnitude (const int channel,
  20089. const int startSample,
  20090. const int numSamples) const throw();
  20091. /** Finds the highest absolute sample value within a region on all channels.
  20092. */
  20093. float getMagnitude (const int startSample,
  20094. const int numSamples) const throw();
  20095. /** Returns the root mean squared level for a region of a channel.
  20096. */
  20097. float getRMSLevel (const int channel,
  20098. const int startSample,
  20099. const int numSamples) const throw();
  20100. /** Fills a section of the buffer using an AudioReader as its source.
  20101. This will convert the reader's fixed- or floating-point data to
  20102. the buffer's floating-point format, and will try to intelligently
  20103. cope with mismatches between the number of channels in the reader
  20104. and the buffer.
  20105. @see writeToAudioWriter
  20106. */
  20107. void readFromAudioReader (AudioFormatReader* reader,
  20108. const int startSample,
  20109. const int numSamples,
  20110. const int readerStartSample,
  20111. const bool useReaderLeftChan,
  20112. const bool useReaderRightChan) throw();
  20113. /** Writes a section of this buffer to an audio writer.
  20114. This saves you having to mess about with channels or floating/fixed
  20115. point conversion.
  20116. @see readFromAudioReader
  20117. */
  20118. void writeToAudioWriter (AudioFormatWriter* writer,
  20119. const int startSample,
  20120. const int numSamples) const throw();
  20121. juce_UseDebuggingNewOperator
  20122. private:
  20123. int numChannels, size, allocatedBytes;
  20124. float** channels;
  20125. float* allocatedData;
  20126. };
  20127. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20128. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20129. #endif
  20130. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20131. /********* Start of inlined file: juce_IIRFilter.h *********/
  20132. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20133. #define __JUCE_IIRFILTER_JUCEHEADER__
  20134. /**
  20135. An IIR filter that can perform low, high, or band-pass filtering on an
  20136. audio signal.
  20137. @see IIRFilterAudioSource
  20138. */
  20139. class JUCE_API IIRFilter
  20140. {
  20141. public:
  20142. /** Creates a filter.
  20143. Initially the filter is inactive, so will have no effect on samples that
  20144. you process with it. Use the appropriate method to turn it into the type
  20145. of filter needed.
  20146. */
  20147. IIRFilter() throw();
  20148. /** Creates a copy of another filter. */
  20149. IIRFilter (const IIRFilter& other) throw();
  20150. /** Destructor. */
  20151. ~IIRFilter() throw();
  20152. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20153. Note that this clears the processing state, but the type of filter and
  20154. its coefficients aren't changed. To put a filter into an inactive state, use
  20155. the makeInactive() method.
  20156. */
  20157. void reset() throw();
  20158. /** Performs the filter operation on the given set of samples.
  20159. */
  20160. void processSamples (float* const samples,
  20161. const int numSamples) throw();
  20162. /** Processes a single sample, without any locking or checking.
  20163. Use this if you need fast processing of a single value, but be aware that
  20164. this isn't thread-safe in the way that processSamples() is.
  20165. */
  20166. float processSingleSampleRaw (const float sample) throw();
  20167. /** Sets the filter up to act as a low-pass filter.
  20168. */
  20169. void makeLowPass (const double sampleRate,
  20170. const double frequency) throw();
  20171. /** Sets the filter up to act as a high-pass filter.
  20172. */
  20173. void makeHighPass (const double sampleRate,
  20174. const double frequency) throw();
  20175. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20176. The gain is a scale factor that the low frequencies are multiplied by, so values
  20177. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20178. attenuate them.
  20179. */
  20180. void makeLowShelf (const double sampleRate,
  20181. const double cutOffFrequency,
  20182. const double Q,
  20183. const float gainFactor) throw();
  20184. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20185. The gain is a scale factor that the high frequencies are multiplied by, so values
  20186. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20187. attenuate them.
  20188. */
  20189. void makeHighShelf (const double sampleRate,
  20190. const double cutOffFrequency,
  20191. const double Q,
  20192. const float gainFactor) throw();
  20193. /** Sets the filter up to act as a band pass filter centred around a
  20194. frequency, with a variable Q and gain.
  20195. The gain is a scale factor that the centre frequencies are multiplied by, so
  20196. values greater than 1.0 will boost the centre frequencies, values less than
  20197. 1.0 will attenuate them.
  20198. */
  20199. void makeBandPass (const double sampleRate,
  20200. const double centreFrequency,
  20201. const double Q,
  20202. const float gainFactor) throw();
  20203. /** Clears the filter's coefficients so that it becomes inactive.
  20204. */
  20205. void makeInactive() throw();
  20206. /** Makes this filter duplicate the set-up of another one.
  20207. */
  20208. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20209. juce_UseDebuggingNewOperator
  20210. protected:
  20211. CriticalSection processLock;
  20212. void setCoefficients (double c1, double c2, double c3,
  20213. double c4, double c5, double c6) throw();
  20214. bool active;
  20215. float coefficients[6];
  20216. float x1, x2, y1, y2;
  20217. // (use the copyCoefficientsFrom() method instead of this operator)
  20218. const IIRFilter& operator= (const IIRFilter&);
  20219. };
  20220. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20221. /********* End of inlined file: juce_IIRFilter.h *********/
  20222. #endif
  20223. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20224. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20225. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20226. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20227. /**
  20228. A subclass of AudioPlayHead can supply information about the position and
  20229. status of a moving play head during audio playback.
  20230. One of these can be supplied to an AudioProcessor object so that it can find
  20231. out about the position of the audio that it is rendering.
  20232. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20233. */
  20234. class JUCE_API AudioPlayHead
  20235. {
  20236. protected:
  20237. AudioPlayHead() {}
  20238. public:
  20239. virtual ~AudioPlayHead() {}
  20240. /** Frame rate types. */
  20241. enum FrameRateType
  20242. {
  20243. fps24 = 0,
  20244. fps25 = 1,
  20245. fps2997 = 2,
  20246. fps30 = 3,
  20247. fps2997drop = 4,
  20248. fps30drop = 5,
  20249. fpsUnknown = 99
  20250. };
  20251. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20252. */
  20253. struct CurrentPositionInfo
  20254. {
  20255. /** The tempo in BPM */
  20256. double bpm;
  20257. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20258. int timeSigNumerator;
  20259. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20260. int timeSigDenominator;
  20261. /** The current play position, in seconds from the start of the edit. */
  20262. double timeInSeconds;
  20263. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20264. double editOriginTime;
  20265. /** The current play position in pulses-per-quarter-note.
  20266. This is the number of quarter notes since the edit start.
  20267. */
  20268. double ppqPosition;
  20269. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20270. This is the number of quarter notes from the start of the edit to the
  20271. start of the current bar.
  20272. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20273. it's not available, the value will be 0.
  20274. */
  20275. double ppqPositionOfLastBarStart;
  20276. /** The video frame rate, if applicable. */
  20277. FrameRateType frameRate;
  20278. /** True if the transport is currently playing. */
  20279. bool isPlaying;
  20280. /** True if the transport is currently recording.
  20281. (When isRecording is true, then isPlaying will also be true).
  20282. */
  20283. bool isRecording;
  20284. };
  20285. /** Fills-in the given structure with details about the transport's
  20286. position at the start of the current processing block.
  20287. */
  20288. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20289. };
  20290. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20291. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20292. #endif
  20293. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20294. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20295. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20296. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20297. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20298. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20299. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20300. class AudioProcessor;
  20301. /**
  20302. Base class for the component that acts as the GUI for an AudioProcessor.
  20303. Derive your editor component from this class, and create an instance of it
  20304. by overriding the AudioProcessor::createEditor() method.
  20305. @see AudioProcessor, GenericAudioProcessorEditor
  20306. */
  20307. class JUCE_API AudioProcessorEditor : public Component
  20308. {
  20309. protected:
  20310. /** Creates an editor for the specified processor.
  20311. */
  20312. AudioProcessorEditor (AudioProcessor* const owner);
  20313. public:
  20314. /** Destructor. */
  20315. ~AudioProcessorEditor();
  20316. /** Returns a pointer to the processor that this editor represents. */
  20317. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20318. private:
  20319. AudioProcessor* const owner;
  20320. };
  20321. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20322. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20323. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20324. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20325. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20326. class AudioProcessor;
  20327. /**
  20328. Base class for listeners that want to know about changes to an AudioProcessor.
  20329. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20330. @see AudioProcessor
  20331. */
  20332. class JUCE_API AudioProcessorListener
  20333. {
  20334. public:
  20335. /** Destructor. */
  20336. virtual ~AudioProcessorListener() {}
  20337. /** Receives a callback when a parameter is changed.
  20338. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20339. many audio processors will change their parameter during their audio callback.
  20340. This means that not only has your handler code got to be completely thread-safe,
  20341. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20342. this event on your message thread, use this callback to trigger an AsyncUpdater
  20343. or ChangeBroadcaster which you can respond to on the message thread.
  20344. */
  20345. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20346. int parameterIndex,
  20347. float newValue) = 0;
  20348. /** Called to indicate that something else in the plugin has changed, like its
  20349. program, number of parameters, etc.
  20350. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20351. call it during their audio callback. This means that not only has your handler code
  20352. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20353. blocking. If you need to handle this event on your message thread, use this callback
  20354. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20355. message thread.
  20356. */
  20357. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20358. /** Indicates that a parameter change gesture has started.
  20359. E.g. if the user is dragging a slider, this would be called when they first
  20360. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20361. called when they release it.
  20362. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20363. call it during their audio callback. This means that not only has your handler code
  20364. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20365. blocking. If you need to handle this event on your message thread, use this callback
  20366. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20367. message thread.
  20368. @see audioProcessorParameterChangeGestureEnd
  20369. */
  20370. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20371. int parameterIndex);
  20372. /** Indicates that a parameter change gesture has finished.
  20373. E.g. if the user is dragging a slider, this would be called when they release
  20374. the mouse button.
  20375. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20376. call it during their audio callback. This means that not only has your handler code
  20377. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20378. blocking. If you need to handle this event on your message thread, use this callback
  20379. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20380. message thread.
  20381. @see audioPluginParameterChangeGestureStart
  20382. */
  20383. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20384. int parameterIndex);
  20385. };
  20386. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20387. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20388. /**
  20389. Base class for audio processing filters or plugins.
  20390. This is intended to act as a base class of audio filter that is general enough to
  20391. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20392. It is also used by the plugin hosting code as the wrapper around an instance
  20393. of a loaded plugin.
  20394. Derive your filter class from this base class, and if you're building a plugin,
  20395. you should implement a global function called createPluginFilter() which creates
  20396. and returns a new instance of your subclass.
  20397. */
  20398. class JUCE_API AudioProcessor
  20399. {
  20400. protected:
  20401. /** Constructor.
  20402. You can also do your initialisation tasks in the initialiseFilterInfo()
  20403. call, which will be made after this object has been created.
  20404. */
  20405. AudioProcessor();
  20406. public:
  20407. /** Destructor. */
  20408. virtual ~AudioProcessor();
  20409. /** Returns the name of this processor.
  20410. */
  20411. virtual const String getName() const = 0;
  20412. /** Called before playback starts, to let the filter prepare itself.
  20413. The sample rate is the target sample rate, and will remain constant until
  20414. playback stops.
  20415. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20416. samples that will be processed for each callback, but isn't any kind
  20417. of guarantee. The actual block sizes that the host uses may be different
  20418. each time the callback happens, and may be more or less than this value.
  20419. */
  20420. virtual void prepareToPlay (double sampleRate,
  20421. int estimatedSamplesPerBlock) = 0;
  20422. /** Called after playback has stopped, to let the filter free up any resources it
  20423. no longer needs.
  20424. */
  20425. virtual void releaseResources() = 0;
  20426. /** Renders the next block.
  20427. When this method is called, the buffer contains a number of channels which is
  20428. at least as great as the maximum number of input and output channels that
  20429. this filter is using. It will be filled with the filter's input data and
  20430. should be replaced with the filter's output.
  20431. So for example if your filter has 2 input channels and 4 output channels, then
  20432. the buffer will contain 4 channels, the first two being filled with the
  20433. input data. Your filter should read these, do its processing, and replace
  20434. the contents of all 4 channels with its output.
  20435. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20436. all filled with data, and your filter should overwrite the first 2 of these
  20437. with its output. But be VERY careful not to write anything to the last 3
  20438. channels, as these might be mapped to memory that the host assumes is read-only!
  20439. Note that if you have more outputs than inputs, then only those channels that
  20440. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20441. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20442. but the last two channels may contain garbage, so you should be careful not to
  20443. let this pass through without being overwritten or cleared.
  20444. Also note that the buffer may have more channels than are strictly necessary,
  20445. but your should only read/write from the ones that your filter is supposed to
  20446. be using.
  20447. The number of samples in these buffers is NOT guaranteed to be the same for every
  20448. callback, and may be more or less than the estimated value given to prepareToPlay().
  20449. Your code must be able to cope with variable-sized blocks, or you're going to get
  20450. clicks and crashes!
  20451. If the filter is receiving a midi input, then the midiMessages array will be filled
  20452. with the midi messages for this block. Each message's timestamp will indicate the
  20453. message's time, as a number of samples from the start of the block.
  20454. Any messages left in the midi buffer when this method has finished are assumed to
  20455. be the filter's midi output. This means that your filter should be careful to
  20456. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20457. Be very careful about what you do in this callback - it's going to be called by
  20458. the audio thread, so any kind of interaction with the UI is absolutely
  20459. out of the question. If you change a parameter in here and need to tell your UI to
  20460. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20461. the UI components register as listeners, and then call sendChangeMessage() inside the
  20462. processBlock() method to send out an asynchronous message. You could also use
  20463. the AsyncUpdater class in a similar way.
  20464. */
  20465. virtual void processBlock (AudioSampleBuffer& buffer,
  20466. MidiBuffer& midiMessages) = 0;
  20467. /** Returns the current AudioPlayHead object that should be used to find
  20468. out the state and position of the playhead.
  20469. You can call this from your processBlock() method, and use the AudioPlayHead
  20470. object to get the details about the time of the start of the block currently
  20471. being processed.
  20472. If the host hasn't supplied a playhead object, this will return 0.
  20473. */
  20474. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20475. /** Returns the current sample rate.
  20476. This can be called from your processBlock() method - it's not guaranteed
  20477. to be valid at any other time, and may return 0 if it's unknown.
  20478. */
  20479. double getSampleRate() const throw() { return sampleRate; }
  20480. /** Returns the current typical block size that is being used.
  20481. This can be called from your processBlock() method - it's not guaranteed
  20482. to be valid at any other time.
  20483. Remember it's not the ONLY block size that may be used when calling
  20484. processBlock, it's just the normal one. The actual block sizes used may be
  20485. larger or smaller than this, and will vary between successive calls.
  20486. */
  20487. int getBlockSize() const throw() { return blockSize; }
  20488. /** Returns the number of input channels that the host will be sending the filter.
  20489. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20490. number of channels that your filter would prefer to have, and this method lets
  20491. you know how many the host is actually using.
  20492. Note that this method is only valid during or after the prepareToPlay()
  20493. method call. Until that point, the number of channels will be unknown.
  20494. */
  20495. int getNumInputChannels() const throw() { return numInputChannels; }
  20496. /** Returns the number of output channels that the host will be sending the filter.
  20497. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20498. number of channels that your filter would prefer to have, and this method lets
  20499. you know how many the host is actually using.
  20500. Note that this method is only valid during or after the prepareToPlay()
  20501. method call. Until that point, the number of channels will be unknown.
  20502. */
  20503. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20504. /** Returns the name of one of the input channels, as returned by the host.
  20505. The host might not supply very useful names for channels, and this might be
  20506. something like "1", "2", "left", "right", etc.
  20507. */
  20508. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20509. /** Returns the name of one of the output channels, as returned by the host.
  20510. The host might not supply very useful names for channels, and this might be
  20511. something like "1", "2", "left", "right", etc.
  20512. */
  20513. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20514. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20515. virtual bool isInputChannelStereoPair (int index) const = 0;
  20516. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20517. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20518. /** This returns the number of samples delay that the filter imposes on the audio
  20519. passing through it.
  20520. The host will call this to find the latency - the filter itself should set this value
  20521. by calling setLatencySamples() as soon as it can during its initialisation.
  20522. */
  20523. int getLatencySamples() const throw() { return latencySamples; }
  20524. /** The filter should call this to set the number of samples delay that it introduces.
  20525. The filter should call this as soon as it can during initialisation, and can call it
  20526. later if the value changes.
  20527. */
  20528. void setLatencySamples (const int newLatency);
  20529. /** Returns true if the processor wants midi messages. */
  20530. virtual bool acceptsMidi() const = 0;
  20531. /** Returns true if the processor produces midi messages. */
  20532. virtual bool producesMidi() const = 0;
  20533. /** This returns a critical section that will automatically be locked while the host
  20534. is calling the processBlock() method.
  20535. Use it from your UI or other threads to lock access to variables that are used
  20536. by the process callback, but obviously be careful not to keep it locked for
  20537. too long, because that could cause stuttering playback. If you need to do something
  20538. that'll take a long time and need the processing to stop while it happens, use the
  20539. suspendProcessing() method instead.
  20540. @see suspendProcessing
  20541. */
  20542. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20543. /** Enables and disables the processing callback.
  20544. If you need to do something time-consuming on a thread and would like to make sure
  20545. the audio processing callback doesn't happen until you've finished, use this
  20546. to disable the callback and re-enable it again afterwards.
  20547. E.g.
  20548. @code
  20549. void loadNewPatch()
  20550. {
  20551. suspendProcessing (true);
  20552. ..do something that takes ages..
  20553. suspendProcessing (false);
  20554. }
  20555. @endcode
  20556. If the host tries to make an audio callback while processing is suspended, the
  20557. filter will return an empty buffer, but won't block the audio thread like it would
  20558. do if you use the getCallbackLock() critical section to synchronise access.
  20559. If you're going to use this, your processBlock() method must call isSuspended() and
  20560. check whether it's suspended or not. If it is, then it should skip doing any real
  20561. processing, either emitting silence or passing the input through unchanged.
  20562. @see getCallbackLock
  20563. */
  20564. void suspendProcessing (const bool shouldBeSuspended);
  20565. /** Returns true if processing is currently suspended.
  20566. @see suspendProcessing
  20567. */
  20568. bool isSuspended() const throw() { return suspended; }
  20569. /** A plugin can override this to be told when it should reset any playing voices.
  20570. The default implementation does nothing, but a host may call this to tell the
  20571. plugin that it should stop any tails or sounds that have been left running.
  20572. */
  20573. virtual void reset();
  20574. /** Returns true if the processor is being run in an offline mode for rendering.
  20575. If the processor is being run live on realtime signals, this returns false.
  20576. If the mode is unknown, this will assume it's realtime and return false.
  20577. This value may be unreliable until the prepareToPlay() method has been called,
  20578. and could change each time prepareToPlay() is called.
  20579. @see setNonRealtime()
  20580. */
  20581. bool isNonRealtime() const throw() { return nonRealtime; }
  20582. /** Called by the host to tell this processor whether it's being used in a non-realime
  20583. capacity for offline rendering or bouncing.
  20584. Whatever value is passed-in will be
  20585. */
  20586. void setNonRealtime (const bool isNonRealtime) throw();
  20587. /** Creates the filter's UI.
  20588. This can return 0 if you want a UI-less filter, in which case the host may create
  20589. a generic UI that lets the user twiddle the parameters directly.
  20590. If you do want to pass back a component, the component should be created and set to
  20591. the correct size before returning it.
  20592. Remember not to do anything silly like allowing your filter to keep a pointer to
  20593. the component that gets created - it could be deleted later without any warning, which
  20594. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20595. The correct way to handle the connection between an editor component and its
  20596. filter is to use something like a ChangeBroadcaster so that the editor can
  20597. register itself as a listener, and be told when a change occurs. This lets them
  20598. safely unregister themselves when they are deleted.
  20599. Here are a few things to bear in mind when writing an editor:
  20600. - Initially there won't be an editor, until the user opens one, or they might
  20601. not open one at all. Your filter mustn't rely on it being there.
  20602. - An editor object may be deleted and a replacement one created again at any time.
  20603. - It's safe to assume that an editor will be deleted before its filter.
  20604. */
  20605. virtual AudioProcessorEditor* createEditor() = 0;
  20606. /** Returns the active editor, if there is one.
  20607. Bear in mind this can return 0, even if an editor has previously been
  20608. opened.
  20609. */
  20610. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20611. /** Returns the active editor, or if there isn't one, it will create one.
  20612. This may call createEditor() internally to create the component.
  20613. */
  20614. AudioProcessorEditor* createEditorIfNeeded();
  20615. /** This must return the correct value immediately after the object has been
  20616. created, and mustn't change the number of parameters later.
  20617. */
  20618. virtual int getNumParameters() = 0;
  20619. /** Returns the name of a particular parameter. */
  20620. virtual const String getParameterName (int parameterIndex) = 0;
  20621. /** Called by the host to find out the value of one of the filter's parameters.
  20622. The host will expect the value returned to be between 0 and 1.0.
  20623. This could be called quite frequently, so try to make your code efficient.
  20624. It's also likely to be called by non-UI threads, so the code in here should
  20625. be thread-aware.
  20626. */
  20627. virtual float getParameter (int parameterIndex) = 0;
  20628. /** Returns the value of a parameter as a text string. */
  20629. virtual const String getParameterText (int parameterIndex) = 0;
  20630. /** The host will call this method to change the value of one of the filter's parameters.
  20631. The host may call this at any time, including during the audio processing
  20632. callback, so the filter has to process this very fast and avoid blocking.
  20633. If you want to set the value of a parameter internally, e.g. from your
  20634. editor component, then don't call this directly - instead, use the
  20635. setParameterNotifyingHost() method, which will also send a message to
  20636. the host telling it about the change. If the message isn't sent, the host
  20637. won't be able to automate your parameters properly.
  20638. The value passed will be between 0 and 1.0.
  20639. */
  20640. virtual void setParameter (int parameterIndex,
  20641. float newValue) = 0;
  20642. /** Your filter can call this when it needs to change one of its parameters.
  20643. This could happen when the editor or some other internal operation changes
  20644. a parameter. This method will call the setParameter() method to change the
  20645. value, and will then send a message to the host telling it about the change.
  20646. Note that to make sure the host correctly handles automation, you should call
  20647. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20648. tell the host when the user has started and stopped changing the parameter.
  20649. */
  20650. void setParameterNotifyingHost (int parameterIndex,
  20651. float newValue);
  20652. /** Returns true if the host can automate this parameter.
  20653. By default, this returns true for all parameters.
  20654. */
  20655. virtual bool isParameterAutomatable (int parameterIndex) const;
  20656. /** Should return true if this parameter is a "meta" parameter.
  20657. A meta-parameter is a parameter that changes other params. It is used
  20658. by some hosts (e.g. AudioUnit hosts).
  20659. By default this returns false.
  20660. */
  20661. virtual bool isMetaParameter (int parameterIndex) const;
  20662. /** Sends a signal to the host to tell it that the user is about to start changing this
  20663. parameter.
  20664. This allows the host to know when a parameter is actively being held by the user, and
  20665. it may use this information to help it record automation.
  20666. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20667. */
  20668. void beginParameterChangeGesture (int parameterIndex);
  20669. /** Tells the host that the user has finished changing this parameter.
  20670. This allows the host to know when a parameter is actively being held by the user, and
  20671. it may use this information to help it record automation.
  20672. A call to this method must follow a call to beginParameterChangeGesture().
  20673. */
  20674. void endParameterChangeGesture (int parameterIndex);
  20675. /** The filter can call this when something (apart from a parameter value) has changed.
  20676. It sends a hint to the host that something like the program, number of parameters,
  20677. etc, has changed, and that it should update itself.
  20678. */
  20679. void updateHostDisplay();
  20680. /** Returns the number of preset programs the filter supports.
  20681. The value returned must be valid as soon as this object is created, and
  20682. must not change over its lifetime.
  20683. This value shouldn't be less than 1.
  20684. */
  20685. virtual int getNumPrograms() = 0;
  20686. /** Returns the number of the currently active program.
  20687. */
  20688. virtual int getCurrentProgram() = 0;
  20689. /** Called by the host to change the current program.
  20690. */
  20691. virtual void setCurrentProgram (int index) = 0;
  20692. /** Must return the name of a given program. */
  20693. virtual const String getProgramName (int index) = 0;
  20694. /** Called by the host to rename a program.
  20695. */
  20696. virtual void changeProgramName (int index, const String& newName) = 0;
  20697. /** The host will call this method when it wants to save the filter's internal state.
  20698. This must copy any info about the filter's state into the block of memory provided,
  20699. so that the host can store this and later restore it using setStateInformation().
  20700. Note that there's also a getCurrentProgramStateInformation() method, which only
  20701. stores the current program, not the state of the entire filter.
  20702. See also the helper function copyXmlToBinary() for storing settings as XML.
  20703. @see getCurrentProgramStateInformation
  20704. */
  20705. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20706. /** The host will call this method if it wants to save the state of just the filter's
  20707. current program.
  20708. Unlike getStateInformation, this should only return the current program's state.
  20709. Not all hosts support this, and if you don't implement it, the base class
  20710. method just calls getStateInformation() instead. If you do implement it, be
  20711. sure to also implement getCurrentProgramStateInformation.
  20712. @see getStateInformation, setCurrentProgramStateInformation
  20713. */
  20714. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20715. /** This must restore the filter's state from a block of data previously created
  20716. using getStateInformation().
  20717. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20718. to restore just the current program, not the state of the entire filter.
  20719. See also the helper function getXmlFromBinary() for loading settings as XML.
  20720. @see setCurrentProgramStateInformation
  20721. */
  20722. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20723. /** The host will call this method if it wants to restore the state of just the filter's
  20724. current program.
  20725. Not all hosts support this, and if you don't implement it, the base class
  20726. method just calls setStateInformation() instead. If you do implement it, be
  20727. sure to also implement getCurrentProgramStateInformation.
  20728. @see setStateInformation, getCurrentProgramStateInformation
  20729. */
  20730. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20731. /** Adds a listener that will be called when an aspect of this processor changes. */
  20732. void addListener (AudioProcessorListener* const newListener) throw();
  20733. /** Removes a previously added listener. */
  20734. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20735. /** Not for public use - this is called before deleting an editor component. */
  20736. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20737. /** Not for public use - this is called to initialise the processor. */
  20738. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20739. /** Not for public use - this is called to initialise the processor before playing. */
  20740. void setPlayConfigDetails (const int numIns, const int numOuts,
  20741. const double sampleRate,
  20742. const int blockSize) throw();
  20743. juce_UseDebuggingNewOperator
  20744. protected:
  20745. /** Helper function that just converts an xml element into a binary blob.
  20746. Use this in your filter's getStateInformation() method if you want to
  20747. store its state as xml.
  20748. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20749. from a binary blob.
  20750. */
  20751. static void copyXmlToBinary (const XmlElement& xml,
  20752. JUCE_NAMESPACE::MemoryBlock& destData);
  20753. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20754. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20755. an XmlElement object that the caller must delete when no longer needed.
  20756. */
  20757. static XmlElement* getXmlFromBinary (const void* data,
  20758. const int sizeInBytes);
  20759. /** @internal */
  20760. AudioPlayHead* playHead;
  20761. /** @internal */
  20762. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20763. private:
  20764. VoidArray listeners;
  20765. AudioProcessorEditor* activeEditor;
  20766. double sampleRate;
  20767. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20768. bool suspended, nonRealtime;
  20769. CriticalSection callbackLock, listenerLock;
  20770. #ifdef JUCE_DEBUG
  20771. BitArray changingParams;
  20772. #endif
  20773. AudioProcessor (const AudioProcessor&);
  20774. const AudioProcessor& operator= (const AudioProcessor&);
  20775. };
  20776. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20777. /********* End of inlined file: juce_AudioProcessor.h *********/
  20778. #endif
  20779. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20780. #endif
  20781. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20782. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20783. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20784. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20785. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20786. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20787. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20788. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20789. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20790. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20791. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20792. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20793. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20794. /********* Start of inlined file: juce_PluginDescription.h *********/
  20795. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20796. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20797. /**
  20798. A small class to represent some facts about a particular type of plugin.
  20799. This class is for storing and managing the details about a plugin without
  20800. actually having to load an instance of it.
  20801. A KnownPluginList contains a list of PluginDescription objects.
  20802. @see KnownPluginList
  20803. */
  20804. class JUCE_API PluginDescription
  20805. {
  20806. public:
  20807. PluginDescription() throw();
  20808. PluginDescription (const PluginDescription& other) throw();
  20809. const PluginDescription& operator= (const PluginDescription& other) throw();
  20810. ~PluginDescription() throw();
  20811. /** The name of the plugin. */
  20812. String name;
  20813. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  20814. */
  20815. String pluginFormatName;
  20816. /** A category, such as "Dynamics", "Reverbs", etc.
  20817. */
  20818. String category;
  20819. /** The manufacturer. */
  20820. String manufacturerName;
  20821. /** The version. This string doesn't have any particular format. */
  20822. String version;
  20823. /** Either the file containing the plugin module, or some other unique way
  20824. of identifying it.
  20825. E.g. for an AU, this would be an ID string that the component manager
  20826. could use to retrieve the plugin. For a VST, it's the file path.
  20827. */
  20828. String fileOrIdentifier;
  20829. /** The last time the plugin file was changed.
  20830. This is handy when scanning for new or changed plugins.
  20831. */
  20832. Time lastFileModTime;
  20833. /** A unique ID for the plugin.
  20834. Note that this might not be unique between formats, e.g. a VST and some
  20835. other format might actually have the same id.
  20836. @see createIdentifierString
  20837. */
  20838. int uid;
  20839. /** True if the plugin identifies itself as a synthesiser. */
  20840. bool isInstrument;
  20841. /** The number of inputs. */
  20842. int numInputChannels;
  20843. /** The number of outputs. */
  20844. int numOutputChannels;
  20845. /** Returns true if the two descriptions refer the the same plugin.
  20846. This isn't quite as simple as them just having the same file (because of
  20847. shell plugins).
  20848. */
  20849. bool isDuplicateOf (const PluginDescription& other) const;
  20850. /** Returns a string that can be saved and used to uniquely identify the
  20851. plugin again.
  20852. This contains less info than the XML encoding, and is independent of the
  20853. plugin's file location, so can be used to store a plugin ID for use
  20854. across different machines.
  20855. */
  20856. const String createIdentifierString() const throw();
  20857. /** Creates an XML object containing these details.
  20858. @see loadFromXml
  20859. */
  20860. XmlElement* createXml() const;
  20861. /** Reloads the info in this structure from an XML record that was previously
  20862. saved with createXML().
  20863. Returns true if the XML was a valid plugin description.
  20864. */
  20865. bool loadFromXml (const XmlElement& xml);
  20866. juce_UseDebuggingNewOperator
  20867. };
  20868. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20869. /********* End of inlined file: juce_PluginDescription.h *********/
  20870. /**
  20871. Base class for an active instance of a plugin.
  20872. This derives from the AudioProcessor class, and adds some extra functionality
  20873. that helps when wrapping dynamically loaded plugins.
  20874. @see AudioProcessor, AudioPluginFormat
  20875. */
  20876. class JUCE_API AudioPluginInstance : public AudioProcessor
  20877. {
  20878. public:
  20879. /** Destructor.
  20880. Make sure that you delete any UI components that belong to this plugin before
  20881. deleting the plugin.
  20882. */
  20883. virtual ~AudioPluginInstance();
  20884. /** Fills-in the appropriate parts of this plugin description object.
  20885. */
  20886. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  20887. juce_UseDebuggingNewOperator
  20888. protected:
  20889. AudioPluginInstance();
  20890. AudioPluginInstance (const AudioPluginInstance&);
  20891. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  20892. };
  20893. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20894. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  20895. class PluginDescription;
  20896. /**
  20897. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  20898. Use the static getNumFormats() and getFormat() calls to find the types
  20899. of format that are available.
  20900. */
  20901. class JUCE_API AudioPluginFormat
  20902. {
  20903. public:
  20904. /** Destructor. */
  20905. virtual ~AudioPluginFormat();
  20906. /** Returns the format name.
  20907. E.g. "VST", "AudioUnit", etc.
  20908. */
  20909. virtual const String getName() const = 0;
  20910. /** This tries to create descriptions for all the plugin types available in
  20911. a binary module file.
  20912. The file will be some kind of DLL or bundle.
  20913. Normally there will only be one type returned, but some plugins
  20914. (e.g. VST shells) can use a single DLL to create a set of different plugin
  20915. subtypes, so in that case, each subtype is returned as a separate object.
  20916. */
  20917. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  20918. const String& fileOrIdentifier) = 0;
  20919. /** Tries to recreate a type from a previously generated PluginDescription.
  20920. @see PluginDescription::createInstance
  20921. */
  20922. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  20923. /** Should do a quick check to see if this file or directory might be a plugin of
  20924. this format.
  20925. This is for searching for potential files, so it shouldn't actually try to
  20926. load the plugin or do anything time-consuming.
  20927. */
  20928. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  20929. /** Returns a readable version of the name of the plugin that this identifier refers to.
  20930. */
  20931. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  20932. /** Checks whether this plugin could possibly be loaded.
  20933. It doesn't actually need to load it, just to check whether the file or component
  20934. still exists.
  20935. */
  20936. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  20937. /** Searches a suggested set of directories for any plugins in this format.
  20938. The path might be ignored, e.g. by AUs, which are found by the OS rather
  20939. than manually.
  20940. */
  20941. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  20942. const bool recursive) = 0;
  20943. /** Returns the typical places to look for this kind of plugin.
  20944. Note that if this returns no paths, it means that the format can't be scanned-for
  20945. (i.e. it's an internal format that doesn't live in files)
  20946. */
  20947. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  20948. juce_UseDebuggingNewOperator
  20949. protected:
  20950. AudioPluginFormat() throw();
  20951. AudioPluginFormat (const AudioPluginFormat&);
  20952. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  20953. };
  20954. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20955. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  20956. /**
  20957. This maintains a list of known AudioPluginFormats.
  20958. @see AudioPluginFormat
  20959. */
  20960. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  20961. {
  20962. public:
  20963. AudioPluginFormatManager() throw();
  20964. /** Destructor. */
  20965. ~AudioPluginFormatManager() throw();
  20966. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  20967. /** Adds any formats that it knows about, e.g. VST.
  20968. */
  20969. void addDefaultFormats();
  20970. /** Returns the number of types of format that are available.
  20971. Use getFormat() to get one of them.
  20972. */
  20973. int getNumFormats() throw();
  20974. /** Returns one of the available formats.
  20975. @see getNumFormats
  20976. */
  20977. AudioPluginFormat* getFormat (const int index) throw();
  20978. /** Adds a format to the list.
  20979. The object passed in will be owned and deleted by the manager.
  20980. */
  20981. void addFormat (AudioPluginFormat* const format) throw();
  20982. /** Tries to load the type for this description, by trying all the formats
  20983. that this manager knows about.
  20984. The caller is responsible for deleting the object that is returned.
  20985. If it can't load the plugin, it returns 0 and leaves a message in the
  20986. errorMessage string.
  20987. */
  20988. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  20989. String& errorMessage) const;
  20990. /** Checks that the file or component for this plugin actually still exists.
  20991. (This won't try to load the plugin)
  20992. */
  20993. bool doesPluginStillExist (const PluginDescription& description) const;
  20994. juce_UseDebuggingNewOperator
  20995. private:
  20996. OwnedArray <AudioPluginFormat> formats;
  20997. AudioPluginFormatManager (const AudioPluginFormatManager&);
  20998. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  20999. };
  21000. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21001. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21002. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21003. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21004. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21005. /********* Start of inlined file: juce_PopupMenu.h *********/
  21006. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21007. #define __JUCE_POPUPMENU_JUCEHEADER__
  21008. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21009. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21010. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21011. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21012. @see PopupMenu::addCustomItem
  21013. */
  21014. class JUCE_API PopupMenuCustomComponent : public Component
  21015. {
  21016. public:
  21017. /** Destructor. */
  21018. ~PopupMenuCustomComponent();
  21019. /** Chooses the size that this component would like to have.
  21020. Note that the size which this method returns isn't necessarily the one that
  21021. the menu will give it, as it will be stretched to fit the other items in
  21022. the menu.
  21023. */
  21024. virtual void getIdealSize (int& idealWidth,
  21025. int& idealHeight) = 0;
  21026. /** Dismisses the menu indicating that this item has been chosen.
  21027. This will cause the menu to exit from its modal state, returning
  21028. this item's id as the result.
  21029. */
  21030. void triggerMenuItem();
  21031. /** Returns true if this item should be highlighted because the mouse is
  21032. over it.
  21033. You can call this method in your paint() method to find out whether
  21034. to draw a highlight.
  21035. */
  21036. bool isItemHighlighted() const throw() { return isHighlighted; }
  21037. protected:
  21038. /** Constructor.
  21039. If isTriggeredAutomatically is true, then the menu will automatically detect
  21040. a click on this component and use that to trigger it. If it's false, then it's
  21041. up to your class to manually trigger the item if it wants to.
  21042. */
  21043. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21044. private:
  21045. friend class MenuItemInfo;
  21046. friend class MenuItemComponent;
  21047. friend class PopupMenuWindow;
  21048. int refCount_;
  21049. bool isHighlighted, isTriggeredAutomatically;
  21050. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21051. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21052. };
  21053. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21054. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21055. /** Creates and displays a popup-menu.
  21056. To show a popup-menu, you create one of these, add some items to it, then
  21057. call its show() method, which returns the id of the item the user selects.
  21058. E.g. @code
  21059. void MyWidget::mouseDown (const MouseEvent& e)
  21060. {
  21061. PopupMenu m;
  21062. m.addItem (1, "item 1");
  21063. m.addItem (2, "item 2");
  21064. const int result = m.show();
  21065. if (result == 0)
  21066. {
  21067. // user dismissed the menu without picking anything
  21068. }
  21069. else if (result == 1)
  21070. {
  21071. // user picked item 1
  21072. }
  21073. else if (result == 2)
  21074. {
  21075. // user picked item 2
  21076. }
  21077. }
  21078. @endcode
  21079. Submenus are easy too: @code
  21080. void MyWidget::mouseDown (const MouseEvent& e)
  21081. {
  21082. PopupMenu subMenu;
  21083. subMenu.addItem (1, "item 1");
  21084. subMenu.addItem (2, "item 2");
  21085. PopupMenu mainMenu;
  21086. mainMenu.addItem (3, "item 3");
  21087. mainMenu.addSubMenu ("other choices", subMenu);
  21088. const int result = m.show();
  21089. ...etc
  21090. }
  21091. @endcode
  21092. */
  21093. class JUCE_API PopupMenu
  21094. {
  21095. public:
  21096. /** Creates an empty popup menu. */
  21097. PopupMenu() throw();
  21098. /** Creates a copy of another menu. */
  21099. PopupMenu (const PopupMenu& other) throw();
  21100. /** Destructor. */
  21101. ~PopupMenu() throw();
  21102. /** Copies this menu from another one. */
  21103. const PopupMenu& operator= (const PopupMenu& other) throw();
  21104. /** Resets the menu, removing all its items. */
  21105. void clear() throw();
  21106. /** Appends a new text item for this menu to show.
  21107. @param itemResultId the number that will be returned from the show() method
  21108. if the user picks this item. The value should never be
  21109. zero, because that's used to indicate that the user didn't
  21110. select anything.
  21111. @param itemText the text to show.
  21112. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21113. picked
  21114. @param isTicked if true, the item will be shown with a tick next to it
  21115. @param iconToUse if this is non-zero, it should be an image that will be
  21116. displayed to the left of the item. This method will take its
  21117. own copy of the image passed-in, so there's no need to keep
  21118. it hanging around.
  21119. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21120. */
  21121. void addItem (const int itemResultId,
  21122. const String& itemText,
  21123. const bool isActive = true,
  21124. const bool isTicked = false,
  21125. const Image* const iconToUse = 0) throw();
  21126. /** Adds an item that represents one of the commands in a command manager object.
  21127. @param commandManager the manager to use to trigger the command and get information
  21128. about it
  21129. @param commandID the ID of the command
  21130. @param displayName if this is non-empty, then this string will be used instead of
  21131. the command's registered name
  21132. */
  21133. void addCommandItem (ApplicationCommandManager* commandManager,
  21134. const int commandID,
  21135. const String& displayName = String::empty) throw();
  21136. /** Appends a text item with a special colour.
  21137. This is the same as addItem(), but specifies a colour to use for the
  21138. text, which will override the default colours that are used by the
  21139. current look-and-feel. See addItem() for a description of the parameters.
  21140. */
  21141. void addColouredItem (const int itemResultId,
  21142. const String& itemText,
  21143. const Colour& itemTextColour,
  21144. const bool isActive = true,
  21145. const bool isTicked = false,
  21146. const Image* const iconToUse = 0) throw();
  21147. /** Appends a custom menu item.
  21148. This will add a user-defined component to use as a menu item. The component
  21149. passed in will be deleted by this menu when it's no longer needed.
  21150. @see PopupMenuCustomComponent
  21151. */
  21152. void addCustomItem (const int itemResultId,
  21153. PopupMenuCustomComponent* const customComponent) throw();
  21154. /** Appends a custom menu item that can't be used to trigger a result.
  21155. This will add a user-defined component to use as a menu item. Unlike the
  21156. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21157. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21158. delete the component when it's finished, so it's the caller's responsibility
  21159. to manage the component that is passed-in.
  21160. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21161. detection of a mouse-click on your component, and use that to trigger the
  21162. menu ID specified in itemResultId. If this is false, the menu item can't
  21163. be triggered, so itemResultId is not used.
  21164. @see PopupMenuCustomComponent
  21165. */
  21166. void addCustomItem (const int itemResultId,
  21167. Component* customComponent,
  21168. int idealWidth, int idealHeight,
  21169. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21170. /** Appends a sub-menu.
  21171. If the menu that's passed in is empty, it will appear as an inactive item.
  21172. */
  21173. void addSubMenu (const String& subMenuName,
  21174. const PopupMenu& subMenu,
  21175. const bool isActive = true,
  21176. Image* const iconToUse = 0,
  21177. const bool isTicked = false) throw();
  21178. /** Appends a separator to the menu, to help break it up into sections.
  21179. The menu class is smart enough not to display separators at the top or bottom
  21180. of the menu, and it will replace mutliple adjacent separators with a single
  21181. one, so your code can be quite free and easy about adding these, and it'll
  21182. always look ok.
  21183. */
  21184. void addSeparator() throw();
  21185. /** Adds a non-clickable text item to the menu.
  21186. This is a bold-font items which can be used as a header to separate the items
  21187. into named groups.
  21188. */
  21189. void addSectionHeader (const String& title) throw();
  21190. /** Returns the number of items that the menu currently contains.
  21191. (This doesn't count separators).
  21192. */
  21193. int getNumItems() const throw();
  21194. /** Returns true if the menu contains a command item that triggers the given command. */
  21195. bool containsCommandItem (const int commandID) const throw();
  21196. /** Returns true if the menu contains any items that can be used. */
  21197. bool containsAnyActiveItems() const throw();
  21198. /** Displays the menu and waits for the user to pick something.
  21199. This will display the menu modally, and return the ID of the item that the
  21200. user picks. If they click somewhere off the menu to get rid of it without
  21201. choosing anything, this will return 0.
  21202. The current location of the mouse will be used as the position to show the
  21203. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21204. on where this point is on the screen, the menu will appear above, below or
  21205. to the side of the point.
  21206. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21207. then when the menu first appears, it will make sure
  21208. that this item is visible. So if the menu has too many
  21209. items to fit on the screen, it will be scrolled to a
  21210. position where this item is visible.
  21211. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21212. than this if some items are too long to fit.
  21213. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21214. vertical column, the menu may be laid out as a series of
  21215. columns - this is the maximum number allowed. To use the
  21216. default value for this (probably about 7), you can pass
  21217. in zero.
  21218. @param standardItemHeight if this is non-zero, it will be used as the standard
  21219. height for menu items (apart from custom items)
  21220. @see showAt
  21221. */
  21222. int show (const int itemIdThatMustBeVisible = 0,
  21223. const int minimumWidth = 0,
  21224. const int maximumNumColumns = 0,
  21225. const int standardItemHeight = 0);
  21226. /** Displays the menu at a specific location.
  21227. This is the same as show(), but uses a specific location (in global screen
  21228. co-ordinates) rather than the current mouse position.
  21229. Note that the co-ordinates don't specify the top-left of the menu - they
  21230. indicate a point of interest, and the menu will position itself nearby to
  21231. this point, trying to keep it fully on-screen.
  21232. @see show()
  21233. */
  21234. int showAt (const int screenX,
  21235. const int screenY,
  21236. const int itemIdThatMustBeVisible = 0,
  21237. const int minimumWidth = 0,
  21238. const int maximumNumColumns = 0,
  21239. const int standardItemHeight = 0);
  21240. /** Displays the menu as if it's attached to a component such as a button.
  21241. This is similar to showAt(), but will position it next to the given component, e.g.
  21242. so that the menu's edge is aligned with that of the component. This is intended for
  21243. things like buttons that trigger a pop-up menu.
  21244. */
  21245. int showAt (Component* componentToAttachTo,
  21246. const int itemIdThatMustBeVisible = 0,
  21247. const int minimumWidth = 0,
  21248. const int maximumNumColumns = 0,
  21249. const int standardItemHeight = 0);
  21250. /** Closes any menus that are currently open.
  21251. This might be useful if you have a situation where your window is being closed
  21252. by some means other than a user action, and you'd like to make sure that menus
  21253. aren't left hanging around.
  21254. */
  21255. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21256. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21257. This can be called before show() if you need a customised menu. Be careful
  21258. not to delete the LookAndFeel object before the menu has been deleted.
  21259. */
  21260. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21261. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21262. These constants can be used either via the LookAndFeel::setColour()
  21263. method for the look and feel that is set for this menu with setLookAndFeel()
  21264. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21265. */
  21266. enum ColourIds
  21267. {
  21268. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21269. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21270. colour is specified when the item is added). */
  21271. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21272. addSectionHeader() method). */
  21273. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21274. highlighted menu item. */
  21275. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21276. highlighted item. */
  21277. };
  21278. /**
  21279. Allows you to iterate through the items in a pop-up menu, and examine
  21280. their properties.
  21281. To use this, just create one and repeatedly call its next() method. When this
  21282. returns true, all the member variables of the iterator are filled-out with
  21283. information describing the menu item. When it returns false, the end of the
  21284. list has been reached.
  21285. */
  21286. class JUCE_API MenuItemIterator
  21287. {
  21288. public:
  21289. /** Creates an iterator that will scan through the items in the specified
  21290. menu.
  21291. Be careful not to add any items to a menu while it is being iterated,
  21292. or things could get out of step.
  21293. */
  21294. MenuItemIterator (const PopupMenu& menu) throw();
  21295. /** Destructor. */
  21296. ~MenuItemIterator() throw();
  21297. /** Returns true if there is another item, and sets up all this object's
  21298. member variables to reflect that item's properties.
  21299. */
  21300. bool next() throw();
  21301. String itemName;
  21302. const PopupMenu* subMenu;
  21303. int itemId;
  21304. bool isSeparator;
  21305. bool isTicked;
  21306. bool isEnabled;
  21307. bool isCustomComponent;
  21308. bool isSectionHeader;
  21309. const Colour* customColour;
  21310. const Image* customImage;
  21311. ApplicationCommandManager* commandManager;
  21312. juce_UseDebuggingNewOperator
  21313. private:
  21314. const PopupMenu& menu;
  21315. int index;
  21316. MenuItemIterator (const MenuItemIterator&);
  21317. const MenuItemIterator& operator= (const MenuItemIterator&);
  21318. };
  21319. juce_UseDebuggingNewOperator
  21320. private:
  21321. friend class PopupMenuWindow;
  21322. friend class MenuItemIterator;
  21323. VoidArray items;
  21324. LookAndFeel* lookAndFeel;
  21325. bool separatorPending;
  21326. void addSeparatorIfPending();
  21327. int showMenu (const int x, const int y, const int w, const int h,
  21328. const int itemIdThatMustBeVisible,
  21329. const int minimumWidth,
  21330. const int maximumNumColumns,
  21331. const int standardItemHeight,
  21332. const bool alignToRectangle,
  21333. Component* const componentAttachedTo) throw();
  21334. friend class MenuBarComponent;
  21335. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21336. const int itemIdThatMustBeVisible,
  21337. const int minimumWidth,
  21338. const int maximumNumColumns,
  21339. const int standardItemHeight,
  21340. const bool alignToRectangle,
  21341. Component* menuBarComponent,
  21342. ApplicationCommandManager** managerOfChosenCommand,
  21343. Component* const componentAttachedTo) throw();
  21344. };
  21345. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21346. /********* End of inlined file: juce_PopupMenu.h *********/
  21347. /**
  21348. Manages a list of plugin types.
  21349. This can be easily edited, saved and loaded, and used to create instances of
  21350. the plugin types in it.
  21351. @see PluginListComponent
  21352. */
  21353. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21354. {
  21355. public:
  21356. /** Creates an empty list.
  21357. */
  21358. KnownPluginList();
  21359. /** Destructor. */
  21360. ~KnownPluginList();
  21361. /** Clears the list. */
  21362. void clear();
  21363. /** Returns the number of types currently in the list.
  21364. @see getType
  21365. */
  21366. int getNumTypes() const throw() { return types.size(); }
  21367. /** Returns one of the types.
  21368. @see getNumTypes
  21369. */
  21370. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21371. /** Looks for a type in the list which comes from this file.
  21372. */
  21373. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21374. /** Looks for a type in the list which matches a plugin type ID.
  21375. The identifierString parameter must have been created by
  21376. PluginDescription::createIdentifierString().
  21377. */
  21378. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21379. /** Adds a type manually from its description. */
  21380. bool addType (const PluginDescription& type);
  21381. /** Removes a type. */
  21382. void removeType (const int index) throw();
  21383. /** Looks for all types that can be loaded from a given file, and adds them
  21384. to the list.
  21385. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21386. re-tested if it's not already in the list, or if the file's modification
  21387. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21388. false, the file will always be reloaded and tested.
  21389. Returns true if any new types were added, and all the types found in this
  21390. file (even if it was already known and hasn't been re-scanned) get returned
  21391. in the array.
  21392. */
  21393. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21394. const bool dontRescanIfAlreadyInList,
  21395. OwnedArray <PluginDescription>& typesFound,
  21396. AudioPluginFormat& formatToUse);
  21397. /** Returns true if the specified file is already known about and if it
  21398. hasn't been modified since our entry was created.
  21399. */
  21400. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21401. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21402. If any types are found in the files, their descriptions are returned in the array.
  21403. */
  21404. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21405. OwnedArray <PluginDescription>& typesFound);
  21406. /** Sort methods used to change the order of the plugins in the list.
  21407. */
  21408. enum SortMethod
  21409. {
  21410. defaultOrder = 0,
  21411. sortAlphabetically,
  21412. sortByCategory,
  21413. sortByManufacturer,
  21414. sortByFileSystemLocation
  21415. };
  21416. /** Adds all the plugin types to a popup menu so that the user can select one.
  21417. Depending on the sort method, it may add sub-menus for categories,
  21418. manufacturers, etc.
  21419. Use getIndexChosenByMenu() to find out the type that was chosen.
  21420. */
  21421. void addToMenu (PopupMenu& menu,
  21422. const SortMethod sortMethod) const;
  21423. /** Converts a menu item index that has been chosen into its index in this list.
  21424. Returns -1 if it's not an ID that was used.
  21425. @see addToMenu
  21426. */
  21427. int getIndexChosenByMenu (const int menuResultCode) const;
  21428. /** Sorts the list. */
  21429. void sort (const SortMethod method);
  21430. /** Creates some XML that can be used to store the state of this list.
  21431. */
  21432. XmlElement* createXml() const;
  21433. /** Recreates the state of this list from its stored XML format.
  21434. */
  21435. void recreateFromXml (const XmlElement& xml);
  21436. juce_UseDebuggingNewOperator
  21437. private:
  21438. OwnedArray <PluginDescription> types;
  21439. KnownPluginList (const KnownPluginList&);
  21440. const KnownPluginList& operator= (const KnownPluginList&);
  21441. };
  21442. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21443. /********* End of inlined file: juce_KnownPluginList.h *********/
  21444. /**
  21445. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21446. Use one of these objects if you want to wire-up a set of AudioProcessors
  21447. and play back the result.
  21448. Processors can be added to the graph as "nodes" using addNode(), and once
  21449. added, you can connect any of their input or output channels to other
  21450. nodes using addConnection().
  21451. To play back a graph through an audio device, you might want to use an
  21452. AudioProcessorPlayer object.
  21453. */
  21454. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21455. public AsyncUpdater
  21456. {
  21457. public:
  21458. /** Creates an empty graph.
  21459. */
  21460. AudioProcessorGraph();
  21461. /** Destructor.
  21462. Any processor objects that have been added to the graph will also be deleted.
  21463. */
  21464. ~AudioProcessorGraph();
  21465. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21466. To create a node, call AudioProcessorGraph::addNode().
  21467. */
  21468. class Node : public ReferenceCountedObject
  21469. {
  21470. public:
  21471. /** Destructor.
  21472. */
  21473. ~Node();
  21474. /** The ID number assigned to this node.
  21475. This is assigned by the graph that owns it, and can't be changed.
  21476. */
  21477. const uint32 id;
  21478. /** The actual processor object that this node represents.
  21479. */
  21480. AudioProcessor* const processor;
  21481. /** A set of user-definable properties that are associated with this node.
  21482. This can be used to attach values to the node for whatever purpose seems
  21483. useful. For example, you might store an x and y position if your application
  21484. is displaying the nodes on-screen.
  21485. */
  21486. PropertySet properties;
  21487. /** A convenient typedef for referring to a pointer to a node object.
  21488. */
  21489. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21490. juce_UseDebuggingNewOperator
  21491. private:
  21492. friend class AudioProcessorGraph;
  21493. bool isPrepared;
  21494. Node (const uint32 id, AudioProcessor* const processor) throw();
  21495. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21496. void unprepare();
  21497. Node (const Node&);
  21498. const Node& operator= (const Node&);
  21499. };
  21500. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21501. To create a connection, use AudioProcessorGraph::addConnection().
  21502. */
  21503. struct Connection
  21504. {
  21505. public:
  21506. /** The ID number of the node which is the input source for this connection.
  21507. @see AudioProcessorGraph::getNodeForId
  21508. */
  21509. uint32 sourceNodeId;
  21510. /** The index of the output channel of the source node from which this
  21511. connection takes its data.
  21512. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21513. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21514. index of an audio output channel in the source node.
  21515. */
  21516. int sourceChannelIndex;
  21517. /** The ID number of the node which is the destination for this connection.
  21518. @see AudioProcessorGraph::getNodeForId
  21519. */
  21520. uint32 destNodeId;
  21521. /** The index of the input channel of the destination node to which this
  21522. connection delivers its data.
  21523. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21524. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21525. index of an audio input channel in the destination node.
  21526. */
  21527. int destChannelIndex;
  21528. juce_UseDebuggingNewOperator
  21529. private:
  21530. };
  21531. /** Deletes all nodes and connections from this graph.
  21532. Any processor objects in the graph will be deleted.
  21533. */
  21534. void clear();
  21535. /** Returns the number of nodes in the graph. */
  21536. int getNumNodes() const throw() { return nodes.size(); }
  21537. /** Returns a pointer to one of the nodes in the graph.
  21538. This will return 0 if the index is out of range.
  21539. @see getNodeForId
  21540. */
  21541. Node* getNode (const int index) const throw() { return nodes [index]; }
  21542. /** Searches the graph for a node with the given ID number and returns it.
  21543. If no such node was found, this returns 0.
  21544. @see getNode
  21545. */
  21546. Node* getNodeForId (const uint32 nodeId) const throw();
  21547. /** Adds a node to the graph.
  21548. This creates a new node in the graph, for the specified processor. Once you have
  21549. added a processor to the graph, the graph owns it and will delete it later when
  21550. it is no longer needed.
  21551. The optional nodeId parameter lets you specify an ID to use for the node, but
  21552. if the value is already in use, this new node will overwrite the old one.
  21553. If this succeeds, it returns a pointer to the newly-created node.
  21554. */
  21555. Node* addNode (AudioProcessor* const newProcessor,
  21556. uint32 nodeId = 0);
  21557. /** Deletes a node within the graph which has the specified ID.
  21558. This will also delete any connections that are attached to this node.
  21559. */
  21560. bool removeNode (const uint32 nodeId);
  21561. /** Returns the number of connections in the graph. */
  21562. int getNumConnections() const throw() { return connections.size(); }
  21563. /** Returns a pointer to one of the connections in the graph. */
  21564. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21565. /** Searches for a connection between some specified channels.
  21566. If no such connection is found, this returns 0.
  21567. */
  21568. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21569. const int sourceChannelIndex,
  21570. const uint32 destNodeId,
  21571. const int destChannelIndex) const throw();
  21572. /** Returns true if there is a connection between any of the channels of
  21573. two specified nodes.
  21574. */
  21575. bool isConnected (const uint32 possibleSourceNodeId,
  21576. const uint32 possibleDestNodeId) const throw();
  21577. /** Returns true if it would be legal to connect the specified points.
  21578. */
  21579. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21580. const uint32 destNodeId, const int destChannelIndex) const throw();
  21581. /** Attempts to connect two specified channels of two nodes.
  21582. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21583. to an audio one or other such nonsense), then it'll return false.
  21584. */
  21585. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21586. const uint32 destNodeId, const int destChannelIndex);
  21587. /** Deletes the connection with the specified index.
  21588. Returns true if a connection was actually deleted.
  21589. */
  21590. void removeConnection (const int index);
  21591. /** Deletes any connection between two specified points.
  21592. Returns true if a connection was actually deleted.
  21593. */
  21594. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21595. const uint32 destNodeId, const int destChannelIndex);
  21596. /** Removes all connections from the specified node.
  21597. */
  21598. bool disconnectNode (const uint32 nodeId);
  21599. /** Performs a sanity checks of all the connections.
  21600. This might be useful if some of the processors are doing things like changing
  21601. their channel counts, which could render some connections obsolete.
  21602. */
  21603. bool removeIllegalConnections();
  21604. /** A special number that represents the midi channel of a node.
  21605. This is used as a channel index value if you want to refer to the midi input
  21606. or output instead of an audio channel.
  21607. */
  21608. static const int midiChannelIndex;
  21609. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21610. in order to use the audio that comes into and out of the graph itself.
  21611. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21612. node in the graph which delivers the audio that is coming into the parent
  21613. graph. This allows you to stream the data to other nodes and process the
  21614. incoming audio.
  21615. Likewise, one of these in "output" mode can be sent data which it will add to
  21616. the sum of data being sent to the graph's output.
  21617. @see AudioProcessorGraph
  21618. */
  21619. class AudioGraphIOProcessor : public AudioPluginInstance
  21620. {
  21621. public:
  21622. /** Specifies the mode in which this processor will operate.
  21623. */
  21624. enum IODeviceType
  21625. {
  21626. audioInputNode, /**< In this mode, the processor has output channels
  21627. representing all the audio input channels that are
  21628. coming into its parent audio graph. */
  21629. audioOutputNode, /**< In this mode, the processor has input channels
  21630. representing all the audio output channels that are
  21631. going out of its parent audio graph. */
  21632. midiInputNode, /**< In this mode, the processor has a midi output which
  21633. delivers the same midi data that is arriving at its
  21634. parent graph. */
  21635. midiOutputNode /**< In this mode, the processor has a midi input and
  21636. any data sent to it will be passed out of the parent
  21637. graph. */
  21638. };
  21639. /** Returns the mode of this processor. */
  21640. IODeviceType getType() const throw() { return type; }
  21641. /** Returns the parent graph to which this processor belongs, or 0 if it
  21642. hasn't yet been added to one. */
  21643. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21644. /** True if this is an audio or midi input. */
  21645. bool isInput() const throw();
  21646. /** True if this is an audio or midi output. */
  21647. bool isOutput() const throw();
  21648. AudioGraphIOProcessor (const IODeviceType type);
  21649. ~AudioGraphIOProcessor();
  21650. const String getName() const;
  21651. void fillInPluginDescription (PluginDescription& d) const;
  21652. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21653. void releaseResources();
  21654. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21655. const String getInputChannelName (const int channelIndex) const;
  21656. const String getOutputChannelName (const int channelIndex) const;
  21657. bool isInputChannelStereoPair (int index) const;
  21658. bool isOutputChannelStereoPair (int index) const;
  21659. bool acceptsMidi() const;
  21660. bool producesMidi() const;
  21661. AudioProcessorEditor* createEditor();
  21662. int getNumParameters();
  21663. const String getParameterName (int);
  21664. float getParameter (int);
  21665. const String getParameterText (int);
  21666. void setParameter (int, float);
  21667. int getNumPrograms();
  21668. int getCurrentProgram();
  21669. void setCurrentProgram (int);
  21670. const String getProgramName (int);
  21671. void changeProgramName (int, const String&);
  21672. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21673. void setStateInformation (const void* data, int sizeInBytes);
  21674. /** @internal */
  21675. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21676. juce_UseDebuggingNewOperator
  21677. private:
  21678. const IODeviceType type;
  21679. AudioProcessorGraph* graph;
  21680. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21681. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21682. };
  21683. // AudioProcessor methods:
  21684. const String getName() const;
  21685. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21686. void releaseResources();
  21687. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21688. const String getInputChannelName (const int channelIndex) const;
  21689. const String getOutputChannelName (const int channelIndex) const;
  21690. bool isInputChannelStereoPair (int index) const;
  21691. bool isOutputChannelStereoPair (int index) const;
  21692. bool acceptsMidi() const;
  21693. bool producesMidi() const;
  21694. AudioProcessorEditor* createEditor() { return 0; }
  21695. int getNumParameters() { return 0; }
  21696. const String getParameterName (int) { return String::empty; }
  21697. float getParameter (int) { return 0; }
  21698. const String getParameterText (int) { return String::empty; }
  21699. void setParameter (int, float) { }
  21700. int getNumPrograms() { return 0; }
  21701. int getCurrentProgram() { return 0; }
  21702. void setCurrentProgram (int) { }
  21703. const String getProgramName (int) { return String::empty; }
  21704. void changeProgramName (int, const String&) { }
  21705. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21706. void setStateInformation (const void* data, int sizeInBytes);
  21707. /** @internal */
  21708. void handleAsyncUpdate();
  21709. juce_UseDebuggingNewOperator
  21710. private:
  21711. ReferenceCountedArray <Node> nodes;
  21712. OwnedArray <Connection> connections;
  21713. int lastNodeId;
  21714. AudioSampleBuffer renderingBuffers;
  21715. OwnedArray <MidiBuffer> midiBuffers;
  21716. CriticalSection renderLock;
  21717. VoidArray renderingOps;
  21718. friend class AudioGraphIOProcessor;
  21719. AudioSampleBuffer* currentAudioInputBuffer;
  21720. AudioSampleBuffer currentAudioOutputBuffer;
  21721. MidiBuffer* currentMidiInputBuffer;
  21722. MidiBuffer currentMidiOutputBuffer;
  21723. void clearRenderingSequence();
  21724. void buildRenderingSequence();
  21725. bool isAnInputTo (const uint32 possibleInputId,
  21726. const uint32 possibleDestinationId,
  21727. const int recursionCheck) const throw();
  21728. AudioProcessorGraph (const AudioProcessorGraph&);
  21729. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21730. };
  21731. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21732. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21733. #endif
  21734. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21735. #endif
  21736. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21737. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21738. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21739. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21740. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21741. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21742. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21743. class AudioIODevice;
  21744. /**
  21745. One of these is passed to an AudioIODevice object to stream the audio data
  21746. in and out.
  21747. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21748. method on its own high-priority audio thread, when it needs to send or receive
  21749. the next block of data.
  21750. @see AudioIODevice, AudioDeviceManager
  21751. */
  21752. class JUCE_API AudioIODeviceCallback
  21753. {
  21754. public:
  21755. /** Destructor. */
  21756. virtual ~AudioIODeviceCallback() {}
  21757. /** Processes a block of incoming and outgoing audio data.
  21758. The subclass's implementation should use the incoming audio for whatever
  21759. purposes it needs to, and must fill all the output channels with the next
  21760. block of output data before returning.
  21761. The channel data is arranged with the same array indices as the channel name
  21762. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21763. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21764. associated channel, so remember to check for this.
  21765. @param inputChannelData a set of arrays containing the audio data for each
  21766. incoming channel - this data is valid until the function
  21767. returns. There will be one channel of data for each input
  21768. channel that was enabled when the audio device was opened
  21769. (see AudioIODevice::open())
  21770. @param numInputChannels the number of pointers to channel data in the
  21771. inputChannelData array.
  21772. @param outputChannelData a set of arrays which need to be filled with the data
  21773. that should be sent to each outgoing channel of the device.
  21774. There will be one channel of data for each output channel
  21775. that was enabled when the audio device was opened (see
  21776. AudioIODevice::open())
  21777. The initial contents of the array is undefined, so the
  21778. callback function must fill all the channels with zeros if
  21779. its output is silence. Failing to do this could cause quite
  21780. an unpleasant noise!
  21781. @param numOutputChannels the number of pointers to channel data in the
  21782. outputChannelData array.
  21783. @param numSamples the number of samples in each channel of the input and
  21784. output arrays. The number of samples will depend on the
  21785. audio device's buffer size and will usually remain constant,
  21786. although this isn't guaranteed, so make sure your code can
  21787. cope with reasonable changes in the buffer size from one
  21788. callback to the next.
  21789. */
  21790. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21791. int numInputChannels,
  21792. float** outputChannelData,
  21793. int numOutputChannels,
  21794. int numSamples) = 0;
  21795. /** Called to indicate that the device is about to start calling back.
  21796. This will be called just before the audio callbacks begin, either when this
  21797. callback has just been added to an audio device, or after the device has been
  21798. restarted because of a sample-rate or block-size change.
  21799. You can use this opportunity to find out the sample rate and block size
  21800. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21801. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21802. @param device the audio IO device that will be used to drive the callback.
  21803. Note that if you're going to store this this pointer, it is
  21804. only valid until the next time that audioDeviceStopped is called.
  21805. */
  21806. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21807. /** Called to indicate that the device has stopped.
  21808. */
  21809. virtual void audioDeviceStopped() = 0;
  21810. };
  21811. /**
  21812. Base class for an audio device with synchronised input and output channels.
  21813. Subclasses of this are used to implement different protocols such as DirectSound,
  21814. ASIO, CoreAudio, etc.
  21815. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21816. documentation for that class for more info.
  21817. For an easier way of managing audio devices and their settings, have a look at the
  21818. AudioDeviceManager class.
  21819. @see AudioIODeviceType, AudioDeviceManager
  21820. */
  21821. class JUCE_API AudioIODevice
  21822. {
  21823. public:
  21824. /** Destructor. */
  21825. virtual ~AudioIODevice();
  21826. /** Returns the device's name, (as set in the constructor). */
  21827. const String& getName() const throw() { return name; }
  21828. /** Returns the type of the device.
  21829. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21830. */
  21831. const String& getTypeName() const throw() { return typeName; }
  21832. /** Returns the names of all the available output channels on this device.
  21833. To find out which of these are currently in use, call getActiveOutputChannels().
  21834. */
  21835. virtual const StringArray getOutputChannelNames() = 0;
  21836. /** Returns the names of all the available input channels on this device.
  21837. To find out which of these are currently in use, call getActiveInputChannels().
  21838. */
  21839. virtual const StringArray getInputChannelNames() = 0;
  21840. /** Returns the number of sample-rates this device supports.
  21841. To find out which rates are available on this device, use this method to
  21842. find out how many there are, and getSampleRate() to get the rates.
  21843. @see getSampleRate
  21844. */
  21845. virtual int getNumSampleRates() = 0;
  21846. /** Returns one of the sample-rates this device supports.
  21847. To find out which rates are available on this device, use getNumSampleRates() to
  21848. find out how many there are, and getSampleRate() to get the individual rates.
  21849. The sample rate is set by the open() method.
  21850. (Note that for DirectSound some rates might not work, depending on combinations
  21851. of i/o channels that are being opened).
  21852. @see getNumSampleRates
  21853. */
  21854. virtual double getSampleRate (int index) = 0;
  21855. /** Returns the number of sizes of buffer that are available.
  21856. @see getBufferSizeSamples, getDefaultBufferSize
  21857. */
  21858. virtual int getNumBufferSizesAvailable() = 0;
  21859. /** Returns one of the possible buffer-sizes.
  21860. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21861. @returns a number of samples
  21862. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21863. */
  21864. virtual int getBufferSizeSamples (int index) = 0;
  21865. /** Returns the default buffer-size to use.
  21866. @returns a number of samples
  21867. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21868. */
  21869. virtual int getDefaultBufferSize() = 0;
  21870. /** Tries to open the device ready to play.
  21871. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21872. input channel should be enabled
  21873. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  21874. output channel should be enabled
  21875. @param sampleRate the sample rate to try to use - to find out which rates are
  21876. available, see getNumSampleRates() and getSampleRate()
  21877. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  21878. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  21879. @returns an error description if there's a problem, or an empty string if it succeeds in
  21880. opening the device
  21881. @see close
  21882. */
  21883. virtual const String open (const BitArray& inputChannels,
  21884. const BitArray& outputChannels,
  21885. double sampleRate,
  21886. int bufferSizeSamples) = 0;
  21887. /** Closes and releases the device if it's open. */
  21888. virtual void close() = 0;
  21889. /** Returns true if the device is still open.
  21890. A device might spontaneously close itself if something goes wrong, so this checks if
  21891. it's still open.
  21892. */
  21893. virtual bool isOpen() = 0;
  21894. /** Starts the device actually playing.
  21895. This must be called after the device has been opened.
  21896. @param callback the callback to use for streaming the data.
  21897. @see AudioIODeviceCallback, open
  21898. */
  21899. virtual void start (AudioIODeviceCallback* callback) = 0;
  21900. /** Stops the device playing.
  21901. Once a device has been started, this will stop it. Any pending calls to the
  21902. callback class will be flushed before this method returns.
  21903. */
  21904. virtual void stop() = 0;
  21905. /** Returns true if the device is still calling back.
  21906. The device might mysteriously stop, so this checks whether it's
  21907. still playing.
  21908. */
  21909. virtual bool isPlaying() = 0;
  21910. /** Returns the last error that happened if anything went wrong. */
  21911. virtual const String getLastError() = 0;
  21912. /** Returns the buffer size that the device is currently using.
  21913. If the device isn't actually open, this value doesn't really mean much.
  21914. */
  21915. virtual int getCurrentBufferSizeSamples() = 0;
  21916. /** Returns the sample rate that the device is currently using.
  21917. If the device isn't actually open, this value doesn't really mean much.
  21918. */
  21919. virtual double getCurrentSampleRate() = 0;
  21920. /** Returns the device's current physical bit-depth.
  21921. If the device isn't actually open, this value doesn't really mean much.
  21922. */
  21923. virtual int getCurrentBitDepth() = 0;
  21924. /** Returns a mask showing which of the available output channels are currently
  21925. enabled.
  21926. @see getOutputChannelNames
  21927. */
  21928. virtual const BitArray getActiveOutputChannels() const = 0;
  21929. /** Returns a mask showing which of the available input channels are currently
  21930. enabled.
  21931. @see getInputChannelNames
  21932. */
  21933. virtual const BitArray getActiveInputChannels() const = 0;
  21934. /** Returns the device's output latency.
  21935. This is the delay in samples between a callback getting a block of data, and
  21936. that data actually getting played.
  21937. */
  21938. virtual int getOutputLatencyInSamples() = 0;
  21939. /** Returns the device's input latency.
  21940. This is the delay in samples between some audio actually arriving at the soundcard,
  21941. and the callback getting passed this block of data.
  21942. */
  21943. virtual int getInputLatencyInSamples() = 0;
  21944. /** True if this device can show a pop-up control panel for editing its settings.
  21945. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  21946. to display it.
  21947. */
  21948. virtual bool hasControlPanel() const;
  21949. /** Shows a device-specific control panel if there is one.
  21950. This should only be called for devices which return true from hasControlPanel().
  21951. */
  21952. virtual bool showControlPanel();
  21953. protected:
  21954. /** Creates a device, setting its name and type member variables. */
  21955. AudioIODevice (const String& deviceName,
  21956. const String& typeName);
  21957. /** @internal */
  21958. String name, typeName;
  21959. };
  21960. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21961. /********* End of inlined file: juce_AudioIODevice.h *********/
  21962. /**
  21963. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  21964. To use one of these, just make it the callback used by your AudioIODevice, and
  21965. give it a processor to use by calling setProcessor().
  21966. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  21967. input to send both streams through the processor.
  21968. @see AudioProcessor, AudioProcessorGraph
  21969. */
  21970. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  21971. public MidiInputCallback
  21972. {
  21973. public:
  21974. /**
  21975. */
  21976. AudioProcessorPlayer();
  21977. /** Destructor. */
  21978. virtual ~AudioProcessorPlayer();
  21979. /** Sets the processor that should be played.
  21980. The processor that is passed in will not be deleted or owned by this object.
  21981. To stop anything playing, pass in 0 to this method.
  21982. */
  21983. void setProcessor (AudioProcessor* const processorToPlay);
  21984. /** Returns the current audio processor that is being played.
  21985. */
  21986. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  21987. /** Returns a midi message collector that you can pass midi messages to if you
  21988. want them to be injected into the midi stream that is being sent to the
  21989. processor.
  21990. */
  21991. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  21992. /** @internal */
  21993. void audioDeviceIOCallback (const float** inputChannelData,
  21994. int totalNumInputChannels,
  21995. float** outputChannelData,
  21996. int totalNumOutputChannels,
  21997. int numSamples);
  21998. /** @internal */
  21999. void audioDeviceAboutToStart (AudioIODevice* device);
  22000. /** @internal */
  22001. void audioDeviceStopped();
  22002. /** @internal */
  22003. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22004. juce_UseDebuggingNewOperator
  22005. private:
  22006. AudioProcessor* processor;
  22007. CriticalSection lock;
  22008. double sampleRate;
  22009. int blockSize;
  22010. bool isPrepared;
  22011. int numInputChans, numOutputChans;
  22012. float* channels [128];
  22013. AudioSampleBuffer tempBuffer;
  22014. MidiBuffer incomingMidi;
  22015. MidiMessageCollector messageCollector;
  22016. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22017. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22018. };
  22019. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22020. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22021. #endif
  22022. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22023. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22024. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22025. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22026. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22027. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22028. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22029. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22030. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22031. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22032. class EditableProperty;
  22033. /**
  22034. A base class for a component that goes in a PropertyPanel and displays one of
  22035. an item's properties.
  22036. Subclasses of this are used to display a property in various forms, e.g. a
  22037. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22038. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22039. A subclass must implement the refresh() method which will be called to tell the
  22040. component to update itself, and is also responsible for calling this it when the
  22041. item that it refers to is changed.
  22042. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22043. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22044. */
  22045. class JUCE_API PropertyComponent : public Component
  22046. {
  22047. public:
  22048. /** Creates a PropertyComponent.
  22049. @param propertyName the name is stored as this component's name, and is
  22050. used as the name displayed next to this component in
  22051. a property panel
  22052. @param preferredHeight the height that the component should be given - some
  22053. items may need to be larger than a normal row height.
  22054. This value can also be set if a subclass changes the
  22055. preferredHeight member variable.
  22056. */
  22057. PropertyComponent (const String& propertyName,
  22058. const int preferredHeight = 25);
  22059. /** Destructor. */
  22060. ~PropertyComponent();
  22061. /** Returns this item's preferred height.
  22062. This value is specified either in the constructor or by a subclass changing the
  22063. preferredHeight member variable.
  22064. */
  22065. int getPreferredHeight() const throw() { return preferredHeight; }
  22066. /** Updates the property component if the item it refers to has changed.
  22067. A subclass must implement this method, and other objects may call it to
  22068. force it to refresh itself.
  22069. The subclass should be economical in the amount of work is done, so for
  22070. example it should check whether it really needs to do a repaint rather than
  22071. just doing one every time this method is called, as it may be called when
  22072. the value being displayed hasn't actually changed.
  22073. */
  22074. virtual void refresh() = 0;
  22075. /** The default paint method fills the background and draws a label for the
  22076. item's name.
  22077. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22078. */
  22079. void paint (Graphics& g);
  22080. /** The default resize method positions any child component to the right of this
  22081. one, based on the look and feel's default label size.
  22082. */
  22083. void resized();
  22084. /** By default, this just repaints the component. */
  22085. void enablementChanged();
  22086. juce_UseDebuggingNewOperator
  22087. protected:
  22088. /** Used by the PropertyPanel to determine how high this component needs to be.
  22089. A subclass can update this value in its constructor but shouldn't alter it later
  22090. as changes won't necessarily be picked up.
  22091. */
  22092. int preferredHeight;
  22093. };
  22094. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22095. /********* End of inlined file: juce_PropertyComponent.h *********/
  22096. /********* Start of inlined file: juce_Viewport.h *********/
  22097. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22098. #define __JUCE_VIEWPORT_JUCEHEADER__
  22099. /********* Start of inlined file: juce_ScrollBar.h *********/
  22100. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22101. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22102. /********* Start of inlined file: juce_Button.h *********/
  22103. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22104. #define __JUCE_BUTTON_JUCEHEADER__
  22105. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22106. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22107. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22108. /********* Start of inlined file: juce_TooltipClient.h *********/
  22109. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22110. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22111. /**
  22112. Components that want to use pop-up tooltips should implement this interface.
  22113. A TooltipWindow will wait for the mouse to hover over a component that
  22114. implements the TooltipClient interface, and when it finds one, it will display
  22115. the tooltip returned by its getTooltip() method.
  22116. @see TooltipWindow, SettableTooltipClient
  22117. */
  22118. class JUCE_API TooltipClient
  22119. {
  22120. public:
  22121. /** Destructor. */
  22122. virtual ~TooltipClient() {}
  22123. /** Returns the string that this object wants to show as its tooltip. */
  22124. virtual const String getTooltip() = 0;
  22125. };
  22126. /**
  22127. An implementation of TooltipClient that stores the tooltip string and a method
  22128. for changing it.
  22129. This makes it easy to add a tooltip to a custom component, by simply adding this
  22130. as a base class and calling setTooltip().
  22131. Many of the Juce widgets already use this as a base class to implement their
  22132. tooltips.
  22133. @see TooltipClient, TooltipWindow
  22134. */
  22135. class JUCE_API SettableTooltipClient : public TooltipClient
  22136. {
  22137. public:
  22138. /** Destructor. */
  22139. virtual ~SettableTooltipClient() {}
  22140. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22141. virtual const String getTooltip() { return tooltipString; }
  22142. juce_UseDebuggingNewOperator
  22143. protected:
  22144. String tooltipString;
  22145. };
  22146. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22147. /********* End of inlined file: juce_TooltipClient.h *********/
  22148. /**
  22149. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22150. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22151. object.
  22152. The TooltipWindow object will then stay invisible, waiting until the mouse
  22153. hovers for the specified length of time - it will then see if it's currently
  22154. over a component which implements the TooltipClient interface, and if so,
  22155. it will make itself visible to show the tooltip in the appropriate place.
  22156. @see TooltipClient, SettableTooltipClient
  22157. */
  22158. class JUCE_API TooltipWindow : public Component,
  22159. private Timer
  22160. {
  22161. public:
  22162. /** Creates a tooltip window.
  22163. Make sure your app only creates one instance of this class, otherwise you'll
  22164. get multiple overlaid tooltips appearing. The window will initially be invisible
  22165. and will make itself visible when it needs to display a tip.
  22166. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22167. methods.
  22168. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22169. otherwise the tooltip will be added to the given parent
  22170. component.
  22171. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22172. before a tooltip will be shown
  22173. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22174. */
  22175. TooltipWindow (Component* parentComponent = 0,
  22176. const int millisecondsBeforeTipAppears = 700);
  22177. /** Destructor. */
  22178. ~TooltipWindow();
  22179. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22180. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22181. methods.
  22182. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22183. */
  22184. enum ColourIds
  22185. {
  22186. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22187. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22188. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22189. };
  22190. juce_UseDebuggingNewOperator
  22191. private:
  22192. const int millisecondsBeforeTipAppears;
  22193. int mouseX, mouseY, mouseClicks;
  22194. unsigned int lastMouseMoveTime, lastHideTime;
  22195. Component* lastComponentUnderMouse;
  22196. bool changedCompsSinceShown;
  22197. String tip;
  22198. void paint (Graphics& g);
  22199. void mouseEnter (const MouseEvent& e);
  22200. void timerCallback();
  22201. void showFor (Component* const c);
  22202. void hide();
  22203. TooltipWindow (const TooltipWindow&);
  22204. const TooltipWindow& operator= (const TooltipWindow&);
  22205. };
  22206. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22207. /********* End of inlined file: juce_TooltipWindow.h *********/
  22208. class Button;
  22209. /**
  22210. Used to receive callbacks when a button is clicked.
  22211. @see Button::addButtonListener, Button::removeButtonListener
  22212. */
  22213. class JUCE_API ButtonListener
  22214. {
  22215. public:
  22216. /** Destructor. */
  22217. virtual ~ButtonListener() {}
  22218. /** Called when the button is clicked. */
  22219. virtual void buttonClicked (Button* button) = 0;
  22220. /** Called when the button's state changes. */
  22221. virtual void buttonStateChanged (Button*) {}
  22222. };
  22223. /**
  22224. A base class for buttons.
  22225. This contains all the logic for button behaviours such as enabling/disabling,
  22226. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22227. and radio groups, etc.
  22228. @see TextButton, DrawableButton, ToggleButton
  22229. */
  22230. class JUCE_API Button : public Component,
  22231. public SettableTooltipClient,
  22232. public ApplicationCommandManagerListener,
  22233. private KeyListener
  22234. {
  22235. protected:
  22236. /** Creates a button.
  22237. @param buttonName the text to put in the button (the component's name is also
  22238. initially set to this string, but these can be changed later
  22239. using the setName() and setButtonText() methods)
  22240. */
  22241. Button (const String& buttonName);
  22242. public:
  22243. /** Destructor. */
  22244. virtual ~Button();
  22245. /** Changes the button's text.
  22246. @see getButtonText
  22247. */
  22248. void setButtonText (const String& newText) throw();
  22249. /** Returns the text displayed in the button.
  22250. @see setButtonText
  22251. */
  22252. const String getButtonText() const throw() { return text; }
  22253. /** Returns true if the button is currently being held down by the mouse.
  22254. @see isOver
  22255. */
  22256. bool isDown() const throw();
  22257. /** Returns true if the mouse is currently over the button.
  22258. This will be also be true if the mouse is being held down.
  22259. @see isDown
  22260. */
  22261. bool isOver() const throw();
  22262. /** A button has an on/off state associated with it, and this changes that.
  22263. By default buttons are 'off' and for simple buttons that you click to perform
  22264. an action you won't change this. Toggle buttons, however will want to
  22265. change their state when turned on or off.
  22266. @param shouldBeOn whether to set the button's toggle state to be on or
  22267. off. If it's a member of a button group, this will
  22268. always try to turn it on, and to turn off any other
  22269. buttons in the group
  22270. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22271. the button will be repainted but no notification will
  22272. be sent
  22273. @see getToggleState, setRadioGroupId
  22274. */
  22275. void setToggleState (const bool shouldBeOn,
  22276. const bool sendChangeNotification);
  22277. /** Returns true if the button in 'on'.
  22278. By default buttons are 'off' and for simple buttons that you click to perform
  22279. an action you won't change this. Toggle buttons, however will want to
  22280. change their state when turned on or off.
  22281. @see setToggleState
  22282. */
  22283. bool getToggleState() const throw() { return isOn; }
  22284. /** This tells the button to automatically flip the toggle state when
  22285. the button is clicked.
  22286. If set to true, then before the clicked() callback occurs, the toggle-state
  22287. of the button is flipped.
  22288. */
  22289. void setClickingTogglesState (const bool shouldToggle) throw();
  22290. /** Returns true if this button is set to be an automatic toggle-button.
  22291. This returns the last value that was passed to setClickingTogglesState().
  22292. */
  22293. bool getClickingTogglesState() const throw();
  22294. /** Enables the button to act as a member of a mutually-exclusive group
  22295. of 'radio buttons'.
  22296. If the group ID is set to a non-zero number, then this button will
  22297. act as part of a group of buttons with the same ID, only one of
  22298. which can be 'on' at the same time. Note that when it's part of
  22299. a group, clicking a toggle-button that's 'on' won't turn it off.
  22300. To find other buttons with the same ID, this button will search through
  22301. its sibling components for ToggleButtons, so all the buttons for a
  22302. particular group must be placed inside the same parent component.
  22303. Set the group ID back to zero if you want it to act as a normal toggle
  22304. button again.
  22305. @see getRadioGroupId
  22306. */
  22307. void setRadioGroupId (const int newGroupId);
  22308. /** Returns the ID of the group to which this button belongs.
  22309. (See setRadioGroupId() for an explanation of this).
  22310. */
  22311. int getRadioGroupId() const throw() { return radioGroupId; }
  22312. /** Registers a listener to receive events when this button's state changes.
  22313. If the listener is already registered, this will not register it again.
  22314. @see removeButtonListener
  22315. */
  22316. void addButtonListener (ButtonListener* const newListener) throw();
  22317. /** Removes a previously-registered button listener
  22318. @see addButtonListener
  22319. */
  22320. void removeButtonListener (ButtonListener* const listener) throw();
  22321. /** Causes the button to act as if it's been clicked.
  22322. This will asynchronously make the button draw itself going down and up, and
  22323. will then call back the clicked() method as if mouse was clicked on it.
  22324. @see clicked
  22325. */
  22326. virtual void triggerClick();
  22327. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22328. When the button is pressed, it will use the given manager to trigger the
  22329. command ID.
  22330. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22331. before this button is. To disable the command triggering, call this method and
  22332. pass 0 for the parameters.
  22333. If generateTooltip is true, then the button's tooltip will be automatically
  22334. generated based on the name of this command and its current shortcut key.
  22335. @see addShortcut, getCommandID
  22336. */
  22337. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22338. const int commandID,
  22339. const bool generateTooltip);
  22340. /** Returns the command ID that was set by setCommandToTrigger().
  22341. */
  22342. int getCommandID() const throw() { return commandID; }
  22343. /** Assigns a shortcut key to trigger the button.
  22344. The button registers itself with its top-level parent component for keypresses.
  22345. Note that a different way of linking buttons to keypresses is by using the
  22346. setKeyPressToTrigger() method to invoke a command - the difference being that
  22347. setting a shortcut allows the button to be temporarily linked to a keypress
  22348. only while it's on-screen.
  22349. @see clearShortcuts
  22350. */
  22351. void addShortcut (const KeyPress& key);
  22352. /** Removes all key shortcuts that had been set for this button.
  22353. @see addShortcut
  22354. */
  22355. void clearShortcuts();
  22356. /** Returns true if the given keypress is a shortcut for this button.
  22357. @see addShortcut
  22358. */
  22359. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22360. /** Sets an auto-repeat speed for the button when it is held down.
  22361. (Auto-repeat is disabled by default).
  22362. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22363. triggering the next click. If this is zero, auto-repeat
  22364. is disabled
  22365. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22366. triggered
  22367. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22368. get faster, the longer the button is held down, up to the
  22369. minimum interval specified here
  22370. */
  22371. void setRepeatSpeed (const int initialDelayInMillisecs,
  22372. const int repeatDelayInMillisecs,
  22373. const int minimumDelayInMillisecs = -1) throw();
  22374. /** Sets whether the button click should happen when the mouse is pressed or released.
  22375. By default the button is only considered to have been clicked when the mouse is
  22376. released, but setting this to true will make it call the clicked() method as soon
  22377. as the button is pressed.
  22378. This is useful if the button is being used to show a pop-up menu, as it allows
  22379. the click to be used as a drag onto the menu.
  22380. */
  22381. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22382. /** Returns the number of milliseconds since the last time the button
  22383. went into the 'down' state.
  22384. */
  22385. uint32 getMillisecondsSinceButtonDown() const throw();
  22386. /** (overridden from Component to do special stuff). */
  22387. void setVisible (bool shouldBeVisible);
  22388. /** Sets the tooltip for this button.
  22389. @see TooltipClient, TooltipWindow
  22390. */
  22391. void setTooltip (const String& newTooltip);
  22392. // (implementation of the TooltipClient method)
  22393. const String getTooltip();
  22394. /** A combination of these flags are used by setConnectedEdges().
  22395. */
  22396. enum ConnectedEdgeFlags
  22397. {
  22398. ConnectedOnLeft = 1,
  22399. ConnectedOnRight = 2,
  22400. ConnectedOnTop = 4,
  22401. ConnectedOnBottom = 8
  22402. };
  22403. /** Hints about which edges of the button might be connected to adjoining buttons.
  22404. The value passed in is a bitwise combination of any of the values in the
  22405. ConnectedEdgeFlags enum.
  22406. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22407. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22408. without rounded corners on the edges that connect. It's only a hint, so the
  22409. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22410. button.
  22411. */
  22412. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22413. /** Returns the set of flags passed into setConnectedEdges(). */
  22414. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22415. /** Indicates whether the button adjoins another one on its left edge.
  22416. @see setConnectedEdges
  22417. */
  22418. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22419. /** Indicates whether the button adjoins another one on its right edge.
  22420. @see setConnectedEdges
  22421. */
  22422. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22423. /** Indicates whether the button adjoins another one on its top edge.
  22424. @see setConnectedEdges
  22425. */
  22426. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22427. /** Indicates whether the button adjoins another one on its bottom edge.
  22428. @see setConnectedEdges
  22429. */
  22430. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22431. /** Used by setState(). */
  22432. enum ButtonState
  22433. {
  22434. buttonNormal,
  22435. buttonOver,
  22436. buttonDown
  22437. };
  22438. /** Can be used to force the button into a particular state.
  22439. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22440. from happening.
  22441. The state that you set here will only last until it is automatically changed when the mouse
  22442. enters or exits the button, or the mouse-button is pressed or released.
  22443. */
  22444. void setState (const ButtonState newState);
  22445. juce_UseDebuggingNewOperator
  22446. protected:
  22447. /** This method is called when the button has been clicked.
  22448. Subclasses can override this to perform whatever they actions they need
  22449. to do.
  22450. Alternatively, a ButtonListener can be added to the button, and these listeners
  22451. will be called when the click occurs.
  22452. @see triggerClick
  22453. */
  22454. virtual void clicked();
  22455. /** This method is called when the button has been clicked.
  22456. By default it just calls clicked(), but you might want to override it to handle
  22457. things like clicking when a modifier key is pressed, etc.
  22458. @see ModifierKeys
  22459. */
  22460. virtual void clicked (const ModifierKeys& modifiers);
  22461. /** Subclasses should override this to actually paint the button's contents.
  22462. It's better to use this than the paint method, because it gives you information
  22463. about the over/down state of the button.
  22464. @param g the graphics context to use
  22465. @param isMouseOverButton true if the button is either in the 'over' or
  22466. 'down' state
  22467. @param isButtonDown true if the button should be drawn in the 'down' position
  22468. */
  22469. virtual void paintButton (Graphics& g,
  22470. bool isMouseOverButton,
  22471. bool isButtonDown) = 0;
  22472. /** Called when the button's up/down/over state changes.
  22473. Subclasses can override this if they need to do something special when the button
  22474. goes up or down.
  22475. @see isDown, isOver
  22476. */
  22477. virtual void buttonStateChanged();
  22478. /** @internal */
  22479. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22480. /** @internal */
  22481. void handleCommandMessage (int commandId);
  22482. /** @internal */
  22483. void mouseEnter (const MouseEvent& e);
  22484. /** @internal */
  22485. void mouseExit (const MouseEvent& e);
  22486. /** @internal */
  22487. void mouseDown (const MouseEvent& e);
  22488. /** @internal */
  22489. void mouseDrag (const MouseEvent& e);
  22490. /** @internal */
  22491. void mouseUp (const MouseEvent& e);
  22492. /** @internal */
  22493. bool keyPressed (const KeyPress& key);
  22494. /** @internal */
  22495. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22496. /** @internal */
  22497. bool keyStateChanged (Component* originatingComponent);
  22498. /** @internal */
  22499. void paint (Graphics& g);
  22500. /** @internal */
  22501. void parentHierarchyChanged();
  22502. /** @internal */
  22503. void focusGained (FocusChangeType cause);
  22504. /** @internal */
  22505. void focusLost (FocusChangeType cause);
  22506. /** @internal */
  22507. void enablementChanged();
  22508. /** @internal */
  22509. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22510. /** @internal */
  22511. void applicationCommandListChanged();
  22512. private:
  22513. Array <KeyPress> shortcuts;
  22514. Component* keySource;
  22515. String text;
  22516. SortedSet <void*> buttonListeners;
  22517. friend class InternalButtonRepeatTimer;
  22518. Timer* repeatTimer;
  22519. uint32 buttonPressTime, lastTimeCallbackTime;
  22520. ApplicationCommandManager* commandManagerToUse;
  22521. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22522. int radioGroupId, commandID, connectedEdgeFlags;
  22523. ButtonState buttonState;
  22524. bool isOn : 1;
  22525. bool clickTogglesState : 1;
  22526. bool needsToRelease : 1;
  22527. bool needsRepainting : 1;
  22528. bool isKeyDown : 1;
  22529. bool triggerOnMouseDown : 1;
  22530. bool generateTooltip : 1;
  22531. void repeatTimerCallback() throw();
  22532. Timer& getRepeatTimer() throw();
  22533. ButtonState updateState (const MouseEvent* const e) throw();
  22534. bool isShortcutPressed() const throw();
  22535. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22536. void flashButtonState() throw();
  22537. void sendClickMessage (const ModifierKeys& modifiers);
  22538. void sendStateMessage();
  22539. Button (const Button&);
  22540. const Button& operator= (const Button&);
  22541. };
  22542. #endif // __JUCE_BUTTON_JUCEHEADER__
  22543. /********* End of inlined file: juce_Button.h *********/
  22544. class ScrollBar;
  22545. /**
  22546. A class for receiving events from a ScrollBar.
  22547. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22548. method, and it will be called when the bar's position changes.
  22549. @see ScrollBar::addListener, ScrollBar::removeListener
  22550. */
  22551. class JUCE_API ScrollBarListener
  22552. {
  22553. public:
  22554. /** Destructor. */
  22555. virtual ~ScrollBarListener() {}
  22556. /** Called when a ScrollBar is moved.
  22557. @param scrollBarThatHasMoved the bar that has moved
  22558. @param newRangeStart the new range start of this bar
  22559. */
  22560. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22561. const double newRangeStart) = 0;
  22562. };
  22563. /**
  22564. A scrollbar component.
  22565. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22566. sets the range of values it can represent. Then you can use setCurrentRange() to
  22567. change the position and size of the scrollbar's 'thumb'.
  22568. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22569. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22570. they moved it to.
  22571. The scrollbar will adjust its own visibility according to whether its thumb size
  22572. allows it to actually be scrolled.
  22573. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22574. instead of handling a scrollbar directly.
  22575. @see ScrollBarListener
  22576. */
  22577. class JUCE_API ScrollBar : public Component,
  22578. public AsyncUpdater,
  22579. private Timer
  22580. {
  22581. public:
  22582. /** Creates a Scrollbar.
  22583. @param isVertical whether it should be a vertical or horizontal bar
  22584. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22585. */
  22586. ScrollBar (const bool isVertical,
  22587. const bool buttonsAreVisible = true);
  22588. /** Destructor. */
  22589. ~ScrollBar();
  22590. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22591. bool isVertical() const throw() { return vertical; }
  22592. /** Changes the scrollbar's direction.
  22593. You'll also need to resize the bar appropriately - this just changes its internal
  22594. layout.
  22595. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22596. */
  22597. void setOrientation (const bool shouldBeVertical) throw();
  22598. /** Shows or hides the scrollbar's buttons. */
  22599. void setButtonVisibility (const bool buttonsAreVisible);
  22600. /** Tells the scrollbar whether to make itself invisible when not needed.
  22601. The default behaviour is for a scrollbar to become invisible when the thumb
  22602. fills the whole of its range (i.e. when it can't be moved). Setting this
  22603. value to false forces the bar to always be visible.
  22604. */
  22605. void setAutoHide (const bool shouldHideWhenFullRange);
  22606. /** Sets the minimum and maximum values that the bar will move between.
  22607. The bar's thumb will always be constrained so that the top of the thumb
  22608. will be >= minimum, and the bottom of the thumb <= maximum.
  22609. @see setCurrentRange
  22610. */
  22611. void setRangeLimits (const double minimum,
  22612. const double maximum) throw();
  22613. /** Returns the lower value that the thumb can be set to.
  22614. This is the value set by setRangeLimits().
  22615. */
  22616. double getMinimumRangeLimit() const throw() { return minimum; }
  22617. /** Returns the upper value that the thumb can be set to.
  22618. This is the value set by setRangeLimits().
  22619. */
  22620. double getMaximumRangeLimit() const throw() { return maximum; }
  22621. /** Changes the position of the scrollbar's 'thumb'.
  22622. This sets both the position and size of the thumb - to just set the position without
  22623. changing the size, you can use setCurrentRangeStart().
  22624. If this method call actually changes the scrollbar's position, it will trigger an
  22625. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22626. are registered.
  22627. @param newStart the top (or left) of the thumb, in the range
  22628. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22629. value is beyond these limits, it will be clipped.
  22630. @param newSize the size of the thumb, such that
  22631. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22632. size is beyond these limits, it will be clipped.
  22633. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22634. */
  22635. void setCurrentRange (double newStart,
  22636. double newSize) throw();
  22637. /** Moves the bar's thumb position.
  22638. This will move the thumb position without changing the thumb size. Note
  22639. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22640. If this method call actually changes the scrollbar's position, it will trigger an
  22641. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22642. are registered.
  22643. @see setCurrentRange
  22644. */
  22645. void setCurrentRangeStart (double newStart) throw();
  22646. /** Returns the position of the top of the thumb.
  22647. @see setCurrentRangeStart
  22648. */
  22649. double getCurrentRangeStart() const throw() { return rangeStart; }
  22650. /** Returns the current size of the thumb.
  22651. @see setCurrentRange
  22652. */
  22653. double getCurrentRangeSize() const throw() { return rangeSize; }
  22654. /** Sets the amount by which the up and down buttons will move the bar.
  22655. The value here is in terms of the total range, and is added or subtracted
  22656. from the thumb position when the user clicks an up/down (or left/right) button.
  22657. */
  22658. void setSingleStepSize (const double newSingleStepSize) throw();
  22659. /** Moves the scrollbar by a number of single-steps.
  22660. This will move the bar by a multiple of its single-step interval (as
  22661. specified using the setSingleStepSize() method).
  22662. A positive value here will move the bar down or to the right, a negative
  22663. value moves it up or to the left.
  22664. */
  22665. void moveScrollbarInSteps (const int howManySteps) throw();
  22666. /** Moves the scroll bar up or down in pages.
  22667. This will move the bar by a multiple of its current thumb size, effectively
  22668. doing a page-up or down.
  22669. A positive value here will move the bar down or to the right, a negative
  22670. value moves it up or to the left.
  22671. */
  22672. void moveScrollbarInPages (const int howManyPages) throw();
  22673. /** Scrolls to the top (or left).
  22674. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22675. */
  22676. void scrollToTop() throw();
  22677. /** Scrolls to the bottom (or right).
  22678. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22679. */
  22680. void scrollToBottom() throw();
  22681. /** Changes the delay before the up and down buttons autorepeat when they are held
  22682. down.
  22683. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22684. @see Button::setRepeatSpeed
  22685. */
  22686. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22687. const int repeatDelayInMillisecs,
  22688. const int minimumDelayInMillisecs = -1) throw();
  22689. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22690. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22691. methods.
  22692. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22693. */
  22694. enum ColourIds
  22695. {
  22696. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22697. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22698. 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. */
  22699. };
  22700. /** Registers a listener that will be called when the scrollbar is moved. */
  22701. void addListener (ScrollBarListener* const listener) throw();
  22702. /** Deregisters a previously-registered listener. */
  22703. void removeListener (ScrollBarListener* const listener) throw();
  22704. /** @internal */
  22705. bool keyPressed (const KeyPress& key);
  22706. /** @internal */
  22707. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22708. /** @internal */
  22709. void lookAndFeelChanged();
  22710. /** @internal */
  22711. void handleAsyncUpdate();
  22712. /** @internal */
  22713. void mouseDown (const MouseEvent& e);
  22714. /** @internal */
  22715. void mouseDrag (const MouseEvent& e);
  22716. /** @internal */
  22717. void mouseUp (const MouseEvent& e);
  22718. /** @internal */
  22719. void paint (Graphics& g);
  22720. /** @internal */
  22721. void resized();
  22722. juce_UseDebuggingNewOperator
  22723. private:
  22724. double minimum, maximum;
  22725. double rangeStart, rangeSize;
  22726. double singleStepSize, dragStartRange;
  22727. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22728. int dragStartMousePos, lastMousePos;
  22729. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22730. bool vertical, isDraggingThumb, alwaysVisible;
  22731. Button* upButton;
  22732. Button* downButton;
  22733. SortedSet <void*> listeners;
  22734. void updateThumbPosition() throw();
  22735. void timerCallback();
  22736. ScrollBar (const ScrollBar&);
  22737. const ScrollBar& operator= (const ScrollBar&);
  22738. };
  22739. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22740. /********* End of inlined file: juce_ScrollBar.h *********/
  22741. /**
  22742. A Viewport is used to contain a larger child component, and allows the child
  22743. to be automatically scrolled around.
  22744. To use a Viewport, just create one and set the component that goes inside it
  22745. using the setViewedComponent() method. When the child component changes size,
  22746. the Viewport will adjust its scrollbars accordingly.
  22747. A subclass of the viewport can be created which will receive calls to its
  22748. visibleAreaChanged() method when the subcomponent changes position or size.
  22749. */
  22750. class JUCE_API Viewport : public Component,
  22751. private ComponentListener,
  22752. private ScrollBarListener
  22753. {
  22754. public:
  22755. /** Creates a Viewport.
  22756. The viewport is initially empty - use the setViewedComponent() method to
  22757. add a child component for it to manage.
  22758. */
  22759. Viewport (const String& componentName = String::empty);
  22760. /** Destructor. */
  22761. ~Viewport();
  22762. /** Sets the component that this viewport will contain and scroll around.
  22763. This will add the given component to this Viewport and position it at
  22764. (0, 0).
  22765. (Don't add or remove any child components directly using the normal
  22766. Component::addChildComponent() methods).
  22767. @param newViewedComponent the component to add to this viewport (this pointer
  22768. may be null). The component passed in will be deleted
  22769. by the Viewport when it's no longer needed
  22770. @see getViewedComponent
  22771. */
  22772. void setViewedComponent (Component* const newViewedComponent);
  22773. /** Returns the component that's currently being used inside the Viewport.
  22774. @see setViewedComponent
  22775. */
  22776. Component* getViewedComponent() const throw() { return contentComp; }
  22777. /** Changes the position of the viewed component.
  22778. The inner component will be moved so that the pixel at the top left of
  22779. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22780. within the inner component.
  22781. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22782. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22783. */
  22784. void setViewPosition (const int xPixelsOffset,
  22785. const int yPixelsOffset);
  22786. /** Changes the view position as a proportion of the distance it can move.
  22787. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22788. visible area in the top-left, and (1, 1) would put it as far down and
  22789. to the right as it's possible to go whilst keeping the child component
  22790. on-screen.
  22791. */
  22792. void setViewPositionProportionately (const double proportionX,
  22793. const double proportionY);
  22794. /** Returns the position within the child component of the top-left of its visible area.
  22795. @see getViewWidth, setViewPosition
  22796. */
  22797. int getViewPositionX() const throw() { return lastVX; }
  22798. /** Returns the position within the child component of the top-left of its visible area.
  22799. @see getViewHeight, setViewPosition
  22800. */
  22801. int getViewPositionY() const throw() { return lastVY; }
  22802. /** Returns the width of the visible area of the child component.
  22803. This may be less than the width of this Viewport if there's a vertical scrollbar
  22804. or if the child component is itself smaller.
  22805. */
  22806. int getViewWidth() const throw() { return lastVW; }
  22807. /** Returns the height of the visible area of the child component.
  22808. This may be less than the height of this Viewport if there's a horizontal scrollbar
  22809. or if the child component is itself smaller.
  22810. */
  22811. int getViewHeight() const throw() { return lastVH; }
  22812. /** Returns the width available within this component for the contents.
  22813. This will be the width of the viewport component minus the width of a
  22814. vertical scrollbar (if visible).
  22815. */
  22816. int getMaximumVisibleWidth() const throw();
  22817. /** Returns the height available within this component for the contents.
  22818. This will be the height of the viewport component minus the space taken up
  22819. by a horizontal scrollbar (if visible).
  22820. */
  22821. int getMaximumVisibleHeight() const throw();
  22822. /** Callback method that is called when the visible area changes.
  22823. This will be called when the visible area is moved either be scrolling or
  22824. by calls to setViewPosition(), etc.
  22825. */
  22826. virtual void visibleAreaChanged (int visibleX, int visibleY,
  22827. int visibleW, int visibleH);
  22828. /** Turns scrollbars on or off.
  22829. If set to false, the scrollbars won't ever appear. When true (the default)
  22830. they will appear only when needed.
  22831. */
  22832. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  22833. const bool showHorizontalScrollbarIfNeeded);
  22834. /** True if the vertical scrollbar is enabled.
  22835. @see setScrollBarsShown
  22836. */
  22837. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  22838. /** True if the horizontal scrollbar is enabled.
  22839. @see setScrollBarsShown
  22840. */
  22841. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  22842. /** Changes the width of the scrollbars.
  22843. If this isn't specified, the default width from the LookAndFeel class will be used.
  22844. @see LookAndFeel::getDefaultScrollbarWidth
  22845. */
  22846. void setScrollBarThickness (const int thickness);
  22847. /** Returns the thickness of the scrollbars.
  22848. @see setScrollBarThickness
  22849. */
  22850. int getScrollBarThickness() const throw();
  22851. /** Changes the distance that a single-step click on a scrollbar button
  22852. will move the viewport.
  22853. */
  22854. void setSingleStepSizes (const int stepX, const int stepY);
  22855. /** Shows or hides the buttons on any scrollbars that are used.
  22856. @see ScrollBar::setButtonVisibility
  22857. */
  22858. void setScrollBarButtonVisibility (const bool buttonsVisible);
  22859. /** Returns a pointer to the scrollbar component being used.
  22860. Handy if you need to customise the bar somehow.
  22861. */
  22862. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  22863. /** Returns a pointer to the scrollbar component being used.
  22864. Handy if you need to customise the bar somehow.
  22865. */
  22866. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  22867. juce_UseDebuggingNewOperator
  22868. /** @internal */
  22869. void resized();
  22870. /** @internal */
  22871. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  22872. /** @internal */
  22873. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22874. /** @internal */
  22875. bool keyPressed (const KeyPress& key);
  22876. /** @internal */
  22877. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  22878. /** @internal */
  22879. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22880. private:
  22881. Component* contentComp;
  22882. int lastVX, lastVY, lastVW, lastVH;
  22883. int scrollBarThickness;
  22884. int singleStepX, singleStepY;
  22885. bool showHScrollbar, showVScrollbar;
  22886. Component* contentHolder;
  22887. ScrollBar* verticalScrollBar;
  22888. ScrollBar* horizontalScrollBar;
  22889. void updateVisibleRegion();
  22890. Viewport (const Viewport&);
  22891. const Viewport& operator= (const Viewport&);
  22892. };
  22893. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  22894. /********* End of inlined file: juce_Viewport.h *********/
  22895. /**
  22896. A panel that holds a list of PropertyComponent objects.
  22897. This panel displays a list of PropertyComponents, and allows them to be organised
  22898. into collapsible sections.
  22899. To use, simply create one of these and add your properties to it with addProperties()
  22900. or addSection().
  22901. @see PropertyComponent
  22902. */
  22903. class JUCE_API PropertyPanel : public Component
  22904. {
  22905. public:
  22906. /** Creates an empty property panel. */
  22907. PropertyPanel();
  22908. /** Destructor. */
  22909. ~PropertyPanel();
  22910. /** Deletes all property components from the panel.
  22911. */
  22912. void clear();
  22913. /** Adds a set of properties to the panel.
  22914. The components in the list will be owned by this object and will be automatically
  22915. deleted later on when no longer needed.
  22916. These properties are added without them being inside a named section. If you
  22917. want them to be kept together in a collapsible section, use addSection() instead.
  22918. */
  22919. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  22920. /** Adds a set of properties to the panel.
  22921. These properties are added at the bottom of the list, under a section heading with
  22922. a plus/minus button that allows it to be opened and closed.
  22923. The components in the list will be owned by this object and will be automatically
  22924. deleted later on when no longer needed.
  22925. To add properies without them being in a section, use addProperties().
  22926. */
  22927. void addSection (const String& sectionTitle,
  22928. const Array <PropertyComponent*>& newPropertyComponents,
  22929. const bool shouldSectionInitiallyBeOpen = true);
  22930. /** Calls the refresh() method of all PropertyComponents in the panel */
  22931. void refreshAll() const;
  22932. /** Returns a list of all the names of sections in the panel.
  22933. These are the sections that have been added with addSection().
  22934. */
  22935. const StringArray getSectionNames() const;
  22936. /** Returns true if the section at this index is currently open.
  22937. The index is from 0 up to the number of items returned by getSectionNames().
  22938. */
  22939. bool isSectionOpen (const int sectionIndex) const;
  22940. /** Opens or closes one of the sections.
  22941. The index is from 0 up to the number of items returned by getSectionNames().
  22942. */
  22943. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  22944. /** Enables or disables one of the sections.
  22945. The index is from 0 up to the number of items returned by getSectionNames().
  22946. */
  22947. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  22948. /** Saves the current state of open/closed sections so it can be restored later.
  22949. The caller is responsible for deleting the object that is returned.
  22950. To restore this state, use restoreOpennessState().
  22951. @see restoreOpennessState
  22952. */
  22953. XmlElement* getOpennessState() const;
  22954. /** Restores a previously saved arrangement of open/closed sections.
  22955. This will try to restore a snapshot of the panel's state that was created by
  22956. the getOpennessState() method. If any of the sections named in the original
  22957. XML aren't present, they will be ignored.
  22958. @see getOpennessState
  22959. */
  22960. void restoreOpennessState (const XmlElement& newState);
  22961. /** Sets a message to be displayed when there are no properties in the panel.
  22962. The default message is "nothing selected".
  22963. */
  22964. void setMessageWhenEmpty (const String& newMessage);
  22965. /** Returns the message that is displayed when there are no properties.
  22966. @see setMessageWhenEmpty
  22967. */
  22968. const String& getMessageWhenEmpty() const throw();
  22969. /** @internal */
  22970. void paint (Graphics& g);
  22971. /** @internal */
  22972. void resized();
  22973. juce_UseDebuggingNewOperator
  22974. private:
  22975. Viewport* viewport;
  22976. Component* propertyHolderComponent;
  22977. String messageWhenEmpty;
  22978. void updatePropHolderLayout() const;
  22979. void updatePropHolderLayout (const int width) const;
  22980. };
  22981. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  22982. /********* End of inlined file: juce_PropertyPanel.h *********/
  22983. /**
  22984. A type of UI component that displays the parameters of an AudioProcessor as
  22985. a simple list of sliders.
  22986. This can be used for showing an editor for a processor that doesn't supply
  22987. its own custom editor.
  22988. @see AudioProcessor
  22989. */
  22990. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  22991. {
  22992. public:
  22993. GenericAudioProcessorEditor (AudioProcessor* const owner);
  22994. ~GenericAudioProcessorEditor();
  22995. void paint (Graphics& g);
  22996. void resized();
  22997. juce_UseDebuggingNewOperator
  22998. private:
  22999. PropertyPanel* panel;
  23000. };
  23001. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23002. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23003. #endif
  23004. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23005. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23006. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23007. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23008. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23009. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23010. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23011. /********* Start of inlined file: juce_AudioSource.h *********/
  23012. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23013. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23014. /**
  23015. Used by AudioSource::getNextAudioBlock().
  23016. */
  23017. struct JUCE_API AudioSourceChannelInfo
  23018. {
  23019. /** The destination buffer to fill with audio data.
  23020. When the AudioSource::getNextAudioBlock() method is called, the active section
  23021. of this buffer should be filled with whatever output the source produces.
  23022. Only the samples specified by the startSample and numSamples members of this structure
  23023. should be affected by the call.
  23024. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23025. method can be treated as the input if the source is performing some kind of filter operation,
  23026. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23027. a handy way of doing this.
  23028. The number of channels in the buffer could be anything, so the AudioSource
  23029. must cope with this in whatever way is appropriate for its function.
  23030. */
  23031. AudioSampleBuffer* buffer;
  23032. /** The first sample in the buffer from which the callback is expected
  23033. to write data. */
  23034. int startSample;
  23035. /** The number of samples in the buffer which the callback is expected to
  23036. fill with data. */
  23037. int numSamples;
  23038. /** Convenient method to clear the buffer if the source is not producing any data. */
  23039. void clearActiveBufferRegion() const
  23040. {
  23041. if (buffer != 0)
  23042. buffer->clear (startSample, numSamples);
  23043. }
  23044. };
  23045. /**
  23046. Base class for objects that can produce a continuous stream of audio.
  23047. @see AudioFormatReaderSource, ResamplingAudioSource
  23048. */
  23049. class JUCE_API AudioSource
  23050. {
  23051. protected:
  23052. /** Creates an AudioSource. */
  23053. AudioSource() throw() {}
  23054. public:
  23055. /** Destructor. */
  23056. virtual ~AudioSource() {}
  23057. /** Tells the source to prepare for playing.
  23058. The source can use this opportunity to initialise anything it needs to.
  23059. Note that this method could be called more than once in succession without
  23060. a matching call to releaseResources(), so make sure your code is robust and
  23061. can handle that kind of situation.
  23062. @param samplesPerBlockExpected the number of samples that the source
  23063. will be expected to supply each time its
  23064. getNextAudioBlock() method is called. This
  23065. number may vary slightly, because it will be dependent
  23066. on audio hardware callbacks, and these aren't
  23067. guaranteed to always use a constant block size, so
  23068. the source should be able to cope with small variations.
  23069. @param sampleRate the sample rate that the output will be used at - this
  23070. is needed by sources such as tone generators.
  23071. @see releaseResources, getNextAudioBlock
  23072. */
  23073. virtual void prepareToPlay (int samplesPerBlockExpected,
  23074. double sampleRate) = 0;
  23075. /** Allows the source to release anything it no longer needs after playback has stopped.
  23076. This will be called when the source is no longer going to have its getNextAudioBlock()
  23077. method called, so it should release any spare memory, etc. that it might have
  23078. allocated during the prepareToPlay() call.
  23079. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23080. releaseResources(), and it may be called more than once in succession, so make sure your
  23081. code is robust and doesn't make any assumptions about when it will be called.
  23082. @see prepareToPlay, getNextAudioBlock
  23083. */
  23084. virtual void releaseResources() = 0;
  23085. /** Called repeatedly to fetch subsequent blocks of audio data.
  23086. After calling the prepareToPlay() method, this callback will be made each
  23087. time the audio playback hardware (or whatever other destination the audio
  23088. data is going to) needs another block of data.
  23089. It will generally be called on a high-priority system thread, or possibly even
  23090. an interrupt, so be careful not to do too much work here, as that will cause
  23091. audio glitches!
  23092. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23093. */
  23094. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23095. };
  23096. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23097. /********* End of inlined file: juce_AudioSource.h *********/
  23098. /**
  23099. A type of AudioSource which can be repositioned.
  23100. The basic AudioSource just streams continuously with no idea of a current
  23101. time or length, so the PositionableAudioSource is used for a finite stream
  23102. that has a current read position.
  23103. @see AudioSource, AudioTransportSource
  23104. */
  23105. class JUCE_API PositionableAudioSource : public AudioSource
  23106. {
  23107. protected:
  23108. /** Creates the PositionableAudioSource. */
  23109. PositionableAudioSource() throw() {}
  23110. public:
  23111. /** Destructor */
  23112. ~PositionableAudioSource() {}
  23113. /** Tells the stream to move to a new position.
  23114. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23115. should return samples from this position.
  23116. Note that this may be called on a different thread to getNextAudioBlock(),
  23117. so the subclass should make sure it's synchronised.
  23118. */
  23119. virtual void setNextReadPosition (int newPosition) = 0;
  23120. /** Returns the position from which the next block will be returned.
  23121. @see setNextReadPosition
  23122. */
  23123. virtual int getNextReadPosition() const = 0;
  23124. /** Returns the total length of the stream (in samples). */
  23125. virtual int getTotalLength() const = 0;
  23126. /** Returns true if this source is actually playing in a loop. */
  23127. virtual bool isLooping() const = 0;
  23128. };
  23129. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23130. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23131. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23132. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23133. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23134. class AudioFormat;
  23135. /**
  23136. Reads samples from an audio file stream.
  23137. A subclass that reads a specific type of audio format will be created by
  23138. an AudioFormat object.
  23139. @see AudioFormat, AudioFormatWriter
  23140. */
  23141. class JUCE_API AudioFormatReader
  23142. {
  23143. protected:
  23144. /** Creates an AudioFormatReader object.
  23145. @param sourceStream the stream to read from - this will be deleted
  23146. by this object when it is no longer needed. (Some
  23147. specialised readers might not use this parameter and
  23148. can leave it as 0).
  23149. @param formatName the description that will be returned by the getFormatName()
  23150. method
  23151. */
  23152. AudioFormatReader (InputStream* const sourceStream,
  23153. const String& formatName);
  23154. public:
  23155. /** Destructor. */
  23156. virtual ~AudioFormatReader();
  23157. /** Returns a description of what type of format this is.
  23158. E.g. "AIFF"
  23159. */
  23160. const String getFormatName() const throw() { return formatName; }
  23161. /** Reads samples from the stream.
  23162. @param destSamples an array of buffers into which the sample data for each
  23163. channel will be written.
  23164. If the format is fixed-point, each channel will be written
  23165. as an array of 32-bit signed integers using the full
  23166. range -0x80000000 to 0x7fffffff, regardless of the source's
  23167. bit-depth. If it is a floating-point format, you should cast
  23168. the resulting array to a (float**) to get the values (in the
  23169. range -1.0 to 1.0 or beyond)
  23170. If the format is stereo, then destSamples[0] is the left channel
  23171. data, and destSamples[1] is the right channel.
  23172. The array passed in should be zero-terminated, and it's ok to
  23173. pass in an array with a different number of channels than
  23174. the number in the stream, so if you pass in an array with only
  23175. one channel and the stream is stereo, the reader will
  23176. put a merged sum of the stereo channels into the single
  23177. destination channel.
  23178. @param startSample the offset into the audio stream from which the samples
  23179. should be read, as a number of samples from the start of the
  23180. stream. It's ok for this to be beyond the start or end of the
  23181. available data - any samples that can't be read will be padded
  23182. with zeros.
  23183. @param numSamples the number of samples to read. If this is greater than the
  23184. number of samples available, the result will be padded with
  23185. zeros
  23186. @returns true if the operation succeeded, false if there was an error. Note
  23187. that reading sections of data beyond the extent of the stream isn't an
  23188. error - the reader should just return zeros for these regions
  23189. @see readMaxLevels
  23190. */
  23191. virtual bool read (int** destSamples,
  23192. int64 startSample,
  23193. int numSamples) = 0;
  23194. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23195. This will read a block of samples from the stream, and measure the
  23196. highest and lowest sample levels from the channels in that section, returning
  23197. these as normalised floating-point levels.
  23198. @param startSample the offset into the audio stream to start reading from. It's
  23199. ok for this to be beyond the start or end of the stream.
  23200. @param numSamples how many samples to read
  23201. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23202. @param highestLeft on return, this is the highest absolute sample from the left channel
  23203. @param lowestRight on return, this is the lowest absolute sample from the right
  23204. channel (if there is one)
  23205. @param highestRight on return, this is the highest absolute sample from the right
  23206. channel (if there is one)
  23207. @see read
  23208. */
  23209. virtual void readMaxLevels (int64 startSample,
  23210. int64 numSamples,
  23211. float& lowestLeft,
  23212. float& highestLeft,
  23213. float& lowestRight,
  23214. float& highestRight);
  23215. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23216. This will read from the source, either forwards or backwards between two sample
  23217. positions, until it finds a sample whose magnitude lies between two specified levels.
  23218. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23219. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23220. points when you're searching for a continuous range of samples
  23221. @param startSample the first sample to look at
  23222. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23223. the search will go backwards
  23224. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23225. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23226. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23227. of this many consecutive samples, all of which lie
  23228. within the target range. When it finds such a sequence,
  23229. it returns the position of the first in-range sample
  23230. it found (i.e. the earliest one if scanning forwards, the
  23231. latest one if scanning backwards)
  23232. */
  23233. int64 searchForLevel (int64 startSample,
  23234. int64 numSamplesToSearch,
  23235. const double magnitudeRangeMinimum,
  23236. const double magnitudeRangeMaximum,
  23237. const int minimumConsecutiveSamples);
  23238. /** The sample-rate of the stream. */
  23239. double sampleRate;
  23240. /** The number of bits per sample, e.g. 16, 24, 32. */
  23241. unsigned int bitsPerSample;
  23242. /** The total number of samples in the audio stream. */
  23243. int64 lengthInSamples;
  23244. /** The total number of channels in the audio stream. */
  23245. unsigned int numChannels;
  23246. /** Indicates whether the data is floating-point or fixed. */
  23247. bool usesFloatingPointData;
  23248. /** A set of metadata values that the reader has pulled out of the stream.
  23249. Exactly what these values are depends on the format, so you can
  23250. check out the format implementation code to see what kind of stuff
  23251. they understand.
  23252. */
  23253. StringPairArray metadataValues;
  23254. /** The input stream, for use by subclasses. */
  23255. InputStream* input;
  23256. juce_UseDebuggingNewOperator
  23257. private:
  23258. String formatName;
  23259. AudioFormatReader (const AudioFormatReader&);
  23260. const AudioFormatReader& operator= (const AudioFormatReader&);
  23261. };
  23262. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23263. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23264. /**
  23265. A type of AudioSource that will read from an AudioFormatReader.
  23266. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23267. */
  23268. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23269. {
  23270. public:
  23271. /** Creates an AudioFormatReaderSource for a given reader.
  23272. @param sourceReader the reader to use as the data source
  23273. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23274. when this object is deleted; if false it will be
  23275. left up to the caller to manage its lifetime
  23276. */
  23277. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23278. const bool deleteReaderWhenThisIsDeleted);
  23279. /** Destructor. */
  23280. ~AudioFormatReaderSource();
  23281. /** Toggles loop-mode.
  23282. If set to true, it will continuously loop the input source. If false,
  23283. it will just emit silence after the source has finished.
  23284. @see isLooping
  23285. */
  23286. void setLooping (const bool shouldLoop) throw();
  23287. /** Returns whether loop-mode is turned on or not. */
  23288. bool isLooping() const { return looping; }
  23289. /** Returns the reader that's being used. */
  23290. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23291. /** Implementation of the AudioSource method. */
  23292. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23293. /** Implementation of the AudioSource method. */
  23294. void releaseResources();
  23295. /** Implementation of the AudioSource method. */
  23296. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23297. /** Implements the PositionableAudioSource method. */
  23298. void setNextReadPosition (int newPosition);
  23299. /** Implements the PositionableAudioSource method. */
  23300. int getNextReadPosition() const;
  23301. /** Implements the PositionableAudioSource method. */
  23302. int getTotalLength() const;
  23303. juce_UseDebuggingNewOperator
  23304. private:
  23305. AudioFormatReader* reader;
  23306. bool deleteReader;
  23307. int volatile nextPlayPos;
  23308. bool volatile looping;
  23309. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23310. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23311. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23312. };
  23313. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23314. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23315. #endif
  23316. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23317. #endif
  23318. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23319. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23320. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23321. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23322. /**
  23323. Wrapper class to continuously stream audio from an audio source to an
  23324. AudioIODevice.
  23325. This object acts as an AudioIODeviceCallback, so can be attached to an
  23326. output device, and will stream audio from an AudioSource.
  23327. */
  23328. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23329. {
  23330. public:
  23331. /** Creates an empty AudioSourcePlayer. */
  23332. AudioSourcePlayer();
  23333. /** Destructor.
  23334. Make sure this object isn't still being used by an AudioIODevice before
  23335. deleting it!
  23336. */
  23337. virtual ~AudioSourcePlayer();
  23338. /** Changes the current audio source to play from.
  23339. If the source passed in is already being used, this method will do nothing.
  23340. If the source is not null, its prepareToPlay() method will be called
  23341. before it starts being used for playback.
  23342. If there's another source currently playing, its releaseResources() method
  23343. will be called after it has been swapped for the new one.
  23344. @param newSource the new source to use - this will NOT be deleted
  23345. by this object when no longer needed, so it's the
  23346. caller's responsibility to manage it.
  23347. */
  23348. void setSource (AudioSource* newSource);
  23349. /** Returns the source that's playing.
  23350. May return 0 if there's no source.
  23351. */
  23352. AudioSource* getCurrentSource() const throw() { return source; }
  23353. /** Sets a gain to apply to the audio data. */
  23354. void setGain (const float newGain) throw();
  23355. /** Implementation of the AudioIODeviceCallback method. */
  23356. void audioDeviceIOCallback (const float** inputChannelData,
  23357. int totalNumInputChannels,
  23358. float** outputChannelData,
  23359. int totalNumOutputChannels,
  23360. int numSamples);
  23361. /** Implementation of the AudioIODeviceCallback method. */
  23362. void audioDeviceAboutToStart (AudioIODevice* device);
  23363. /** Implementation of the AudioIODeviceCallback method. */
  23364. void audioDeviceStopped();
  23365. juce_UseDebuggingNewOperator
  23366. private:
  23367. CriticalSection readLock;
  23368. AudioSource* source;
  23369. double sampleRate;
  23370. int bufferSize;
  23371. float* channels [128];
  23372. float* outputChans [128];
  23373. const float* inputChans [128];
  23374. AudioSampleBuffer tempBuffer;
  23375. float lastGain, gain;
  23376. AudioSourcePlayer (const AudioSourcePlayer&);
  23377. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23378. };
  23379. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23380. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23381. #endif
  23382. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23383. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23384. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23385. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23386. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23387. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23388. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23389. /**
  23390. An AudioSource which takes another source as input, and buffers it using a thread.
  23391. Create this as a wrapper around another thread, and it will read-ahead with
  23392. a background thread to smooth out playback. You can either create one of these
  23393. directly, or use it indirectly using an AudioTransportSource.
  23394. @see PositionableAudioSource, AudioTransportSource
  23395. */
  23396. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23397. {
  23398. public:
  23399. /** Creates a BufferingAudioSource.
  23400. @param source the input source to read from
  23401. @param deleteSourceWhenDeleted if true, then the input source object will
  23402. be deleted when this object is deleted
  23403. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23404. */
  23405. BufferingAudioSource (PositionableAudioSource* source,
  23406. const bool deleteSourceWhenDeleted,
  23407. int numberOfSamplesToBuffer);
  23408. /** Destructor.
  23409. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23410. flag was set in the constructor.
  23411. */
  23412. ~BufferingAudioSource();
  23413. /** Implementation of the AudioSource method. */
  23414. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23415. /** Implementation of the AudioSource method. */
  23416. void releaseResources();
  23417. /** Implementation of the AudioSource method. */
  23418. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23419. /** Implements the PositionableAudioSource method. */
  23420. void setNextReadPosition (int newPosition);
  23421. /** Implements the PositionableAudioSource method. */
  23422. int getNextReadPosition() const;
  23423. /** Implements the PositionableAudioSource method. */
  23424. int getTotalLength() const { return source->getTotalLength(); }
  23425. /** Implements the PositionableAudioSource method. */
  23426. bool isLooping() const { return source->isLooping(); }
  23427. juce_UseDebuggingNewOperator
  23428. private:
  23429. PositionableAudioSource* source;
  23430. bool deleteSourceWhenDeleted;
  23431. int numberOfSamplesToBuffer;
  23432. AudioSampleBuffer buffer;
  23433. CriticalSection bufferStartPosLock;
  23434. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23435. bool wasSourceLooping;
  23436. double volatile sampleRate;
  23437. friend class SharedBufferingAudioSourceThread;
  23438. bool readNextBufferChunk();
  23439. void readBufferSection (int start, int length, int bufferOffset);
  23440. BufferingAudioSource (const BufferingAudioSource&);
  23441. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23442. };
  23443. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23444. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23445. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23446. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23447. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23448. /**
  23449. A type of AudioSource that takes an input source and changes its sample rate.
  23450. @see AudioSource
  23451. */
  23452. class JUCE_API ResamplingAudioSource : public AudioSource
  23453. {
  23454. public:
  23455. /** Creates a ResamplingAudioSource for a given input source.
  23456. @param inputSource the input source to read from
  23457. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23458. this object is deleted
  23459. */
  23460. ResamplingAudioSource (AudioSource* const inputSource,
  23461. const bool deleteInputWhenDeleted);
  23462. /** Destructor. */
  23463. ~ResamplingAudioSource();
  23464. /** Changes the resampling ratio.
  23465. (This value can be changed at any time, even while the source is running).
  23466. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23467. values will speed it up; lower values will slow it
  23468. down. The ratio must be greater than 0
  23469. */
  23470. void setResamplingRatio (const double samplesInPerOutputSample);
  23471. /** Returns the current resampling ratio.
  23472. This is the value that was set by setResamplingRatio().
  23473. */
  23474. double getResamplingRatio() const throw() { return ratio; }
  23475. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23476. void releaseResources();
  23477. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23478. juce_UseDebuggingNewOperator
  23479. private:
  23480. AudioSource* const input;
  23481. const bool deleteInputWhenDeleted;
  23482. double ratio, lastRatio;
  23483. AudioSampleBuffer buffer;
  23484. int bufferPos, sampsInBuffer;
  23485. double subSampleOffset;
  23486. double coefficients[6];
  23487. CriticalSection ratioLock;
  23488. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23489. void createLowPass (const double proportionalRate);
  23490. struct FilterState
  23491. {
  23492. double x1, x2, y1, y2;
  23493. };
  23494. FilterState filterStates[2];
  23495. void resetFilters();
  23496. void applyFilter (float* samples, int num, FilterState& fs);
  23497. ResamplingAudioSource (const ResamplingAudioSource&);
  23498. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23499. };
  23500. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23501. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23502. /**
  23503. An AudioSource that takes a PositionableAudioSource and allows it to be
  23504. played, stopped, started, etc.
  23505. This can also be told use a buffer and background thread to read ahead, and
  23506. if can correct for different sample-rates.
  23507. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23508. to control playback of an audio file.
  23509. @see AudioSource, AudioSourcePlayer
  23510. */
  23511. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23512. public ChangeBroadcaster
  23513. {
  23514. public:
  23515. /** Creates an AudioTransportSource.
  23516. After creating one of these, use the setSource() method to select an input source.
  23517. */
  23518. AudioTransportSource();
  23519. /** Destructor. */
  23520. ~AudioTransportSource();
  23521. /** Sets the reader that is being used as the input source.
  23522. This will stop playback, reset the position to 0 and change to the new reader.
  23523. The source passed in will not be deleted by this object, so must be managed by
  23524. the caller.
  23525. @param newSource the new input source to use. This may be zero
  23526. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23527. is zero, no reading ahead will be done; if it's
  23528. greater than zero, a BufferingAudioSource will be used
  23529. to do the reading-ahead
  23530. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23531. rate of the source, and playback will be sample-rate
  23532. adjusted to maintain playback at the correct pitch. If
  23533. this is 0, no sample-rate adjustment will be performed
  23534. */
  23535. void setSource (PositionableAudioSource* const newSource,
  23536. int readAheadBufferSize = 0,
  23537. double sourceSampleRateToCorrectFor = 0.0);
  23538. /** Changes the current playback position in the source stream.
  23539. The next time the getNextAudioBlock() method is called, this
  23540. is the time from which it'll read data.
  23541. @see getPosition
  23542. */
  23543. void setPosition (double newPosition);
  23544. /** Returns the position that the next data block will be read from
  23545. This is a time in seconds.
  23546. */
  23547. double getCurrentPosition() const;
  23548. /** Returns true if the player has stopped because its input stream ran out of data.
  23549. */
  23550. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23551. /** Starts playing (if a source has been selected).
  23552. If it starts playing, this will send a message to any ChangeListeners
  23553. that are registered with this object.
  23554. */
  23555. void start();
  23556. /** Stops playing.
  23557. If it's actually playing, this will send a message to any ChangeListeners
  23558. that are registered with this object.
  23559. */
  23560. void stop();
  23561. /** Returns true if it's currently playing. */
  23562. bool isPlaying() const throw() { return playing; }
  23563. /** Changes the gain to apply to the output.
  23564. @param newGain a factor by which to multiply the outgoing samples,
  23565. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23566. */
  23567. void setGain (const float newGain) throw();
  23568. /** Returns the current gain setting.
  23569. @see setGain
  23570. */
  23571. float getGain() const throw() { return gain; }
  23572. /** Implementation of the AudioSource method. */
  23573. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23574. /** Implementation of the AudioSource method. */
  23575. void releaseResources();
  23576. /** Implementation of the AudioSource method. */
  23577. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23578. /** Implements the PositionableAudioSource method. */
  23579. void setNextReadPosition (int newPosition);
  23580. /** Implements the PositionableAudioSource method. */
  23581. int getNextReadPosition() const;
  23582. /** Implements the PositionableAudioSource method. */
  23583. int getTotalLength() const;
  23584. /** Implements the PositionableAudioSource method. */
  23585. bool isLooping() const;
  23586. juce_UseDebuggingNewOperator
  23587. private:
  23588. PositionableAudioSource* source;
  23589. ResamplingAudioSource* resamplerSource;
  23590. BufferingAudioSource* bufferingSource;
  23591. PositionableAudioSource* positionableSource;
  23592. AudioSource* masterSource;
  23593. CriticalSection callbackLock;
  23594. float volatile gain, lastGain;
  23595. bool volatile playing, stopped;
  23596. double sampleRate, sourceSampleRate;
  23597. int blockSize, readAheadBufferSize;
  23598. bool isPrepared, inputStreamEOF;
  23599. AudioTransportSource (const AudioTransportSource&);
  23600. const AudioTransportSource& operator= (const AudioTransportSource&);
  23601. };
  23602. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23603. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23604. #endif
  23605. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23606. #endif
  23607. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23608. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23609. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23610. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23611. /**
  23612. An AudioSource that takes the audio from another source, and re-maps its
  23613. input and output channels to a different arrangement.
  23614. You can use this to increase or decrease the number of channels that an
  23615. audio source uses, or to re-order those channels.
  23616. Call the reset() method before using it to set up a default mapping, and then
  23617. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23618. create an appropriate mapping, otherwise no channels will be connected and
  23619. it'll produce silence.
  23620. @see AudioSource
  23621. */
  23622. class ChannelRemappingAudioSource : public AudioSource
  23623. {
  23624. public:
  23625. /** Creates a remapping source that will pass on audio from the given input.
  23626. @param source the input source to use. Make sure that this doesn't
  23627. get deleted before the ChannelRemappingAudioSource object
  23628. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23629. when this object is deleted, if false, the caller is
  23630. responsible for its deletion
  23631. */
  23632. ChannelRemappingAudioSource (AudioSource* const source,
  23633. const bool deleteSourceWhenDeleted);
  23634. /** Destructor. */
  23635. ~ChannelRemappingAudioSource();
  23636. /** Specifies a number of channels that this audio source must produce from its
  23637. getNextAudioBlock() callback.
  23638. */
  23639. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23640. /** Clears any mapped channels.
  23641. After this, no channels are mapped, so this object will produce silence. Create
  23642. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23643. */
  23644. void clearAllMappings() throw();
  23645. /** Creates an input channel mapping.
  23646. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23647. data will be sent to destChannelIndex of our input source.
  23648. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23649. source specified when this object was created).
  23650. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23651. during our getNextAudioBlock() callback
  23652. */
  23653. void setInputChannelMapping (const int destChannelIndex,
  23654. const int sourceChannelIndex) throw();
  23655. /** Creates an output channel mapping.
  23656. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23657. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23658. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23659. (i.e. the source specified when this object was created).
  23660. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23661. during our getNextAudioBlock() callback
  23662. */
  23663. void setOutputChannelMapping (const int sourceChannelIndex,
  23664. const int destChannelIndex) throw();
  23665. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23666. our input audio source.
  23667. */
  23668. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23669. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23670. source will be sent to.
  23671. */
  23672. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23673. /** Returns an XML object to encapsulate the state of the mappings.
  23674. @see restoreFromXml
  23675. */
  23676. XmlElement* createXml() const throw();
  23677. /** Restores the mappings from an XML object created by createXML().
  23678. @see createXml
  23679. */
  23680. void restoreFromXml (const XmlElement& e) throw();
  23681. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23682. void releaseResources();
  23683. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23684. juce_UseDebuggingNewOperator
  23685. private:
  23686. int requiredNumberOfChannels;
  23687. Array <int> remappedInputs, remappedOutputs;
  23688. AudioSource* const source;
  23689. const bool deleteSourceWhenDeleted;
  23690. AudioSampleBuffer buffer;
  23691. AudioSourceChannelInfo remappedInfo;
  23692. CriticalSection lock;
  23693. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23694. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23695. };
  23696. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23697. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23698. #endif
  23699. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23700. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23701. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23702. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23703. /**
  23704. An AudioSource that performs an IIR filter on another source.
  23705. */
  23706. class JUCE_API IIRFilterAudioSource : public AudioSource
  23707. {
  23708. public:
  23709. /** Creates a IIRFilterAudioSource for a given input source.
  23710. @param inputSource the input source to read from
  23711. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23712. this object is deleted
  23713. */
  23714. IIRFilterAudioSource (AudioSource* const inputSource,
  23715. const bool deleteInputWhenDeleted);
  23716. /** Destructor. */
  23717. ~IIRFilterAudioSource();
  23718. /** Changes the filter to use the same parameters as the one being passed in.
  23719. */
  23720. void setFilterParameters (const IIRFilter& newSettings);
  23721. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23722. void releaseResources();
  23723. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23724. juce_UseDebuggingNewOperator
  23725. private:
  23726. AudioSource* const input;
  23727. const bool deleteInputWhenDeleted;
  23728. OwnedArray <IIRFilter> iirFilters;
  23729. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23730. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23731. };
  23732. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23733. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23734. #endif
  23735. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23736. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23737. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23738. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23739. /**
  23740. An AudioSource that mixes together the output of a set of other AudioSources.
  23741. Input sources can be added and removed while the mixer is running as long as their
  23742. prepareToPlay() and releaseResources() methods are called before and after adding
  23743. them to the mixer.
  23744. */
  23745. class JUCE_API MixerAudioSource : public AudioSource
  23746. {
  23747. public:
  23748. /** Creates a MixerAudioSource.
  23749. */
  23750. MixerAudioSource();
  23751. /** Destructor. */
  23752. ~MixerAudioSource();
  23753. /** Adds an input source to the mixer.
  23754. If the mixer is running you'll need to make sure that the input source
  23755. is ready to play by calling its prepareToPlay() method before adding it.
  23756. If the mixer is stopped, then its input sources will be automatically
  23757. prepared when the mixer's prepareToPlay() method is called.
  23758. @param newInput the source to add to the mixer
  23759. @param deleteWhenRemoved if true, then this source will be deleted when
  23760. the mixer is deleted or when removeAllInputs() is
  23761. called (unless the source is previously removed
  23762. with the removeInputSource method)
  23763. */
  23764. void addInputSource (AudioSource* newInput,
  23765. const bool deleteWhenRemoved);
  23766. /** Removes an input source.
  23767. If the mixer is running, this will remove the source but not call its
  23768. releaseResources() method, so the caller might want to do this manually.
  23769. @param input the source to remove
  23770. @param deleteSource whether to delete this source after it's been removed
  23771. */
  23772. void removeInputSource (AudioSource* input,
  23773. const bool deleteSource);
  23774. /** Removes all the input sources.
  23775. If the mixer is running, this will remove the sources but not call their
  23776. releaseResources() method, so the caller might want to do this manually.
  23777. Any sources which were added with the deleteWhenRemoved flag set will be
  23778. deleted by this method.
  23779. */
  23780. void removeAllInputs();
  23781. /** Implementation of the AudioSource method.
  23782. This will call prepareToPlay() on all its input sources.
  23783. */
  23784. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23785. /** Implementation of the AudioSource method.
  23786. This will call releaseResources() on all its input sources.
  23787. */
  23788. void releaseResources();
  23789. /** Implementation of the AudioSource method. */
  23790. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23791. juce_UseDebuggingNewOperator
  23792. private:
  23793. VoidArray inputs;
  23794. BitArray inputsToDelete;
  23795. CriticalSection lock;
  23796. AudioSampleBuffer tempBuffer;
  23797. double currentSampleRate;
  23798. int bufferSizeExpected;
  23799. MixerAudioSource (const MixerAudioSource&);
  23800. const MixerAudioSource& operator= (const MixerAudioSource&);
  23801. };
  23802. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23803. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23804. #endif
  23805. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23806. #endif
  23807. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23808. #endif
  23809. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23810. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23811. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23812. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23813. /**
  23814. A simple AudioSource that generates a sine wave.
  23815. */
  23816. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  23817. {
  23818. public:
  23819. /** Creates a ToneGeneratorAudioSource. */
  23820. ToneGeneratorAudioSource();
  23821. /** Destructor. */
  23822. ~ToneGeneratorAudioSource();
  23823. /** Sets the signal's amplitude. */
  23824. void setAmplitude (const float newAmplitude);
  23825. /** Sets the signal's frequency. */
  23826. void setFrequency (const double newFrequencyHz);
  23827. /** Implementation of the AudioSource method. */
  23828. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23829. /** Implementation of the AudioSource method. */
  23830. void releaseResources();
  23831. /** Implementation of the AudioSource method. */
  23832. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23833. juce_UseDebuggingNewOperator
  23834. private:
  23835. double frequency, sampleRate;
  23836. double currentPhase, phasePerSample;
  23837. float amplitude;
  23838. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  23839. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  23840. };
  23841. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23842. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23843. #endif
  23844. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23845. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  23846. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23847. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23848. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  23849. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23850. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23851. class AudioDeviceManager;
  23852. class Component;
  23853. /**
  23854. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  23855. To get a list of available audio driver types, use the createDeviceTypes()
  23856. method. Each of the objects returned can then be used to list the available
  23857. devices of that type. E.g.
  23858. @code
  23859. OwnedArray <AudioIODeviceType> types;
  23860. AudioIODeviceType::createDeviceTypes (types);
  23861. for (int i = 0; i < types.size(); ++i)
  23862. {
  23863. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  23864. types[i]->scanForDevices(); // This must be called before getting the list of devices
  23865. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  23866. for (int j = 0; j < deviceNames.size(); ++j)
  23867. {
  23868. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  23869. ...
  23870. }
  23871. }
  23872. @endcode
  23873. For an easier way of managing audio devices and their settings, have a look at the
  23874. AudioDeviceManager class.
  23875. @see AudioIODevice, AudioDeviceManager
  23876. */
  23877. class JUCE_API AudioIODeviceType
  23878. {
  23879. public:
  23880. /** Returns the name of this type of driver that this object manages.
  23881. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  23882. */
  23883. const String& getTypeName() const throw() { return typeName; }
  23884. /** Refreshes the object's cached list of known devices.
  23885. This must be called at least once before calling getDeviceNames() or any of
  23886. the other device creation methods.
  23887. */
  23888. virtual void scanForDevices() = 0;
  23889. /** Returns the list of available devices of this type.
  23890. The scanForDevices() method must have been called to create this list.
  23891. @param wantInputNames only really used by DirectSound where devices are split up
  23892. into inputs and outputs, this indicates whether to use
  23893. the input or output name to refer to a pair of devices.
  23894. */
  23895. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  23896. /** Returns the name of the default device.
  23897. This will be one of the names from the getDeviceNames() list.
  23898. @param forInput if true, this means that a default input device should be
  23899. returned; if false, it should return the default output
  23900. */
  23901. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  23902. /** Returns the index of a given device in the list of device names.
  23903. If asInput is true, it shows the index in the inputs list, otherwise it
  23904. looks for it in the outputs list.
  23905. */
  23906. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  23907. /** Returns true if two different devices can be used for the input and output.
  23908. */
  23909. virtual bool hasSeparateInputsAndOutputs() const = 0;
  23910. /** Creates one of the devices of this type.
  23911. The deviceName must be one of the strings returned by getDeviceNames(), and
  23912. scanForDevices() must have been called before this method is used.
  23913. */
  23914. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  23915. const String& inputDeviceName) = 0;
  23916. struct DeviceSetupDetails
  23917. {
  23918. AudioDeviceManager* manager;
  23919. int minNumInputChannels, maxNumInputChannels;
  23920. int minNumOutputChannels, maxNumOutputChannels;
  23921. bool useStereoPairs;
  23922. };
  23923. /** Destructor. */
  23924. virtual ~AudioIODeviceType();
  23925. protected:
  23926. AudioIODeviceType (const tchar* const typeName);
  23927. private:
  23928. String typeName;
  23929. AudioIODeviceType (const AudioIODeviceType&);
  23930. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  23931. };
  23932. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23933. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  23934. /********* Start of inlined file: juce_MidiOutput.h *********/
  23935. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  23936. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  23937. /**
  23938. Represents a midi output device.
  23939. To create one of these, use the static getDevices() method to find out what
  23940. outputs are available, then use the openDevice() method to try to open one.
  23941. @see MidiInput
  23942. */
  23943. class JUCE_API MidiOutput : private Thread
  23944. {
  23945. public:
  23946. /** Returns a list of the available midi output devices.
  23947. You can open one of the devices by passing its index into the
  23948. openDevice() method.
  23949. @see getDefaultDeviceIndex, openDevice
  23950. */
  23951. static const StringArray getDevices();
  23952. /** Returns the index of the default midi output device to use.
  23953. This refers to the index in the list returned by getDevices().
  23954. */
  23955. static int getDefaultDeviceIndex();
  23956. /** Tries to open one of the midi output devices.
  23957. This will return a MidiOutput object if it manages to open it. You can then
  23958. send messages to this device, and delete it when no longer needed.
  23959. If the device can't be opened, this will return a null pointer.
  23960. @param deviceIndex the index of a device from the list returned by getDevices()
  23961. @see getDevices
  23962. */
  23963. static MidiOutput* openDevice (int deviceIndex);
  23964. #if JUCE_LINUX || DOXYGEN
  23965. /** LINUX ONLY - This will try to create a new midi output device.
  23966. This will attempt to create a new midi output device that other apps can connect
  23967. to and use as their midi input.
  23968. Returns 0 if a device can't be created.
  23969. @param deviceName the name to use for the new device
  23970. */
  23971. static MidiOutput* createNewDevice (const String& deviceName);
  23972. #endif
  23973. /** Destructor. */
  23974. ~MidiOutput();
  23975. /** Makes this device output a midi message.
  23976. @see MidiMessage
  23977. */
  23978. void sendMessageNow (const MidiMessage& message);
  23979. /** Sends a midi reset to the device. */
  23980. void reset();
  23981. /** Returns the current volume setting for this device. */
  23982. bool getVolume (float& leftVol,
  23983. float& rightVol);
  23984. /** Changes the overall volume for this device. */
  23985. void setVolume (float leftVol,
  23986. float rightVol);
  23987. /** This lets you supply a block of messages that will be sent out at some point
  23988. in the future.
  23989. The MidiOutput class has an internal thread that can send out timestamped
  23990. messages - this appends a set of messages to its internal buffer, ready for
  23991. sending.
  23992. This will only work if you've already started the thread with startBackgroundThread().
  23993. A time is supplied, at which the block of messages should be sent. This time uses
  23994. the same time base as Time::getMillisecondCounter(), and must be in the future.
  23995. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  23996. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  23997. samplesPerSecondForBuffer value is needed to convert this sample position to a
  23998. real time.
  23999. */
  24000. void sendBlockOfMessages (const MidiBuffer& buffer,
  24001. const double millisecondCounterToStartAt,
  24002. double samplesPerSecondForBuffer) throw();
  24003. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24004. */
  24005. void clearAllPendingMessages() throw();
  24006. /** Starts up a background thread so that the device can send blocks of data.
  24007. Call this to get the device ready, before using sendBlockOfMessages().
  24008. */
  24009. void startBackgroundThread() throw();
  24010. /** Stops the background thread, and clears any pending midi events.
  24011. @see startBackgroundThread
  24012. */
  24013. void stopBackgroundThread() throw();
  24014. juce_UseDebuggingNewOperator
  24015. private:
  24016. void* internal;
  24017. struct PendingMessage
  24018. {
  24019. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24020. MidiMessage message;
  24021. PendingMessage* next;
  24022. juce_UseDebuggingNewOperator
  24023. };
  24024. CriticalSection lock;
  24025. PendingMessage* firstMessage;
  24026. MidiOutput() throw();
  24027. MidiOutput (const MidiOutput&);
  24028. void run();
  24029. };
  24030. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24031. /********* End of inlined file: juce_MidiOutput.h *********/
  24032. /********* Start of inlined file: juce_ComboBox.h *********/
  24033. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24034. #define __JUCE_COMBOBOX_JUCEHEADER__
  24035. /********* Start of inlined file: juce_Label.h *********/
  24036. #ifndef __JUCE_LABEL_JUCEHEADER__
  24037. #define __JUCE_LABEL_JUCEHEADER__
  24038. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24039. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24040. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24041. /**
  24042. Object for monitoring a component, and later testing whether it's still valid.
  24043. Slightly obscure, this one, but it's used internally for making sure that
  24044. after some callbacks, a component hasn't been deleted. It's more reliable than
  24045. just using isValidComponent(), which can provide false-positives if a new
  24046. component is created at the same memory location as an old one.
  24047. */
  24048. class JUCE_API ComponentDeletionWatcher
  24049. {
  24050. public:
  24051. /** Creates a watcher for a given component.
  24052. The component must be valid at the time it's passed in.
  24053. */
  24054. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24055. /** Destructor. */
  24056. ~ComponentDeletionWatcher() throw();
  24057. /** Returns true if the component has been deleted since the time that this
  24058. object was created.
  24059. */
  24060. bool hasBeenDeleted() const throw();
  24061. /** Returns the component that's being watched, or null if it has been deleted. */
  24062. const Component* getComponent() const throw();
  24063. juce_UseDebuggingNewOperator
  24064. private:
  24065. const Component* const componentToWatch;
  24066. const uint32 componentUID;
  24067. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24068. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24069. };
  24070. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24071. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24072. /********* Start of inlined file: juce_TextEditor.h *********/
  24073. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24074. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24075. /********* Start of inlined file: juce_UndoManager.h *********/
  24076. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24077. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24078. /********* Start of inlined file: juce_UndoableAction.h *********/
  24079. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24080. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24081. /**
  24082. Used by the UndoManager class to store an action which can be done
  24083. and undone.
  24084. @see UndoManager
  24085. */
  24086. class JUCE_API UndoableAction
  24087. {
  24088. protected:
  24089. /** Creates an action. */
  24090. UndoableAction() throw() {}
  24091. public:
  24092. /** Destructor. */
  24093. virtual ~UndoableAction() {}
  24094. /** Overridden by a subclass to perform the action.
  24095. This method is called by the UndoManager, and shouldn't be used directly by
  24096. applications.
  24097. Be careful not to make any calls in a perform() method that could call
  24098. recursively back into the UndoManager::perform() method
  24099. @returns true if the action could be performed.
  24100. @see UndoManager::perform
  24101. */
  24102. virtual bool perform() = 0;
  24103. /** Overridden by a subclass to undo the action.
  24104. This method is called by the UndoManager, and shouldn't be used directly by
  24105. applications.
  24106. Be careful not to make any calls in an undo() method that could call
  24107. recursively back into the UndoManager::perform() method
  24108. @returns true if the action could be undone without any errors.
  24109. @see UndoManager::perform
  24110. */
  24111. virtual bool undo() = 0;
  24112. /** Returns a value to indicate how much memory this object takes up.
  24113. Because the UndoManager keeps a list of UndoableActions, this is used
  24114. to work out how much space each one will take up, so that the UndoManager
  24115. can work out how many to keep.
  24116. The default value returned here is 10 - units are arbitrary and
  24117. don't have to be accurate.
  24118. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24119. UndoManager::setMaxNumberOfStoredUnits
  24120. */
  24121. virtual int getSizeInUnits() { return 10; }
  24122. };
  24123. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24124. /********* End of inlined file: juce_UndoableAction.h *********/
  24125. /**
  24126. Manages a list of undo/redo commands.
  24127. An UndoManager object keeps a list of past actions and can use these actions
  24128. to move backwards and forwards through an undo history.
  24129. To use it, create subclasses of UndoableAction which perform all the
  24130. actions you need, then when you need to actually perform an action, create one
  24131. and pass it to the UndoManager's perform() method.
  24132. The manager also uses the concept of 'transactions' to group the actions
  24133. together - all actions performed between calls to beginNewTransaction() are
  24134. grouped together and are all undone/redone as a group.
  24135. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24136. when actions are performed or undone.
  24137. @see UndoableAction
  24138. */
  24139. class JUCE_API UndoManager : public ChangeBroadcaster
  24140. {
  24141. public:
  24142. /** Creates an UndoManager.
  24143. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24144. to indicate how much storage it takes up
  24145. (UndoableAction::getSizeInUnits()), so this
  24146. lets you specify the maximum total number of
  24147. units that the undomanager is allowed to
  24148. keep in memory before letting the older actions
  24149. drop off the end of the list.
  24150. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24151. that will be kept, even if this involves exceeding
  24152. the amount of space specified in maxNumberOfUnitsToKeep
  24153. */
  24154. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24155. const int minimumTransactionsToKeep = 30);
  24156. /** Destructor. */
  24157. ~UndoManager();
  24158. /** Deletes all stored actions in the list. */
  24159. void clearUndoHistory();
  24160. /** Returns the current amount of space to use for storing UndoableAction objects.
  24161. @see setMaxNumberOfStoredUnits
  24162. */
  24163. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24164. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24165. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24166. to indicate how much storage it takes up
  24167. (UndoableAction::getSizeInUnits()), so this
  24168. lets you specify the maximum total number of
  24169. units that the undomanager is allowed to
  24170. keep in memory before letting the older actions
  24171. drop off the end of the list.
  24172. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24173. that will be kept, even if this involves exceeding
  24174. the amount of space specified in maxNumberOfUnitsToKeep
  24175. @see getNumberOfUnitsTakenUpByStoredCommands
  24176. */
  24177. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24178. const int minimumTransactionsToKeep);
  24179. /** Performs an action and adds it to the undo history list.
  24180. @param action the action to perform - this will be deleted by the UndoManager
  24181. when no longer needed
  24182. @param actionName if this string is non-empty, the current transaction will be
  24183. given this name; if it's empty, the current transaction name will
  24184. be left unchanged. See setCurrentTransactionName()
  24185. @returns true if the command succeeds - see UndoableAction::perform
  24186. @see beginNewTransaction
  24187. */
  24188. bool perform (UndoableAction* const action,
  24189. const String& actionName = String::empty);
  24190. /** Starts a new group of actions that together will be treated as a single transaction.
  24191. All actions that are passed to the perform() method between calls to this
  24192. method are grouped together and undone/redone together by a single call to
  24193. undo() or redo().
  24194. @param actionName a description of the transaction that is about to be
  24195. performed
  24196. */
  24197. void beginNewTransaction (const String& actionName = String::empty);
  24198. /** Changes the name stored for the current transaction.
  24199. Each transaction is given a name when the beginNewTransaction() method is
  24200. called, but this can be used to change that name without starting a new
  24201. transaction.
  24202. */
  24203. void setCurrentTransactionName (const String& newName);
  24204. /** Returns true if there's at least one action in the list to undo.
  24205. @see getUndoDescription, undo, canRedo
  24206. */
  24207. bool canUndo() const;
  24208. /** Returns the description of the transaction that would be next to get undone.
  24209. The description returned is the one that was passed into beginNewTransaction
  24210. before the set of actions was performed.
  24211. @see undo
  24212. */
  24213. const String getUndoDescription() const;
  24214. /** Tries to roll-back the last transaction.
  24215. @returns true if the transaction can be undone, and false if it fails, or
  24216. if there aren't any transactions to undo
  24217. */
  24218. bool undo();
  24219. /** Tries to roll-back any actions that were added to the current transaction.
  24220. This will perform an undo() only if there are some actions in the undo list
  24221. that were added after the last call to beginNewTransaction().
  24222. This is useful because it lets you call beginNewTransaction(), then
  24223. perform an operation which may or may not actually perform some actions, and
  24224. then call this method to get rid of any actions that might have been done
  24225. without it rolling back the previous transaction if nothing was actually
  24226. done.
  24227. @returns true if any actions were undone.
  24228. */
  24229. bool undoCurrentTransactionOnly();
  24230. /** Returns a list of the UndoableAction objects that have been performed during the
  24231. transaction that is currently open.
  24232. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24233. were to be called now.
  24234. The first item in the list is the earliest action performed.
  24235. */
  24236. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24237. /** Returns true if there's at least one action in the list to redo.
  24238. @see getRedoDescription, redo, canUndo
  24239. */
  24240. bool canRedo() const;
  24241. /** Returns the description of the transaction that would be next to get redone.
  24242. The description returned is the one that was passed into beginNewTransaction
  24243. before the set of actions was performed.
  24244. @see redo
  24245. */
  24246. const String getRedoDescription() const;
  24247. /** Tries to redo the last transaction that was undone.
  24248. @returns true if the transaction can be redone, and false if it fails, or
  24249. if there aren't any transactions to redo
  24250. */
  24251. bool redo();
  24252. juce_UseDebuggingNewOperator
  24253. private:
  24254. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24255. StringArray transactionNames;
  24256. String currentTransactionName;
  24257. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24258. bool newTransaction, reentrancyCheck;
  24259. // disallow copy constructor
  24260. UndoManager (const UndoManager&);
  24261. const UndoManager& operator= (const UndoManager&);
  24262. };
  24263. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24264. /********* End of inlined file: juce_UndoManager.h *********/
  24265. class TextEditor;
  24266. class TextHolderComponent;
  24267. /**
  24268. Receives callbacks from a TextEditor component when it changes.
  24269. @see TextEditor::addListener
  24270. */
  24271. class JUCE_API TextEditorListener
  24272. {
  24273. public:
  24274. /** Destructor. */
  24275. virtual ~TextEditorListener() {}
  24276. /** Called when the user changes the text in some way. */
  24277. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24278. /** Called when the user presses the return key. */
  24279. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24280. /** Called when the user presses the escape key. */
  24281. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24282. /** Called when the text editor loses focus. */
  24283. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24284. };
  24285. /**
  24286. A component containing text that can be edited.
  24287. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24288. fonts and colours.
  24289. @see TextEditorListener, Label
  24290. */
  24291. class JUCE_API TextEditor : public Component,
  24292. public SettableTooltipClient
  24293. {
  24294. public:
  24295. /** Creates a new, empty text editor.
  24296. @param componentName the name to pass to the component for it to use as its name
  24297. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24298. for all characters that are drawn on screen - e.g. to create
  24299. a password-style textbox containing circular blobs instead of text,
  24300. you could set this value to 0x25cf, which is the unicode character
  24301. for a black splodge (not all fonts include this, though), or 0x2022,
  24302. which is a bullet (probably the best choice for linux).
  24303. */
  24304. TextEditor (const String& componentName = String::empty,
  24305. const tchar passwordCharacter = 0);
  24306. /** Destructor. */
  24307. virtual ~TextEditor();
  24308. /** Puts the editor into either multi- or single-line mode.
  24309. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24310. editor.
  24311. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24312. on if you want a multi-line editor with line-breaks.
  24313. @see isMultiLine, setReturnKeyStartsNewLine
  24314. */
  24315. void setMultiLine (const bool shouldBeMultiLine,
  24316. const bool shouldWordWrap = true);
  24317. /** Returns true if the editor is in multi-line mode.
  24318. */
  24319. bool isMultiLine() const throw();
  24320. /** Changes the behaviour of the return key.
  24321. If set to true, the return key will insert a new-line into the text; if false
  24322. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24323. method. By default this is set to false, and when true it will only insert
  24324. new-lines when in multi-line mode (see setMultiLine()).
  24325. */
  24326. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24327. /** Returns the value set by setReturnKeyStartsNewLine().
  24328. See setReturnKeyStartsNewLine() for more info.
  24329. */
  24330. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24331. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24332. or whether it gets ignored.
  24333. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24334. between components.
  24335. */
  24336. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24337. /** Returns true if the tab key is being used for input.
  24338. @see setTabKeyUsedAsCharacter
  24339. */
  24340. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24341. /** Changes the editor to read-only mode.
  24342. By default, the text editor is not read-only. If you're making it read-only, you
  24343. might also want to call setCaretVisible (false) to get rid of the caret.
  24344. The text can still be highlighted and copied when in read-only mode.
  24345. @see isReadOnly, setCaretVisible
  24346. */
  24347. void setReadOnly (const bool shouldBeReadOnly);
  24348. /** Returns true if the editor is in read-only mode.
  24349. */
  24350. bool isReadOnly() const throw();
  24351. /** Makes the caret visible or invisible.
  24352. By default the caret is visible.
  24353. @see setCaretColour, setCaretPosition
  24354. */
  24355. void setCaretVisible (const bool shouldBeVisible) throw();
  24356. /** Returns true if the caret is enabled.
  24357. @see setCaretVisible
  24358. */
  24359. bool isCaretVisible() const throw() { return caretVisible; }
  24360. /** Enables/disables a vertical scrollbar.
  24361. (This only applies when in multi-line mode). When the text gets too long to fit
  24362. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24363. this is enabled, the scrollbar will be hidden unless it's needed.
  24364. By default the scrollbar is enabled.
  24365. */
  24366. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24367. /** Returns true if scrollbars are enabled.
  24368. @see setScrollbarsShown
  24369. */
  24370. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24371. /** Changes the password character used to disguise the text.
  24372. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24373. for all characters that are drawn on screen - e.g. to create
  24374. a password-style textbox containing circular blobs instead of text,
  24375. you could set this value to 0x25cf, which is the unicode character
  24376. for a black splodge (not all fonts include this, though), or 0x2022,
  24377. which is a bullet (probably the best choice for linux).
  24378. */
  24379. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24380. /** Returns the current password character.
  24381. @see setPasswordCharacter
  24382. l */
  24383. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24384. /** Allows a right-click menu to appear for the editor.
  24385. (This defaults to being enabled).
  24386. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24387. of options such as cut/copy/paste, undo/redo, etc.
  24388. */
  24389. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24390. /** Returns true if the right-click menu is enabled.
  24391. @see setPopupMenuEnabled
  24392. */
  24393. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24394. /** Returns true if a popup-menu is currently being displayed.
  24395. */
  24396. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24397. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24398. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24399. methods.
  24400. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24401. */
  24402. enum ColourIds
  24403. {
  24404. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24405. transparent if necessary. */
  24406. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24407. that because the editor can contain multiple colours, calling this
  24408. method won't change the colour of existing text - to do that, call
  24409. applyFontToAllText() after calling this method.*/
  24410. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24411. the text - this can be transparent if you don't want to show any
  24412. highlighting.*/
  24413. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24414. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24415. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24416. the edge of the component. */
  24417. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24418. the edge of the component when it has focus. */
  24419. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24420. around the edge of the editor. */
  24421. };
  24422. /** Sets the font to use for newly added text.
  24423. This will change the font that will be used next time any text is added or entered
  24424. into the editor. It won't change the font of any existing text - to do that, use
  24425. applyFontToAllText() instead.
  24426. @see applyFontToAllText
  24427. */
  24428. void setFont (const Font& newFont) throw();
  24429. /** Applies a font to all the text in the editor.
  24430. This will also set the current font to use for any new text that's added.
  24431. @see setFont
  24432. */
  24433. void applyFontToAllText (const Font& newFont);
  24434. /** Returns the font that's currently being used for new text.
  24435. @see setFont
  24436. */
  24437. const Font getFont() const throw();
  24438. /** If set to true, focusing on the editor will highlight all its text.
  24439. (Set to false by default).
  24440. This is useful for boxes where you expect the user to re-enter all the
  24441. text when they focus on the component, rather than editing what's already there.
  24442. */
  24443. void setSelectAllWhenFocused (const bool b) throw();
  24444. /** Sets limits on the characters that can be entered.
  24445. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24446. limit is set
  24447. @param allowedCharacters if this is non-empty, then only characters that occur in
  24448. this string are allowed to be entered into the editor.
  24449. */
  24450. void setInputRestrictions (const int maxTextLength,
  24451. const String& allowedCharacters = String::empty) throw();
  24452. /** When the text editor is empty, it can be set to display a message.
  24453. This is handy for things like telling the user what to type in the box - the
  24454. string is only displayed, it's not taken to actually be the contents of
  24455. the editor.
  24456. */
  24457. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24458. /** Changes the size of the scrollbars that are used.
  24459. Handy if you need smaller scrollbars for a small text box.
  24460. */
  24461. void setScrollBarThickness (const int newThicknessPixels);
  24462. /** Shows or hides the buttons on any scrollbars that are used.
  24463. @see ScrollBar::setButtonVisibility
  24464. */
  24465. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24466. /** Registers a listener to be told when things happen to the text.
  24467. @see removeListener
  24468. */
  24469. void addListener (TextEditorListener* const newListener) throw();
  24470. /** Deregisters a listener.
  24471. @see addListener
  24472. */
  24473. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24474. /** Returns the entire contents of the editor. */
  24475. const String getText() const throw();
  24476. /** Returns a section of the contents of the editor. */
  24477. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24478. /** Returns true if there are no characters in the editor.
  24479. This is more efficient than calling getText().isEmpty().
  24480. */
  24481. bool isEmpty() const throw();
  24482. /** Sets the entire content of the editor.
  24483. This will clear the editor and insert the given text (using the current text colour
  24484. and font). You can set the current text colour using
  24485. @code setColour (TextEditor::textColourId, ...);
  24486. @endcode
  24487. @param newText the text to add
  24488. @param sendTextChangeMessage if true, this will cause a change message to
  24489. be sent to all the listeners.
  24490. @see insertText
  24491. */
  24492. void setText (const String& newText,
  24493. const bool sendTextChangeMessage = true);
  24494. /** Inserts some text at the current cursor position.
  24495. If a section of the text is highlighted, it will be replaced by
  24496. this string, otherwise it will be inserted.
  24497. To delete a section of text, you can use setHighlightedRegion() to
  24498. highlight it, and call insertTextAtCursor (String::empty).
  24499. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24500. */
  24501. void insertTextAtCursor (String textToInsert);
  24502. /** Deletes all the text from the editor. */
  24503. void clear();
  24504. /** Deletes the currently selected region, and puts it on the clipboard.
  24505. @see copy, paste, SystemClipboard
  24506. */
  24507. void cut();
  24508. /** Copies any currently selected region to the clipboard.
  24509. @see cut, paste, SystemClipboard
  24510. */
  24511. void copy();
  24512. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24513. @see cut, copy, SystemClipboard
  24514. */
  24515. void paste();
  24516. /** Moves the caret to be in front of a given character.
  24517. @see getCaretPosition
  24518. */
  24519. void setCaretPosition (const int newIndex) throw();
  24520. /** Returns the current index of the caret.
  24521. @see setCaretPosition
  24522. */
  24523. int getCaretPosition() const throw();
  24524. /** Attempts to scroll the text editor so that the caret ends up at
  24525. a specified position.
  24526. This won't affect the caret's position within the text, it tries to scroll
  24527. the entire editor vertically and horizontally so that the caret is sitting
  24528. at the given position (relative to the top-left of this component).
  24529. Depending on the amount of text available, it might not be possible to
  24530. scroll far enough for the caret to reach this exact position, but it
  24531. will go as far as it can in that direction.
  24532. */
  24533. void scrollEditorToPositionCaret (const int desiredCaretX,
  24534. const int desiredCaretY) throw();
  24535. /** Get the graphical position of the caret.
  24536. The rectangle returned is relative to the component's top-left corner.
  24537. @see scrollEditorToPositionCaret
  24538. */
  24539. const Rectangle getCaretRectangle() throw();
  24540. /** Selects a section of the text.
  24541. */
  24542. void setHighlightedRegion (int startIndex,
  24543. int numberOfCharactersToHighlight) throw();
  24544. /** Returns the first character that is selected.
  24545. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24546. will return 0.
  24547. @see setHighlightedRegion, getHighlightedRegionLength
  24548. */
  24549. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24550. /** Returns the number of characters that are selected.
  24551. @see setHighlightedRegion, getHighlightedRegionStart
  24552. */
  24553. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24554. /** Returns the section of text that is currently selected. */
  24555. const String getHighlightedText() const throw();
  24556. /** Finds the index of the character at a given position.
  24557. The co-ordinates are relative to the component's top-left.
  24558. */
  24559. int getTextIndexAt (const int x, const int y) throw();
  24560. /** Returns the total width of the text, as it is currently laid-out.
  24561. This may be larger than the size of the TextEditor, and can change when
  24562. the TextEditor is resized or the text changes.
  24563. */
  24564. int getTextWidth() const throw();
  24565. /** Returns the maximum height of the text, as it is currently laid-out.
  24566. This may be larger than the size of the TextEditor, and can change when
  24567. the TextEditor is resized or the text changes.
  24568. */
  24569. int getTextHeight() const throw();
  24570. /** Changes the size of the gap at the top and left-edge of the editor.
  24571. By default there's a gap of 4 pixels.
  24572. */
  24573. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24574. /** Changes the size of border left around the edge of the component.
  24575. @see getBorder
  24576. */
  24577. void setBorder (const BorderSize& border) throw();
  24578. /** Returns the size of border around the edge of the component.
  24579. @see setBorder
  24580. */
  24581. const BorderSize getBorder() const throw();
  24582. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24583. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24584. set to false, it won't.
  24585. */
  24586. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24587. /** @internal */
  24588. void paint (Graphics& g);
  24589. /** @internal */
  24590. void paintOverChildren (Graphics& g);
  24591. /** @internal */
  24592. void mouseDown (const MouseEvent& e);
  24593. /** @internal */
  24594. void mouseUp (const MouseEvent& e);
  24595. /** @internal */
  24596. void mouseDrag (const MouseEvent& e);
  24597. /** @internal */
  24598. void mouseDoubleClick (const MouseEvent& e);
  24599. /** @internal */
  24600. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24601. /** @internal */
  24602. bool keyPressed (const KeyPress& key);
  24603. /** @internal */
  24604. bool keyStateChanged();
  24605. /** @internal */
  24606. void focusGained (FocusChangeType cause);
  24607. /** @internal */
  24608. void focusLost (FocusChangeType cause);
  24609. /** @internal */
  24610. void resized();
  24611. /** @internal */
  24612. void enablementChanged();
  24613. /** @internal */
  24614. void colourChanged();
  24615. juce_UseDebuggingNewOperator
  24616. protected:
  24617. /** This adds the items to the popup menu.
  24618. By default it adds the cut/copy/paste items, but you can override this if
  24619. you need to replace these with your own items.
  24620. If you want to add your own items to the existing ones, you can override this,
  24621. call the base class's addPopupMenuItems() method, then append your own items.
  24622. When the menu has been shown, performPopupMenuAction() will be called to
  24623. perform the item that the user has chosen.
  24624. The default menu items will be added using item IDs in the range
  24625. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24626. menu IDs.
  24627. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24628. a pointer to the info about it, or may be null if the menu is being triggered
  24629. by some other means.
  24630. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24631. */
  24632. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24633. const MouseEvent* mouseClickEvent);
  24634. /** This is called to perform one of the items that was shown on the popup menu.
  24635. If you've overridden addPopupMenuItems(), you should also override this
  24636. to perform the actions that you've added.
  24637. If you've overridden addPopupMenuItems() but have still left the default items
  24638. on the menu, remember to call the superclass's performPopupMenuAction()
  24639. so that it can perform the default actions if that's what the user clicked on.
  24640. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24641. */
  24642. virtual void performPopupMenuAction (const int menuItemID);
  24643. /** Scrolls the minimum distance needed to get the caret into view. */
  24644. void scrollToMakeSureCursorIsVisible() throw();
  24645. /** @internal */
  24646. void moveCaret (int newCaretPos) throw();
  24647. /** @internal */
  24648. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24649. /** Used internally to dispatch a text-change message. */
  24650. void textChanged() throw();
  24651. /** Counts the number of characters in the text.
  24652. This is quicker than getting the text as a string if you just need to know
  24653. the length.
  24654. */
  24655. int getTotalNumChars() throw();
  24656. /** Begins a new transaction in the UndoManager.
  24657. */
  24658. void newTransaction() throw();
  24659. /** Used internally to trigger an undo or redo. */
  24660. void doUndoRedo (const bool isRedo);
  24661. /** Can be overridden to intercept return key presses directly */
  24662. virtual void returnPressed();
  24663. /** Can be overridden to intercept escape key presses directly */
  24664. virtual void escapePressed();
  24665. /** @internal */
  24666. void handleCommandMessage (int commandId);
  24667. private:
  24668. Viewport* viewport;
  24669. TextHolderComponent* textHolder;
  24670. BorderSize borderSize;
  24671. bool readOnly : 1;
  24672. bool multiline : 1;
  24673. bool wordWrap : 1;
  24674. bool returnKeyStartsNewLine : 1;
  24675. bool caretVisible : 1;
  24676. bool popupMenuEnabled : 1;
  24677. bool selectAllTextWhenFocused : 1;
  24678. bool scrollbarVisible : 1;
  24679. bool wasFocused : 1;
  24680. bool caretFlashState : 1;
  24681. bool keepCursorOnScreen : 1;
  24682. bool tabKeyUsed : 1;
  24683. bool menuActive : 1;
  24684. UndoManager undoManager;
  24685. float cursorX, cursorY, cursorHeight;
  24686. int maxTextLength;
  24687. int selectionStart, selectionEnd;
  24688. int leftIndent, topIndent;
  24689. unsigned int lastTransactionTime;
  24690. Font currentFont;
  24691. int totalNumChars, caretPosition;
  24692. VoidArray sections;
  24693. String textToShowWhenEmpty;
  24694. Colour colourForTextWhenEmpty;
  24695. tchar passwordCharacter;
  24696. enum
  24697. {
  24698. notDragging,
  24699. draggingSelectionStart,
  24700. draggingSelectionEnd
  24701. } dragType;
  24702. String allowedCharacters;
  24703. SortedSet <void*> listeners;
  24704. friend class TextEditorInsertAction;
  24705. friend class TextEditorRemoveAction;
  24706. void coalesceSimilarSections() throw();
  24707. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24708. void clearInternal (UndoManager* const um) throw();
  24709. void insert (const String& text,
  24710. const int insertIndex,
  24711. const Font& font,
  24712. const Colour& colour,
  24713. UndoManager* const um,
  24714. const int caretPositionToMoveTo) throw();
  24715. void reinsert (const int insertIndex,
  24716. const VoidArray& sections) throw();
  24717. void remove (const int startIndex,
  24718. int endIndex,
  24719. UndoManager* const um,
  24720. const int caretPositionToMoveTo) throw();
  24721. void getCharPosition (const int index,
  24722. float& x, float& y,
  24723. float& lineHeight) const throw();
  24724. void updateCaretPosition() throw();
  24725. int indexAtPosition (const float x,
  24726. const float y) throw();
  24727. int findWordBreakAfter (const int position) const throw();
  24728. int findWordBreakBefore (const int position) const throw();
  24729. friend class TextHolderComponent;
  24730. friend class TextEditorViewport;
  24731. void drawContent (Graphics& g);
  24732. void updateTextHolderSize() throw();
  24733. float getWordWrapWidth() const throw();
  24734. void timerCallbackInt();
  24735. void repaintCaret();
  24736. void repaintText (int textStartIndex, int textEndIndex);
  24737. TextEditor (const TextEditor&);
  24738. const TextEditor& operator= (const TextEditor&);
  24739. };
  24740. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24741. /********* End of inlined file: juce_TextEditor.h *********/
  24742. class Label;
  24743. /**
  24744. A class for receiving events from a Label.
  24745. You can register a LabelListener with a Label using the Label::addListener()
  24746. method, and it will be called when the text of the label changes, either because
  24747. of a call to Label::setText() or by the user editing the text (if the label is
  24748. editable).
  24749. @see Label::addListener, Label::removeListener
  24750. */
  24751. class JUCE_API LabelListener
  24752. {
  24753. public:
  24754. /** Destructor. */
  24755. virtual ~LabelListener() {}
  24756. /** Called when a Label's text has changed.
  24757. */
  24758. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24759. };
  24760. /**
  24761. A component that displays a text string, and can optionally become a text
  24762. editor when clicked.
  24763. */
  24764. class JUCE_API Label : public Component,
  24765. public SettableTooltipClient,
  24766. protected TextEditorListener,
  24767. private ComponentListener
  24768. {
  24769. public:
  24770. /** Creates a Label.
  24771. @param componentName the name to give the component
  24772. @param labelText the text to show in the label
  24773. */
  24774. Label (const String& componentName,
  24775. const String& labelText);
  24776. /** Destructor. */
  24777. ~Label();
  24778. /** Changes the label text.
  24779. If broadcastChangeMessage is true and the new text is different to the current
  24780. text, then the class will broadcast a change message to any LabelListeners that
  24781. are registered.
  24782. */
  24783. void setText (const String& newText,
  24784. const bool broadcastChangeMessage);
  24785. /** Returns the label's current text.
  24786. @param returnActiveEditorContents if this is true and the label is currently
  24787. being edited, then this method will return the
  24788. text as it's being shown in the editor. If false,
  24789. then the value returned here won't be updated until
  24790. the user has finished typing and pressed the return
  24791. key.
  24792. */
  24793. const String getText (const bool returnActiveEditorContents = false) const throw();
  24794. /** Changes the font to use to draw the text.
  24795. @see getFont
  24796. */
  24797. void setFont (const Font& newFont) throw();
  24798. /** Returns the font currently being used.
  24799. @see setFont
  24800. */
  24801. const Font& getFont() const throw();
  24802. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24803. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24804. methods.
  24805. Note that you can also use the constants from TextEditor::ColourIds to change the
  24806. colour of the text editor that is opened when a label is editable.
  24807. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24808. */
  24809. enum ColourIds
  24810. {
  24811. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  24812. textColourId = 0x1000281, /**< The colour for the text. */
  24813. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  24814. Leave this transparent to not have an outline. */
  24815. };
  24816. /** Sets the style of justification to be used for positioning the text.
  24817. (The default is Justification::centredLeft)
  24818. */
  24819. void setJustificationType (const Justification& justification) throw();
  24820. /** Returns the type of justification, as set in setJustificationType(). */
  24821. const Justification getJustificationType() const throw() { return justification; }
  24822. /** Changes the gap that is left between the edge of the component and the text.
  24823. By default there's a small gap left at the sides of the component to allow for
  24824. the drawing of the border, but you can change this if necessary.
  24825. */
  24826. void setBorderSize (int horizontalBorder, int verticalBorder);
  24827. /** Returns the size of the horizontal gap being left around the text.
  24828. */
  24829. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  24830. /** Returns the size of the vertical gap being left around the text.
  24831. */
  24832. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  24833. /** Makes this label "stick to" another component.
  24834. This will cause the label to follow another component around, staying
  24835. either to its left or above it.
  24836. @param owner the component to follow
  24837. @param onLeft if true, the label will stay on the left of its component; if
  24838. false, it will stay above it.
  24839. */
  24840. void attachToComponent (Component* owner,
  24841. const bool onLeft);
  24842. /** If this label has been attached to another component using attachToComponent, this
  24843. returns the other component.
  24844. Returns 0 if the label is not attached.
  24845. */
  24846. Component* getAttachedComponent() const throw() { return ownerComponent; }
  24847. /** If the label is attached to the left of another component, this returns true.
  24848. Returns false if the label is above the other component. This is only relevent if
  24849. attachToComponent() has been called.
  24850. */
  24851. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  24852. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  24853. using ellipsis.
  24854. @see Graphics::drawFittedText
  24855. */
  24856. void setMinimumHorizontalScale (const float newScale);
  24857. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  24858. /** Registers a listener that will be called when the label's text changes. */
  24859. void addListener (LabelListener* const listener) throw();
  24860. /** Deregisters a previously-registered listener. */
  24861. void removeListener (LabelListener* const listener) throw();
  24862. /** Makes the label turn into a TextEditor when clicked.
  24863. By default this is turned off.
  24864. If turned on, then single- or double-clicking will turn the label into
  24865. an editor. If the user then changes the text, then the ChangeBroadcaster
  24866. base class will be used to send change messages to any listeners that
  24867. have registered.
  24868. If the user changes the text, the textWasEdited() method will be called
  24869. afterwards, and subclasses can override this if they need to do anything
  24870. special.
  24871. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  24872. @param editOnDoubleClick if true, a double-click is needed to start editing
  24873. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  24874. edited will discard any changes; if false, then this will
  24875. commit the changes.
  24876. @see showEditor, setEditorColours, TextEditor
  24877. */
  24878. void setEditable (const bool editOnSingleClick,
  24879. const bool editOnDoubleClick = false,
  24880. const bool lossOfFocusDiscardsChanges = false) throw();
  24881. /** Returns true if this option was set using setEditable(). */
  24882. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  24883. /** Returns true if this option was set using setEditable(). */
  24884. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  24885. /** Returns true if this option has been set in a call to setEditable(). */
  24886. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  24887. /** Returns true if the user can edit this label's text. */
  24888. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  24889. /** Makes the editor appear as if the label had been clicked by the user.
  24890. @see textWasEdited, setEditable
  24891. */
  24892. void showEditor();
  24893. /** Hides the editor if it was being shown.
  24894. @param discardCurrentEditorContents if true, the label's text will be
  24895. reset to whatever it was before the editor
  24896. was shown; if false, the current contents of the
  24897. editor will be used to set the label's text
  24898. before it is hidden.
  24899. */
  24900. void hideEditor (const bool discardCurrentEditorContents);
  24901. /** Returns true if the editor is currently focused and active. */
  24902. bool isBeingEdited() const throw();
  24903. juce_UseDebuggingNewOperator
  24904. protected:
  24905. /** @internal */
  24906. void paint (Graphics& g);
  24907. /** @internal */
  24908. void resized();
  24909. /** @internal */
  24910. void mouseUp (const MouseEvent& e);
  24911. /** @internal */
  24912. void mouseDoubleClick (const MouseEvent& e);
  24913. /** @internal */
  24914. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24915. /** @internal */
  24916. void componentParentHierarchyChanged (Component& component);
  24917. /** @internal */
  24918. void componentVisibilityChanged (Component& component);
  24919. /** @internal */
  24920. void inputAttemptWhenModal();
  24921. /** @internal */
  24922. void focusGained (FocusChangeType);
  24923. /** @internal */
  24924. void enablementChanged();
  24925. /** @internal */
  24926. KeyboardFocusTraverser* createFocusTraverser();
  24927. /** @internal */
  24928. void textEditorTextChanged (TextEditor& editor);
  24929. /** @internal */
  24930. void textEditorReturnKeyPressed (TextEditor& editor);
  24931. /** @internal */
  24932. void textEditorEscapeKeyPressed (TextEditor& editor);
  24933. /** @internal */
  24934. void textEditorFocusLost (TextEditor& editor);
  24935. /** @internal */
  24936. void colourChanged();
  24937. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  24938. Subclasses can override this if they need to customise this component in some way.
  24939. */
  24940. virtual TextEditor* createEditorComponent();
  24941. /** Called after the user changes the text.
  24942. */
  24943. virtual void textWasEdited();
  24944. /** Called when the text has been altered.
  24945. */
  24946. virtual void textWasChanged();
  24947. private:
  24948. String text;
  24949. Font font;
  24950. Justification justification;
  24951. TextEditor* editor;
  24952. SortedSet <void*> listeners;
  24953. Component* ownerComponent;
  24954. ComponentDeletionWatcher* deletionWatcher;
  24955. int horizontalBorderSize, verticalBorderSize;
  24956. float minimumHorizontalScale;
  24957. bool editSingleClick : 1;
  24958. bool editDoubleClick : 1;
  24959. bool lossOfFocusDiscardsChanges : 1;
  24960. bool leftOfOwnerComp : 1;
  24961. bool updateFromTextEditorContents();
  24962. void callChangeListeners();
  24963. Label (const Label&);
  24964. const Label& operator= (const Label&);
  24965. };
  24966. #endif // __JUCE_LABEL_JUCEHEADER__
  24967. /********* End of inlined file: juce_Label.h *********/
  24968. class ComboBox;
  24969. /**
  24970. A class for receiving events from a ComboBox.
  24971. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  24972. method, and it will be called when the selected item in the box changes.
  24973. @see ComboBox::addListener, ComboBox::removeListener
  24974. */
  24975. class JUCE_API ComboBoxListener
  24976. {
  24977. public:
  24978. /** Destructor. */
  24979. virtual ~ComboBoxListener() {}
  24980. /** Called when a ComboBox has its selected item changed.
  24981. */
  24982. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  24983. };
  24984. /**
  24985. A component that lets the user choose from a drop-down list of choices.
  24986. The combo-box has a list of text strings, each with an associated id number,
  24987. that will be shown in the drop-down list when the user clicks on the component.
  24988. The currently selected choice is displayed in the combo-box, and this can
  24989. either be read-only text, or editable.
  24990. To find out when the user selects a different item or edits the text, you
  24991. can register a ComboBoxListener to receive callbacks.
  24992. @see ComboBoxListener
  24993. */
  24994. class JUCE_API ComboBox : public Component,
  24995. public SettableTooltipClient,
  24996. private LabelListener,
  24997. private AsyncUpdater
  24998. {
  24999. public:
  25000. /** Creates a combo-box.
  25001. On construction, the text field will be empty, so you should call the
  25002. setSelectedId() or setText() method to choose the initial value before
  25003. displaying it.
  25004. @param componentName the name to set for the component (see Component::setName())
  25005. */
  25006. ComboBox (const String& componentName);
  25007. /** Destructor. */
  25008. ~ComboBox();
  25009. /** Sets whether the test in the combo-box is editable.
  25010. The default state for a new ComboBox is non-editable, and can only be changed
  25011. by choosing from the drop-down list.
  25012. */
  25013. void setEditableText (const bool isEditable);
  25014. /** Returns true if the text is directly editable.
  25015. @see setEditableText
  25016. */
  25017. bool isTextEditable() const throw();
  25018. /** Sets the style of justification to be used for positioning the text.
  25019. The default is Justification::centredLeft. The text is displayed using a
  25020. Label component inside the ComboBox.
  25021. */
  25022. void setJustificationType (const Justification& justification) throw();
  25023. /** Returns the current justification for the text box.
  25024. @see setJustificationType
  25025. */
  25026. const Justification getJustificationType() const throw();
  25027. /** Adds an item to be shown in the drop-down list.
  25028. @param newItemText the text of the item to show in the list
  25029. @param newItemId an associated ID number that can be set or retrieved - see
  25030. getSelectedId() and setSelectedId()
  25031. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25032. */
  25033. void addItem (const String& newItemText,
  25034. const int newItemId) throw();
  25035. /** Adds a separator line to the drop-down list.
  25036. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25037. */
  25038. void addSeparator() throw();
  25039. /** Adds a heading to the drop-down list, so that you can group the items into
  25040. different sections.
  25041. The headings are indented slightly differently to set them apart from the
  25042. items on the list, and obviously can't be selected. You might want to add
  25043. separators between your sections too.
  25044. @see addItem, addSeparator
  25045. */
  25046. void addSectionHeading (const String& headingName) throw();
  25047. /** This allows items in the drop-down list to be selectively disabled.
  25048. When you add an item, it's enabled by default, but you can call this
  25049. method to change its status.
  25050. If you disable an item which is already selected, this won't change the
  25051. current selection - it just stops the user choosing that item from the list.
  25052. */
  25053. void setItemEnabled (const int itemId,
  25054. const bool isEnabled) throw();
  25055. /** Changes the text for an existing item.
  25056. */
  25057. void changeItemText (const int itemId,
  25058. const String& newText) throw();
  25059. /** Removes all the items from the drop-down list.
  25060. If this call causes the content to be cleared, then a change-message
  25061. will be broadcast unless dontSendChangeMessage is true.
  25062. @see addItem, removeItem, getNumItems
  25063. */
  25064. void clear (const bool dontSendChangeMessage = false);
  25065. /** Returns the number of items that have been added to the list.
  25066. Note that this doesn't include headers or separators.
  25067. */
  25068. int getNumItems() const throw();
  25069. /** Returns the text for one of the items in the list.
  25070. Note that this doesn't include headers or separators.
  25071. @param index the item's index from 0 to (getNumItems() - 1)
  25072. */
  25073. const String getItemText (const int index) const throw();
  25074. /** Returns the ID for one of the items in the list.
  25075. Note that this doesn't include headers or separators.
  25076. @param index the item's index from 0 to (getNumItems() - 1)
  25077. */
  25078. int getItemId (const int index) const throw();
  25079. /** Returns the ID of the item that's currently shown in the box.
  25080. If no item is selected, or if the text is editable and the user
  25081. has entered something which isn't one of the items in the list, then
  25082. this will return 0.
  25083. @see setSelectedId, getSelectedItemIndex, getText
  25084. */
  25085. int getSelectedId() const throw();
  25086. /** Sets one of the items to be the current selection.
  25087. This will set the ComboBox's text to that of the item that matches
  25088. this ID.
  25089. @param newItemId the new item to select
  25090. @param dontSendChangeMessage if set to true, this method won't trigger a
  25091. change notification
  25092. @see getSelectedId, setSelectedItemIndex, setText
  25093. */
  25094. void setSelectedId (const int newItemId,
  25095. const bool dontSendChangeMessage = false) throw();
  25096. /** Returns the index of the item that's currently shown in the box.
  25097. If no item is selected, or if the text is editable and the user
  25098. has entered something which isn't one of the items in the list, then
  25099. this will return -1.
  25100. @see setSelectedItemIndex, getSelectedId, getText
  25101. */
  25102. int getSelectedItemIndex() const throw();
  25103. /** Sets one of the items to be the current selection.
  25104. This will set the ComboBox's text to that of the item at the given
  25105. index in the list.
  25106. @param newItemIndex the new item to select
  25107. @param dontSendChangeMessage if set to true, this method won't trigger a
  25108. change notification
  25109. @see getSelectedItemIndex, setSelectedId, setText
  25110. */
  25111. void setSelectedItemIndex (const int newItemIndex,
  25112. const bool dontSendChangeMessage = false) throw();
  25113. /** Returns the text that is currently shown in the combo-box's text field.
  25114. If the ComboBox has editable text, then this text may have been edited
  25115. by the user; otherwise it will be one of the items from the list, or
  25116. possibly an empty string if nothing was selected.
  25117. @see setText, getSelectedId, getSelectedItemIndex
  25118. */
  25119. const String getText() const throw();
  25120. /** Sets the contents of the combo-box's text field.
  25121. The text passed-in will be set as the current text regardless of whether
  25122. it is one of the items in the list. If the current text isn't one of the
  25123. items, then getSelectedId() will return -1, otherwise it wil return
  25124. the approriate ID.
  25125. @param newText the text to select
  25126. @param dontSendChangeMessage if set to true, this method won't trigger a
  25127. change notification
  25128. @see getText
  25129. */
  25130. void setText (const String& newText,
  25131. const bool dontSendChangeMessage = false) throw();
  25132. /** Programmatically opens the text editor to allow the user to edit the current item.
  25133. This is the same effect as when the box is clicked-on.
  25134. @see Label::showEditor();
  25135. */
  25136. void showEditor();
  25137. /** Registers a listener that will be called when the box's content changes. */
  25138. void addListener (ComboBoxListener* const listener) throw();
  25139. /** Deregisters a previously-registered listener. */
  25140. void removeListener (ComboBoxListener* const listener) throw();
  25141. /** Sets a message to display when there is no item currently selected.
  25142. @see getTextWhenNothingSelected
  25143. */
  25144. void setTextWhenNothingSelected (const String& newMessage) throw();
  25145. /** Returns the text that is shown when no item is selected.
  25146. @see setTextWhenNothingSelected
  25147. */
  25148. const String getTextWhenNothingSelected() const throw();
  25149. /** Sets the message to show when there are no items in the list, and the user clicks
  25150. on the drop-down box.
  25151. By default it just says "no choices", but this lets you change it to something more
  25152. meaningful.
  25153. */
  25154. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25155. /** Returns the text shown when no items have been added to the list.
  25156. @see setTextWhenNoChoicesAvailable
  25157. */
  25158. const String getTextWhenNoChoicesAvailable() const throw();
  25159. /** Gives the ComboBox a tooltip. */
  25160. void setTooltip (const String& newTooltip);
  25161. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25162. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25163. methods.
  25164. To change the colours of the menu that pops up
  25165. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25166. */
  25167. enum ColourIds
  25168. {
  25169. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25170. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25171. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25172. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25173. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25174. };
  25175. /** @internal */
  25176. void labelTextChanged (Label*);
  25177. /** @internal */
  25178. void enablementChanged();
  25179. /** @internal */
  25180. void colourChanged();
  25181. /** @internal */
  25182. void focusGained (Component::FocusChangeType cause);
  25183. /** @internal */
  25184. void focusLost (Component::FocusChangeType cause);
  25185. /** @internal */
  25186. void handleAsyncUpdate();
  25187. /** @internal */
  25188. const String getTooltip() { return label->getTooltip(); }
  25189. /** @internal */
  25190. void mouseDown (const MouseEvent&);
  25191. /** @internal */
  25192. void mouseDrag (const MouseEvent&);
  25193. /** @internal */
  25194. void mouseUp (const MouseEvent&);
  25195. /** @internal */
  25196. void lookAndFeelChanged();
  25197. /** @internal */
  25198. void paint (Graphics&);
  25199. /** @internal */
  25200. void resized();
  25201. /** @internal */
  25202. bool keyStateChanged();
  25203. /** @internal */
  25204. bool keyPressed (const KeyPress&);
  25205. juce_UseDebuggingNewOperator
  25206. private:
  25207. struct ItemInfo
  25208. {
  25209. String name;
  25210. int itemId;
  25211. bool isEnabled : 1, isHeading : 1;
  25212. bool isSeparator() const throw();
  25213. bool isRealItem() const throw();
  25214. };
  25215. OwnedArray <ItemInfo> items;
  25216. int currentIndex;
  25217. bool isButtonDown;
  25218. bool separatorPending;
  25219. bool menuActive;
  25220. SortedSet <void*> listeners;
  25221. Label* label;
  25222. String textWhenNothingSelected, noChoicesMessage;
  25223. void showPopup();
  25224. ItemInfo* getItemForId (const int itemId) const throw();
  25225. ItemInfo* getItemForIndex (const int index) const throw();
  25226. ComboBox (const ComboBox&);
  25227. const ComboBox& operator= (const ComboBox&);
  25228. };
  25229. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25230. /********* End of inlined file: juce_ComboBox.h *********/
  25231. /**
  25232. Manages the state of some audio and midi i/o devices.
  25233. This class keeps tracks of a currently-selected audio device, through
  25234. with which it continuously streams data from an audio callback, as well as
  25235. one or more midi inputs.
  25236. The idea is that your application will create one global instance of this object,
  25237. and let it take care of creating and deleting specific types of audio devices
  25238. internally. So when the device is changed, your callbacks will just keep running
  25239. without having to worry about this.
  25240. The manager can save and reload all of its device settings as XML, which
  25241. makes it very easy for you to save and reload the audio setup of your
  25242. application.
  25243. And to make it easy to let the user change its settings, there's a component
  25244. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25245. device selection/sample-rate/latency controls.
  25246. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25247. call setAudioCallback() to register your audio callback with it, and use that to process
  25248. your audio data.
  25249. The manager also acts as a handy hub for incoming midi messages, allowing a
  25250. listener to register for messages from either a specific midi device, or from whatever
  25251. the current default midi input device is. The listener then doesn't have to worry about
  25252. re-registering with different midi devices if they are changed or deleted.
  25253. And yet another neat trick is that amount of CPU time being used is measured and
  25254. available with the getCpuUsage() method.
  25255. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25256. listeners whenever one of its settings is changed.
  25257. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25258. */
  25259. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25260. {
  25261. public:
  25262. /** Creates a default AudioDeviceManager.
  25263. Initially no audio device will be selected. You should call the initialise() method
  25264. and register an audio callback with setAudioCallback() before it'll be able to
  25265. actually make any noise.
  25266. */
  25267. AudioDeviceManager();
  25268. /** Destructor. */
  25269. ~AudioDeviceManager();
  25270. /** Opens a set of audio devices ready for use.
  25271. This will attempt to open either a default audio device, or one that was
  25272. previously saved as XML.
  25273. @param numInputChannelsNeeded a minimum number of input channels needed
  25274. by your app.
  25275. @param numOutputChannelsNeeded a minimum number of output channels to open
  25276. @param savedState either a previously-saved state that was produced
  25277. by createStateXml(), or 0 if you want the manager
  25278. to choose the best device to open.
  25279. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25280. fails to open, then a default device will be used
  25281. instead. If false, then on failure, no device is
  25282. opened.
  25283. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25284. name, then that will be used as the default device
  25285. (assuming that there wasn't one specified in the XML).
  25286. The string can actually be a simple wildcard, containing "*"
  25287. and "?" characters
  25288. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25289. */
  25290. const String initialise (const int numInputChannelsNeeded,
  25291. const int numOutputChannelsNeeded,
  25292. const XmlElement* const savedState,
  25293. const bool selectDefaultDeviceOnFailure,
  25294. const String& preferredDefaultDeviceName = String::empty);
  25295. /** Returns some XML representing the current state of the manager.
  25296. This stores the current device, its samplerate, block size, etc, and
  25297. can be restored later with initialise().
  25298. */
  25299. XmlElement* createStateXml() const;
  25300. /**
  25301. */
  25302. struct AudioDeviceSetup
  25303. {
  25304. AudioDeviceSetup();
  25305. bool operator== (const AudioDeviceSetup& other) const;
  25306. /**
  25307. */
  25308. String outputDeviceName;
  25309. /**
  25310. */
  25311. String inputDeviceName;
  25312. /**
  25313. */
  25314. double sampleRate;
  25315. /**
  25316. */
  25317. int bufferSize;
  25318. /**
  25319. */
  25320. BitArray inputChannels;
  25321. bool useDefaultInputChannels;
  25322. /**
  25323. */
  25324. BitArray outputChannels;
  25325. bool useDefaultOutputChannels;
  25326. };
  25327. /**
  25328. */
  25329. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25330. /**
  25331. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25332. settings will be taken as having been explicitly chosen by the
  25333. user, and the next time createStateXml() is called, these settings
  25334. will be returned. If it's false, then the device is treated as a
  25335. temporary or default device, and a call to createStateXml() will
  25336. return either the last settings that were made with treatAsChosenDevice
  25337. as true, or the last XML settings that were passed into initialise().
  25338. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25339. */
  25340. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25341. const bool treatAsChosenDevice);
  25342. /** Returns the currently-active audio device. */
  25343. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25344. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25345. void setCurrentAudioDeviceType (const String& type,
  25346. const bool treatAsChosenDevice);
  25347. /** Closes the currently-open device.
  25348. You can call restartLastAudioDevice() later to reopen it in the same state
  25349. that it was just in.
  25350. */
  25351. void closeAudioDevice();
  25352. /** Tries to reload the last audio device that was running.
  25353. Note that this only reloads the last device that was running before
  25354. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25355. and can only be called after a device has been opened with SetAudioDevice().
  25356. If a device is already open, this call will do nothing.
  25357. */
  25358. void restartLastAudioDevice();
  25359. /** Gives the manager an audio callback to use.
  25360. The manager will redirect callbacks from whatever audio device is currently
  25361. in use to this callback object.
  25362. You can pass 0 in here to stop callbacks being made.
  25363. */
  25364. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25365. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25366. Returns a value between 0 and 1.0
  25367. */
  25368. double getCpuUsage() const;
  25369. /** Enables or disables a midi input device.
  25370. The list of devices can be obtained with the MidiInput::getDevices() method.
  25371. Any incoming messages from enabled input devices will be forwarded on to all the
  25372. listeners that have been registered with the addMidiInputCallback() method. They
  25373. can either register for messages from a particular device, or from just the
  25374. "default" midi input.
  25375. Routing the midi input via an AudioDeviceManager means that when a listener
  25376. registers for the default midi input, this default device can be changed by the
  25377. manager without the listeners having to know about it or re-register.
  25378. It also means that a listener can stay registered for a midi input that is disabled
  25379. or not present, so that when the input is re-enabled, the listener will start
  25380. receiving messages again.
  25381. @see addMidiInputCallback, isMidiInputEnabled
  25382. */
  25383. void setMidiInputEnabled (const String& midiInputDeviceName,
  25384. const bool enabled);
  25385. /** Returns true if a given midi input device is being used.
  25386. @see setMidiInputEnabled
  25387. */
  25388. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25389. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25390. The device name can be empty to indicate that it wants events from whatever the
  25391. current "default" device is. Or it can be the name of one of the midi input devices
  25392. (see MidiInput::getDevices() for the names).
  25393. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25394. events forwarded on to listeners.
  25395. */
  25396. void addMidiInputCallback (const String& midiInputDeviceName,
  25397. MidiInputCallback* callback);
  25398. /** Removes a listener that was previously registered with addMidiInputCallback().
  25399. */
  25400. void removeMidiInputCallback (const String& midiInputDeviceName,
  25401. MidiInputCallback* callback);
  25402. /** Sets a midi output device to use as the default.
  25403. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25404. The specified device will be opened automatically and can be retrieved with the
  25405. getDefaultMidiOutput() method.
  25406. Pass in an empty string to deselect all devices. For the default device, you
  25407. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25408. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25409. */
  25410. void setDefaultMidiOutput (const String& deviceName);
  25411. /** Returns the name of the default midi output.
  25412. @see setDefaultMidiOutput, getDefaultMidiOutput
  25413. */
  25414. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25415. /** Returns the current default midi output device.
  25416. If no device has been selected, or the device can't be opened, this will
  25417. return 0.
  25418. @see getDefaultMidiOutputName
  25419. */
  25420. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25421. /**
  25422. */
  25423. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25424. /** Creates a list of available types.
  25425. This will add a set of new AudioIODeviceType objects to the specified list, to
  25426. represent each available types of device.
  25427. You can override this if your app needs to do something specific, like avoid
  25428. using DirectSound devices, etc.
  25429. */
  25430. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25431. /** Plays a beep through the current audio device.
  25432. This is here to allow the audio setup UI panels to easily include a "test"
  25433. button so that the user can check where the audio is coming from.
  25434. */
  25435. void playTestSound();
  25436. /** Turns on level-measuring.
  25437. When enabled, the device manager will measure the peak input level
  25438. across all channels, and you can get this level by calling getCurrentInputLevel().
  25439. This is mainly intended for audio setup UI panels to use to create a mic
  25440. level display, so that the user can check that they've selected the right
  25441. device.
  25442. A simple filter is used to make the level decay smoothly, but this is
  25443. only intended for giving rough feedback, and not for any kind of accurate
  25444. measurement.
  25445. */
  25446. void enableInputLevelMeasurement (const bool enableMeasurement);
  25447. /** Returns the current input level.
  25448. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25449. See enableInputLevelMeasurement() for more info.
  25450. */
  25451. double getCurrentInputLevel() const;
  25452. juce_UseDebuggingNewOperator
  25453. private:
  25454. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25455. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25456. AudioDeviceSetup currentSetup;
  25457. AudioIODevice* currentAudioDevice;
  25458. AudioIODeviceCallback* currentCallback;
  25459. int numInputChansNeeded, numOutputChansNeeded;
  25460. String currentDeviceType;
  25461. BitArray inputChannels, outputChannels;
  25462. XmlElement* lastExplicitSettings;
  25463. mutable bool listNeedsScanning;
  25464. bool useInputNames, inputLevelMeasurementEnabled;
  25465. double inputLevel;
  25466. AudioSampleBuffer* testSound;
  25467. int testSoundPosition;
  25468. StringArray midiInsFromXml;
  25469. OwnedArray <MidiInput> enabledMidiInputs;
  25470. Array <MidiInputCallback*> midiCallbacks;
  25471. Array <MidiInput*> midiCallbackDevices;
  25472. String defaultMidiOutputName;
  25473. MidiOutput* defaultMidiOutput;
  25474. CriticalSection audioCallbackLock, midiCallbackLock;
  25475. double cpuUsageMs, timeToCpuScale;
  25476. class CallbackHandler : public AudioIODeviceCallback,
  25477. public MidiInputCallback
  25478. {
  25479. public:
  25480. AudioDeviceManager* owner;
  25481. void audioDeviceIOCallback (const float** inputChannelData,
  25482. int totalNumInputChannels,
  25483. float** outputChannelData,
  25484. int totalNumOutputChannels,
  25485. int numSamples);
  25486. void audioDeviceAboutToStart (AudioIODevice*);
  25487. void audioDeviceStopped();
  25488. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25489. };
  25490. CallbackHandler callbackHandler;
  25491. friend class CallbackHandler;
  25492. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25493. int totalNumInputChannels,
  25494. float** outputChannelData,
  25495. int totalNumOutputChannels,
  25496. int numSamples);
  25497. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25498. void audioDeviceStoppedInt();
  25499. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25500. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25501. const BitArray& ins, const BitArray& outs);
  25502. void stopDevice();
  25503. void updateXml();
  25504. void createDeviceTypesIfNeeded();
  25505. void scanDevicesIfNeeded();
  25506. void deleteCurrentDevice();
  25507. double chooseBestSampleRate (double preferred) const;
  25508. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25509. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25510. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25511. AudioDeviceManager (const AudioDeviceManager&);
  25512. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25513. };
  25514. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25515. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25516. #endif
  25517. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25518. #endif
  25519. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25520. #endif
  25521. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25522. #endif
  25523. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25524. #endif
  25525. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25526. /********* Start of inlined file: juce_Sampler.h *********/
  25527. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25528. #define __JUCE_SAMPLER_JUCEHEADER__
  25529. /********* Start of inlined file: juce_Synthesiser.h *********/
  25530. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25531. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25532. /**
  25533. Describes one of the sounds that a Synthesiser can play.
  25534. A synthesiser can contain one or more sounds, and a sound can choose which
  25535. midi notes and channels can trigger it.
  25536. The SynthesiserSound is a passive class that just describes what the sound is -
  25537. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25538. more than one SynthesiserVoice to play the same sound at the same time.
  25539. @see Synthesiser, SynthesiserVoice
  25540. */
  25541. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25542. {
  25543. protected:
  25544. SynthesiserSound();
  25545. public:
  25546. /** Destructor. */
  25547. virtual ~SynthesiserSound();
  25548. /** Returns true if this sound should be played when a given midi note is pressed.
  25549. The Synthesiser will use this information when deciding which sounds to trigger
  25550. for a given note.
  25551. */
  25552. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25553. /** Returns true if the sound should be triggered by midi events on a given channel.
  25554. The Synthesiser will use this information when deciding which sounds to trigger
  25555. for a given note.
  25556. */
  25557. virtual bool appliesToChannel (const int midiChannel) = 0;
  25558. /**
  25559. */
  25560. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25561. juce_UseDebuggingNewOperator
  25562. };
  25563. /**
  25564. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25565. A voice plays a single sound at a time, and a synthesiser holds an array of
  25566. voices so that it can play polyphonically.
  25567. @see Synthesiser, SynthesiserSound
  25568. */
  25569. class JUCE_API SynthesiserVoice
  25570. {
  25571. public:
  25572. /** Creates a voice. */
  25573. SynthesiserVoice();
  25574. /** Destructor. */
  25575. virtual ~SynthesiserVoice();
  25576. /** Returns the midi note that this voice is currently playing.
  25577. Returns a value less than 0 if no note is playing.
  25578. */
  25579. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25580. /** Returns the sound that this voice is currently playing.
  25581. Returns 0 if it's not playing.
  25582. */
  25583. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25584. /** Must return true if this voice object is capable of playing the given sound.
  25585. If there are different classes of sound, and different classes of voice, a voice can
  25586. choose which ones it wants to take on.
  25587. A typical implementation of this method may just return true if there's only one type
  25588. of voice and sound, or it might check the type of the sound object passed-in and
  25589. see if it's one that it understands.
  25590. */
  25591. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25592. /** Called to start a new note.
  25593. This will be called during the rendering callback, so must be fast and thread-safe.
  25594. */
  25595. virtual void startNote (const int midiNoteNumber,
  25596. const float velocity,
  25597. SynthesiserSound* sound,
  25598. const int currentPitchWheelPosition) = 0;
  25599. /** Called to stop a note.
  25600. This will be called during the rendering callback, so must be fast and thread-safe.
  25601. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25602. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25603. and allow the synth to reassign it another sound.
  25604. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25605. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25606. finishes playing (during the rendering callback), it must make sure that it calls
  25607. clearCurrentNote().
  25608. */
  25609. virtual void stopNote (const bool allowTailOff) = 0;
  25610. /** Called to let the voice know that the pitch wheel has been moved.
  25611. This will be called during the rendering callback, so must be fast and thread-safe.
  25612. */
  25613. virtual void pitchWheelMoved (const int newValue) = 0;
  25614. /** Called to let the voice know that a midi controller has been moved.
  25615. This will be called during the rendering callback, so must be fast and thread-safe.
  25616. */
  25617. virtual void controllerMoved (const int controllerNumber,
  25618. const int newValue) = 0;
  25619. /** Renders the next block of data for this voice.
  25620. The output audio data must be added to the current contents of the buffer provided.
  25621. Only the region of the buffer between startSample and (startSample + numSamples)
  25622. should be altered by this method.
  25623. If the voice is currently silent, it should just return without doing anything.
  25624. If the sound that the voice is playing finishes during the course of this rendered
  25625. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25626. The size of the blocks that are rendered can change each time it is called, and may
  25627. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25628. the voice's methods will be called to tell it about note and controller events.
  25629. */
  25630. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25631. int startSample,
  25632. int numSamples) = 0;
  25633. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25634. midi channel.
  25635. If it's not currently playing, this will return false.
  25636. */
  25637. bool isPlayingChannel (const int midiChannel) const;
  25638. /** Changes the voice's reference sample rate.
  25639. The rate is set so that subclasses know the output rate and can set their pitch
  25640. accordingly.
  25641. This method is called by the synth, and subclasses can access the current rate with
  25642. the currentSampleRate member.
  25643. */
  25644. void setCurrentPlaybackSampleRate (const double newRate);
  25645. juce_UseDebuggingNewOperator
  25646. protected:
  25647. /** Returns the current target sample rate at which rendering is being done.
  25648. This is available for subclasses so they can pitch things correctly.
  25649. */
  25650. double getSampleRate() const throw() { return currentSampleRate; }
  25651. /** Resets the state of this voice after a sound has finished playing.
  25652. The subclass must call this when it finishes playing a note and becomes available
  25653. to play new ones.
  25654. It must either call it in the stopNote() method, or if the voice is tailing off,
  25655. then it should call it later during the renderNextBlock method, as soon as it
  25656. finishes its tail-off.
  25657. It can also be called at any time during the render callback if the sound happens
  25658. to have finished, e.g. if it's playing a sample and the sample finishes.
  25659. */
  25660. void clearCurrentNote();
  25661. private:
  25662. friend class Synthesiser;
  25663. double currentSampleRate;
  25664. int currentlyPlayingNote;
  25665. uint32 noteOnTime;
  25666. SynthesiserSound::Ptr currentlyPlayingSound;
  25667. };
  25668. /**
  25669. Base class for a musical device that can play sounds.
  25670. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25671. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25672. which can play back one of these sounds.
  25673. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25674. set of sounds, and a set of voices it can use to play them. If you only give it
  25675. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25676. have available.
  25677. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25678. events that go in will be scanned for note on/off messages, and these are used to
  25679. start and stop the voices playing the appropriate sounds.
  25680. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25681. noteOff() and other controller methods.
  25682. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25683. what the target playback rate is. This value is passed on to the voices so that
  25684. they can pitch their output correctly.
  25685. */
  25686. class JUCE_API Synthesiser
  25687. {
  25688. public:
  25689. /** Creates a new synthesiser.
  25690. You'll need to add some sounds and voices before it'll make any sound..
  25691. */
  25692. Synthesiser();
  25693. /** Destructor. */
  25694. virtual ~Synthesiser();
  25695. /** Deletes all voices. */
  25696. void clearVoices();
  25697. /** Returns the number of voices that have been added. */
  25698. int getNumVoices() const throw() { return voices.size(); }
  25699. /** Returns one of the voices that have been added. */
  25700. SynthesiserVoice* getVoice (const int index) const throw();
  25701. /** Adds a new voice to the synth.
  25702. All the voices should be the same class of object and are treated equally.
  25703. The object passed in will be managed by the synthesiser, which will delete
  25704. it later on when no longer needed. The caller should not retain a pointer to the
  25705. voice.
  25706. */
  25707. void addVoice (SynthesiserVoice* const newVoice);
  25708. /** Deletes one of the voices. */
  25709. void removeVoice (const int index);
  25710. /** Deletes all sounds. */
  25711. void clearSounds();
  25712. /** Returns the number of sounds that have been added to the synth. */
  25713. int getNumSounds() const throw() { return sounds.size(); }
  25714. /** Returns one of the sounds. */
  25715. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25716. /** Adds a new sound to the synthesiser.
  25717. The object passed in is reference counted, so will be deleted when it is removed
  25718. from the synthesiser, and when no voices are still using it.
  25719. */
  25720. void addSound (const SynthesiserSound::Ptr& newSound);
  25721. /** Removes and deletes one of the sounds. */
  25722. void removeSound (const int index);
  25723. /** If set to true, then the synth will try to take over an existing voice if
  25724. it runs out and needs to play another note.
  25725. The value of this boolean is passed into findFreeVoice(), so the result will
  25726. depend on the implementation of this method.
  25727. */
  25728. void setNoteStealingEnabled (const bool shouldStealNotes);
  25729. /** Returns true if note-stealing is enabled.
  25730. @see setNoteStealingEnabled
  25731. */
  25732. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25733. /** Triggers a note-on event.
  25734. The default method here will find all the sounds that want to be triggered by
  25735. this note/channel. For each sound, it'll try to find a free voice, and use the
  25736. voice to start playing the sound.
  25737. Subclasses might want to override this if they need a more complex algorithm.
  25738. This method will be called automatically according to the midi data passed into
  25739. renderNextBlock(), but may be called explicitly too.
  25740. */
  25741. virtual void noteOn (const int midiChannel,
  25742. const int midiNoteNumber,
  25743. const float velocity);
  25744. /** Triggers a note-off event.
  25745. This will turn off any voices that are playing a sound for the given note/channel.
  25746. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25747. (if they can do). If this is false, the notes will all be cut off immediately.
  25748. This method will be called automatically according to the midi data passed into
  25749. renderNextBlock(), but may be called explicitly too.
  25750. */
  25751. virtual void noteOff (const int midiChannel,
  25752. const int midiNoteNumber,
  25753. const bool allowTailOff);
  25754. /** Turns off all notes.
  25755. This will turn off any voices that are playing a sound on the given midi channel.
  25756. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25757. which channel they're playing.
  25758. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25759. (if they can do). If this is false, the notes will all be cut off immediately.
  25760. This method will be called automatically according to the midi data passed into
  25761. renderNextBlock(), but may be called explicitly too.
  25762. */
  25763. virtual void allNotesOff (const int midiChannel,
  25764. const bool allowTailOff);
  25765. /** Sends a pitch-wheel message.
  25766. This will send a pitch-wheel message to any voices that are playing sounds on
  25767. the given midi channel.
  25768. This method will be called automatically according to the midi data passed into
  25769. renderNextBlock(), but may be called explicitly too.
  25770. @param midiChannel the midi channel for the event
  25771. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25772. */
  25773. virtual void handlePitchWheel (const int midiChannel,
  25774. const int wheelValue);
  25775. /** Sends a midi controller message.
  25776. This will send a midi controller message to any voices that are playing sounds on
  25777. the given midi channel.
  25778. This method will be called automatically according to the midi data passed into
  25779. renderNextBlock(), but may be called explicitly too.
  25780. @param midiChannel the midi channel for the event
  25781. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  25782. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  25783. */
  25784. virtual void handleController (const int midiChannel,
  25785. const int controllerNumber,
  25786. const int controllerValue);
  25787. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  25788. render.
  25789. This value is propagated to the voices so that they can use it to render the correct
  25790. pitches.
  25791. */
  25792. void setCurrentPlaybackSampleRate (const double sampleRate);
  25793. /** Creates the next block of audio output.
  25794. This will process the next numSamples of data from all the voices, and add that output
  25795. to the audio block supplied, starting from the offset specified. Note that the
  25796. data will be added to the current contents of the buffer, so you should clear it
  25797. before calling this method if necessary.
  25798. The midi events in the inputMidi buffer are parsed for note and controller events,
  25799. and these are used to trigger the voices. Note that the startSample offset applies
  25800. both to the audio output buffer and the midi input buffer, so any midi events
  25801. with timestamps outside the specified region will be ignored.
  25802. */
  25803. void renderNextBlock (AudioSampleBuffer& outputAudio,
  25804. const MidiBuffer& inputMidi,
  25805. int startSample,
  25806. int numSamples);
  25807. juce_UseDebuggingNewOperator
  25808. protected:
  25809. /** This is used to control access to the rendering callback and the note trigger methods. */
  25810. CriticalSection lock;
  25811. OwnedArray <SynthesiserVoice> voices;
  25812. ReferenceCountedArray <SynthesiserSound> sounds;
  25813. /** The last pitch-wheel values for each midi channel. */
  25814. int lastPitchWheelValues [16];
  25815. /** Searches through the voices to find one that's not currently playing, and which
  25816. can play the given sound.
  25817. Returns 0 if all voices are busy and stealing isn't enabled.
  25818. This can be overridden to implement custom voice-stealing algorithms.
  25819. */
  25820. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  25821. const bool stealIfNoneAvailable) const;
  25822. /** Starts a specified voice playing a particular sound.
  25823. You'll probably never need to call this, it's used internally by noteOn(), but
  25824. may be needed by subclasses for custom behaviours.
  25825. */
  25826. void startVoice (SynthesiserVoice* const voice,
  25827. SynthesiserSound* const sound,
  25828. const int midiChannel,
  25829. const int midiNoteNumber,
  25830. const float velocity);
  25831. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  25832. int findFreeVoice (const bool) const { return 0; }
  25833. private:
  25834. double sampleRate;
  25835. uint32 lastNoteOnCounter;
  25836. bool shouldStealNotes;
  25837. Synthesiser (const Synthesiser&);
  25838. const Synthesiser& operator= (const Synthesiser&);
  25839. };
  25840. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  25841. /********* End of inlined file: juce_Synthesiser.h *********/
  25842. /**
  25843. A subclass of SynthesiserSound that represents a sampled audio clip.
  25844. This is a pretty basic sampler, and just attempts to load the whole audio stream
  25845. into memory.
  25846. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25847. give it some SampledSound objects to play.
  25848. @see SamplerVoice, Synthesiser, SynthesiserSound
  25849. */
  25850. class JUCE_API SamplerSound : public SynthesiserSound
  25851. {
  25852. public:
  25853. /** Creates a sampled sound from an audio reader.
  25854. This will attempt to load the audio from the source into memory and store
  25855. it in this object.
  25856. @param name a name for the sample
  25857. @param source the audio to load. This object can be safely deleted by the
  25858. caller after this constructor returns
  25859. @param midiNotes the set of midi keys that this sound should be played on. This
  25860. is used by the SynthesiserSound::appliesToNote() method
  25861. @param midiNoteForNormalPitch the midi note at which the sample should be played
  25862. with its natural rate. All other notes will be pitched
  25863. up or down relative to this one
  25864. @param attackTimeSecs the attack (fade-in) time, in seconds
  25865. @param releaseTimeSecs the decay (fade-out) time, in seconds
  25866. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  25867. source, in seconds
  25868. */
  25869. SamplerSound (const String& name,
  25870. AudioFormatReader& source,
  25871. const BitArray& midiNotes,
  25872. const int midiNoteForNormalPitch,
  25873. const double attackTimeSecs,
  25874. const double releaseTimeSecs,
  25875. const double maxSampleLengthSeconds);
  25876. /** Destructor. */
  25877. ~SamplerSound();
  25878. /** Returns the sample's name */
  25879. const String& getName() const throw() { return name; }
  25880. /** Returns the audio sample data.
  25881. This could be 0 if there was a problem loading it.
  25882. */
  25883. AudioSampleBuffer* getAudioData() const throw() { return data; }
  25884. bool appliesToNote (const int midiNoteNumber);
  25885. bool appliesToChannel (const int midiChannel);
  25886. juce_UseDebuggingNewOperator
  25887. private:
  25888. friend class SamplerVoice;
  25889. String name;
  25890. AudioSampleBuffer* data;
  25891. double sourceSampleRate;
  25892. BitArray midiNotes;
  25893. int length, attackSamples, releaseSamples;
  25894. int midiRootNote;
  25895. };
  25896. /**
  25897. A subclass of SynthesiserVoice that can play a SamplerSound.
  25898. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25899. give it some SampledSound objects to play.
  25900. @see SamplerSound, Synthesiser, SynthesiserVoice
  25901. */
  25902. class JUCE_API SamplerVoice : public SynthesiserVoice
  25903. {
  25904. public:
  25905. /** Creates a SamplerVoice.
  25906. */
  25907. SamplerVoice();
  25908. /** Destructor. */
  25909. ~SamplerVoice();
  25910. bool canPlaySound (SynthesiserSound* sound);
  25911. void startNote (const int midiNoteNumber,
  25912. const float velocity,
  25913. SynthesiserSound* sound,
  25914. const int currentPitchWheelPosition);
  25915. void stopNote (const bool allowTailOff);
  25916. void pitchWheelMoved (const int newValue);
  25917. void controllerMoved (const int controllerNumber,
  25918. const int newValue);
  25919. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  25920. juce_UseDebuggingNewOperator
  25921. private:
  25922. double pitchRatio;
  25923. double sourceSamplePosition;
  25924. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  25925. bool isInAttack, isInRelease;
  25926. };
  25927. #endif // __JUCE_SAMPLER_JUCEHEADER__
  25928. /********* End of inlined file: juce_Sampler.h *********/
  25929. #endif
  25930. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25931. #endif
  25932. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25933. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  25934. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25935. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25936. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  25937. /**
  25938. Implements a plugin format manager for AudioUnits.
  25939. */
  25940. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  25941. {
  25942. public:
  25943. AudioUnitPluginFormat();
  25944. ~AudioUnitPluginFormat();
  25945. const String getName() const { return "AudioUnit"; }
  25946. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  25947. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25948. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  25949. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  25950. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  25951. bool doesPluginStillExist (const PluginDescription& desc);
  25952. const FileSearchPath getDefaultLocationsToSearch();
  25953. juce_UseDebuggingNewOperator
  25954. private:
  25955. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  25956. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  25957. };
  25958. #endif
  25959. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  25960. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  25961. #endif
  25962. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25963. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  25964. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25965. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25966. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  25967. // Sorry, this file is just a placeholder at the moment!...
  25968. /**
  25969. Implements a plugin format manager for DirectX plugins.
  25970. */
  25971. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  25972. {
  25973. public:
  25974. DirectXPluginFormat();
  25975. ~DirectXPluginFormat();
  25976. const String getName() const { return "DirectX"; }
  25977. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  25978. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  25979. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  25980. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  25981. const FileSearchPath getDefaultLocationsToSearch();
  25982. juce_UseDebuggingNewOperator
  25983. private:
  25984. DirectXPluginFormat (const DirectXPluginFormat&);
  25985. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  25986. };
  25987. #endif
  25988. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  25989. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  25990. #endif
  25991. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25992. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  25993. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25994. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  25995. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  25996. // Sorry, this file is just a placeholder at the moment!...
  25997. /**
  25998. Implements a plugin format manager for DirectX plugins.
  25999. */
  26000. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26001. {
  26002. public:
  26003. LADSPAPluginFormat();
  26004. ~LADSPAPluginFormat();
  26005. const String getName() const { return "LADSPA"; }
  26006. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26007. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26008. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26009. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26010. const FileSearchPath getDefaultLocationsToSearch();
  26011. juce_UseDebuggingNewOperator
  26012. private:
  26013. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26014. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26015. };
  26016. #endif
  26017. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26018. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26019. #endif
  26020. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26021. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26022. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26023. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26024. #if JUCE_PLUGINHOST_VST
  26025. /**
  26026. Implements a plugin format manager for VSTs.
  26027. */
  26028. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26029. {
  26030. public:
  26031. VSTPluginFormat();
  26032. ~VSTPluginFormat();
  26033. const String getName() const { return "VST"; }
  26034. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26035. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26036. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26037. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26038. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26039. bool doesPluginStillExist (const PluginDescription& desc);
  26040. const FileSearchPath getDefaultLocationsToSearch();
  26041. juce_UseDebuggingNewOperator
  26042. private:
  26043. VSTPluginFormat (const VSTPluginFormat&);
  26044. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26045. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26046. };
  26047. #endif
  26048. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26049. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26050. #endif
  26051. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26052. #endif
  26053. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26054. #endif
  26055. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26056. #endif
  26057. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26058. #endif
  26059. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26060. #endif
  26061. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26062. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26063. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26064. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26065. /**
  26066. Scans a directory for plugins, and adds them to a KnownPluginList.
  26067. To use one of these, create it and call scanNextFile() repeatedly, until
  26068. it returns false.
  26069. */
  26070. class JUCE_API PluginDirectoryScanner
  26071. {
  26072. public:
  26073. /**
  26074. Creates a scanner.
  26075. @param listToAddResultsTo this will get the new types added to it.
  26076. @param formatToLookFor this is the type of format that you want to look for
  26077. @param directoriesToSearch the path to search
  26078. @param searchRecursively true to search recursively
  26079. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26080. be used as a file to store the names of any plugins
  26081. that crash during initialisation. If there are
  26082. any plugins listed in it, then these will always
  26083. be scanned after all other possible files have
  26084. been tried - in this way, even if there's a few
  26085. dodgy plugins in your path, then a couple of rescans
  26086. will still manage to find all the proper plugins.
  26087. It's probably best to choose a file in the user's
  26088. application data directory (alongside your app's
  26089. settings file) for this. The file format it uses
  26090. is just a list of filenames of the modules that
  26091. failed.
  26092. */
  26093. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26094. AudioPluginFormat& formatToLookFor,
  26095. FileSearchPath directoriesToSearch,
  26096. const bool searchRecursively,
  26097. const File& deadMansPedalFile);
  26098. /** Destructor. */
  26099. ~PluginDirectoryScanner();
  26100. /** Tries the next likely-looking file.
  26101. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26102. re-tested if it's not already in the list, or if the file's modification
  26103. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26104. false, the file will always be reloaded and tested.
  26105. Returns false when there are no more files to try.
  26106. */
  26107. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26108. /** Returns the description of the plugin that will be scanned during the next
  26109. call to scanNextFile().
  26110. This is handy if you want to show the user which file is currently getting
  26111. scanned.
  26112. */
  26113. const String getNextPluginFileThatWillBeScanned() const throw();
  26114. /** Returns the estimated progress, between 0 and 1.
  26115. */
  26116. float getProgress() const { return progress; }
  26117. /** This returns a list of all the filenames of things that looked like being
  26118. a plugin file, but which failed to open for some reason.
  26119. */
  26120. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26121. juce_UseDebuggingNewOperator
  26122. private:
  26123. KnownPluginList& list;
  26124. AudioPluginFormat& format;
  26125. StringArray filesOrIdentifiersToScan;
  26126. File deadMansPedalFile;
  26127. StringArray failedFiles;
  26128. int nextIndex;
  26129. float progress;
  26130. const StringArray getDeadMansPedalFile() throw();
  26131. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26132. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26133. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26134. };
  26135. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26136. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26137. #endif
  26138. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26139. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26140. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26141. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26142. /********* Start of inlined file: juce_ListBox.h *********/
  26143. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26144. #define __JUCE_LISTBOX_JUCEHEADER__
  26145. class ListViewport;
  26146. /**
  26147. A subclass of this is used to drive a ListBox.
  26148. @see ListBox
  26149. */
  26150. class JUCE_API ListBoxModel
  26151. {
  26152. public:
  26153. /** Destructor. */
  26154. virtual ~ListBoxModel() {}
  26155. /** This has to return the number of items in the list.
  26156. @see ListBox::getNumRows()
  26157. */
  26158. virtual int getNumRows() = 0;
  26159. /** This method must be implemented to draw a row of the list.
  26160. */
  26161. virtual void paintListBoxItem (int rowNumber,
  26162. Graphics& g,
  26163. int width, int height,
  26164. bool rowIsSelected) = 0;
  26165. /** This is used to create or update a custom component to go in a row of the list.
  26166. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26167. and handle mouse clicks with listBoxItemClicked().
  26168. This method will be called whenever a custom component might need to be updated - e.g.
  26169. when the table is changed, or TableListBox::updateContent() is called.
  26170. If you don't need a custom component for the specified row, then return 0.
  26171. If you do want a custom component, and the existingComponentToUpdate is null, then
  26172. this method must create a suitable new component and return it.
  26173. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26174. by this method. In this case, the method must either update it to make sure it's correctly representing
  26175. the given row (which may be different from the one that the component was created for), or it can
  26176. delete this component and return a new one.
  26177. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26178. */
  26179. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26180. Component* existingComponentToUpdate);
  26181. /** This can be overridden to react to the user clicking on a row.
  26182. @see listBoxItemDoubleClicked
  26183. */
  26184. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26185. /** This can be overridden to react to the user double-clicking on a row.
  26186. @see listBoxItemClicked
  26187. */
  26188. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26189. /** This can be overridden to react to the user double-clicking on a part of the list where
  26190. there are no rows.
  26191. @see listBoxItemClicked
  26192. */
  26193. virtual void backgroundClicked();
  26194. /** Override this to be informed when rows are selected or deselected.
  26195. This will be called whenever a row is selected or deselected. If a range of
  26196. rows is selected all at once, this will just be called once for that event.
  26197. @param lastRowSelected the last row that the user selected. If no
  26198. rows are currently selected, this may be -1.
  26199. */
  26200. virtual void selectedRowsChanged (int lastRowSelected);
  26201. /** Override this to be informed when the delete key is pressed.
  26202. If no rows are selected when they press the key, this won't be called.
  26203. @param lastRowSelected the last row that had been selected when they pressed the
  26204. key - if there are multiple selections, this might not be
  26205. very useful
  26206. */
  26207. virtual void deleteKeyPressed (int lastRowSelected);
  26208. /** Override this to be informed when the return key is pressed.
  26209. If no rows are selected when they press the key, this won't be called.
  26210. @param lastRowSelected the last row that had been selected when they pressed the
  26211. key - if there are multiple selections, this might not be
  26212. very useful
  26213. */
  26214. virtual void returnKeyPressed (int lastRowSelected);
  26215. /** Override this to be informed when the list is scrolled.
  26216. This might be caused by the user moving the scrollbar, or by programmatic changes
  26217. to the list position.
  26218. */
  26219. virtual void listWasScrolled();
  26220. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26221. If this returns a non-empty name then when the user drags a row, the listbox will
  26222. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26223. a drag-and-drop operation, using this string as the source description, with the listbox
  26224. itself as the source component.
  26225. @see DragAndDropContainer::startDragging
  26226. */
  26227. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26228. };
  26229. /**
  26230. A list of items that can be scrolled vertically.
  26231. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26232. either paint each row of the list and respond to events via callbacks, or for
  26233. more specialised tasks, it can supply a custom component to fill each row.
  26234. @see ComboBox, TableListBox
  26235. */
  26236. class JUCE_API ListBox : public Component,
  26237. public SettableTooltipClient
  26238. {
  26239. public:
  26240. /** Creates a ListBox.
  26241. The model pointer passed-in can be null, in which case you can set it later
  26242. with setModel().
  26243. */
  26244. ListBox (const String& componentName,
  26245. ListBoxModel* const model);
  26246. /** Destructor. */
  26247. ~ListBox();
  26248. /** Changes the current data model to display. */
  26249. void setModel (ListBoxModel* const newModel);
  26250. /** Returns the current list model. */
  26251. ListBoxModel* getModel() const throw() { return model; }
  26252. /** Causes the list to refresh its content.
  26253. Call this when the number of rows in the list changes, or if you want it
  26254. to call refreshComponentForRow() on all the row components.
  26255. Be careful not to call it from a different thread, though, as it's not
  26256. thread-safe.
  26257. */
  26258. void updateContent();
  26259. /** Turns on multiple-selection of rows.
  26260. By default this is disabled.
  26261. When your row component gets clicked you'll need to call the
  26262. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26263. clicked and to get it to do the appropriate selection based on whether
  26264. the ctrl/shift keys are held down.
  26265. */
  26266. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26267. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26268. This function is here primarily for the ComboBox class to use, but might be
  26269. useful for some other purpose too.
  26270. */
  26271. void setMouseMoveSelectsRows (bool shouldSelect);
  26272. /** Selects a row.
  26273. If the row is already selected, this won't do anything.
  26274. @param rowNumber the row to select
  26275. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26276. the selected row is off-screen, it'll scroll to make
  26277. sure that row is on-screen
  26278. @param deselectOthersFirst if true and there are multiple selections, these will
  26279. first be deselected before this item is selected
  26280. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26281. deselectAllRows, selectRangeOfRows
  26282. */
  26283. void selectRow (const int rowNumber,
  26284. bool dontScrollToShowThisRow = false,
  26285. bool deselectOthersFirst = true);
  26286. /** Selects a set of rows.
  26287. This will add these rows to the current selection, so you might need to
  26288. clear the current selection first with deselectAllRows()
  26289. @param firstRow the first row to select (inclusive)
  26290. @param lastRow the last row to select (inclusive)
  26291. */
  26292. void selectRangeOfRows (int firstRow,
  26293. int lastRow);
  26294. /** Deselects a row.
  26295. If it's not currently selected, this will do nothing.
  26296. @see selectRow, deselectAllRows
  26297. */
  26298. void deselectRow (const int rowNumber);
  26299. /** Deselects any currently selected rows.
  26300. @see deselectRow
  26301. */
  26302. void deselectAllRows();
  26303. /** Selects or deselects a row.
  26304. If the row's currently selected, this deselects it, and vice-versa.
  26305. */
  26306. void flipRowSelection (const int rowNumber);
  26307. /** Returns a sparse set indicating the rows that are currently selected.
  26308. @see setSelectedRows
  26309. */
  26310. const SparseSet<int> getSelectedRows() const;
  26311. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26312. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26313. method will be called. If it's false, no notification will be sent to the model.
  26314. @see getSelectedRows
  26315. */
  26316. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26317. const bool sendNotificationEventToModel = true);
  26318. /** Checks whether a row is selected.
  26319. */
  26320. bool isRowSelected (const int rowNumber) const;
  26321. /** Returns the number of rows that are currently selected.
  26322. @see getSelectedRow, isRowSelected, getLastRowSelected
  26323. */
  26324. int getNumSelectedRows() const;
  26325. /** Returns the row number of a selected row.
  26326. This will return the row number of the Nth selected row. The row numbers returned will
  26327. be sorted in order from low to high.
  26328. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26329. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26330. selected
  26331. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26332. */
  26333. int getSelectedRow (const int index = 0) const;
  26334. /** Returns the last row that the user selected.
  26335. This isn't the same as the highest row number that is currently selected - if the user
  26336. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26337. If nothing is selected, it will return -1.
  26338. */
  26339. int getLastRowSelected() const;
  26340. /** Multiply-selects rows based on the modifier keys.
  26341. If no modifier keys are down, this will select the given row and
  26342. deselect any others.
  26343. If the ctrl (or command on the Mac) key is down, it'll flip the
  26344. state of the selected row.
  26345. If the shift key is down, it'll select up to the given row from the
  26346. last row selected.
  26347. @see selectRow
  26348. */
  26349. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26350. const ModifierKeys& modifiers);
  26351. /** Scrolls the list to a particular position.
  26352. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26353. 1.0 scrolls to the bottom.
  26354. If the total number of rows all fit onto the screen at once, then this
  26355. method won't do anything.
  26356. @see getVerticalPosition
  26357. */
  26358. void setVerticalPosition (const double newProportion);
  26359. /** Returns the current vertical position as a proportion of the total.
  26360. This can be used in conjunction with setVerticalPosition() to save and restore
  26361. the list's position. It returns a value in the range 0 to 1.
  26362. @see setVerticalPosition
  26363. */
  26364. double getVerticalPosition() const;
  26365. /** Scrolls if necessary to make sure that a particular row is visible.
  26366. */
  26367. void scrollToEnsureRowIsOnscreen (const int row);
  26368. /** Returns a pointer to the scrollbar.
  26369. (Unlikely to be useful for most people).
  26370. */
  26371. ScrollBar* getVerticalScrollBar() const throw();
  26372. /** Returns a pointer to the scrollbar.
  26373. (Unlikely to be useful for most people).
  26374. */
  26375. ScrollBar* getHorizontalScrollBar() const throw();
  26376. /** Finds the row index that contains a given x,y position.
  26377. The position is relative to the ListBox's top-left.
  26378. If no row exists at this position, the method will return -1.
  26379. @see getComponentForRowNumber
  26380. */
  26381. int getRowContainingPosition (const int x, const int y) const throw();
  26382. /** Finds a row index that would be the most suitable place to insert a new
  26383. item for a given position.
  26384. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26385. because it lets you easily choose the best position to insert the item that
  26386. they drop, based on where they drop it.
  26387. If the position is out of range, this will return -1. If the position is
  26388. beyond the end of the list, it will return getNumRows() to indicate the end
  26389. of the list.
  26390. @see getComponentForRowNumber
  26391. */
  26392. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26393. /** Returns the position of one of the rows, relative to the top-left of
  26394. the listbox.
  26395. This may be off-screen, and the range of the row number that is passed-in is
  26396. not checked to see if it's a valid row.
  26397. */
  26398. const Rectangle getRowPosition (const int rowNumber,
  26399. const bool relativeToComponentTopLeft) const throw();
  26400. /** Finds the row component for a given row in the list.
  26401. The component returned will have been created using createRowComponent().
  26402. If the component for this row is off-screen or if the row is out-of-range,
  26403. this will return 0.
  26404. @see getRowContainingPosition
  26405. */
  26406. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26407. /** Returns the row number that the given component represents.
  26408. If the component isn't one of the list's rows, this will return -1.
  26409. */
  26410. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26411. /** Returns the width of a row (which may be less than the width of this component
  26412. if there's a scrollbar).
  26413. */
  26414. int getVisibleRowWidth() const throw();
  26415. /** Sets the height of each row in the list.
  26416. The default height is 22 pixels.
  26417. @see getRowHeight
  26418. */
  26419. void setRowHeight (const int newHeight);
  26420. /** Returns the height of a row in the list.
  26421. @see setRowHeight
  26422. */
  26423. int getRowHeight() const throw() { return rowHeight; }
  26424. /** Returns the number of rows actually visible.
  26425. This is the number of whole rows which will fit on-screen, so the value might
  26426. be more than the actual number of rows in the list.
  26427. */
  26428. int getNumRowsOnScreen() const throw();
  26429. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26430. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26431. methods.
  26432. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26433. */
  26434. enum ColourIds
  26435. {
  26436. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26437. Make this transparent if you don't want the background to be filled. */
  26438. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26439. Make this transparent to not have an outline. */
  26440. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26441. };
  26442. /** Sets the thickness of a border that will be drawn around the box.
  26443. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26444. @see outlineColourId
  26445. */
  26446. void setOutlineThickness (const int outlineThickness);
  26447. /** Returns the thickness of outline that will be drawn around the listbox.
  26448. @see setOutlineColour
  26449. */
  26450. int getOutlineThickness() const throw() { return outlineThickness; }
  26451. /** Sets a component that the list should use as a header.
  26452. This will position the given component at the top of the list, maintaining the
  26453. height of the component passed-in, but rescaling it horizontally to match the
  26454. width of the items in the listbox.
  26455. The component will be deleted when setHeaderComponent() is called with a
  26456. different component, or when the listbox is deleted.
  26457. */
  26458. void setHeaderComponent (Component* const newHeaderComponent);
  26459. /** Changes the width of the rows in the list.
  26460. This can be used to make the list's row components wider than the list itself - the
  26461. width of the rows will be either the width of the list or this value, whichever is
  26462. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26463. appear.
  26464. The default value for this is 0, which means that the rows will always
  26465. be the same width as the list.
  26466. */
  26467. void setMinimumContentWidth (const int newMinimumWidth);
  26468. /** Returns the space currently available for the row items, taking into account
  26469. borders, scrollbars, etc.
  26470. */
  26471. int getVisibleContentWidth() const throw();
  26472. /** Repaints one of the rows.
  26473. This is a lightweight alternative to calling updateContent, and just causes a
  26474. repaint of the row's area.
  26475. */
  26476. void repaintRow (const int rowNumber) throw();
  26477. /** This fairly obscure method creates an image that just shows the currently
  26478. selected row components.
  26479. It's a handy method for doing drag-and-drop, as it can be passed to the
  26480. DragAndDropContainer for use as the drag image.
  26481. Note that it will make the row components temporarily invisible, so if you're
  26482. using custom components this could affect them if they're sensitive to that
  26483. sort of thing.
  26484. @see Component::createComponentSnapshot
  26485. */
  26486. Image* createSnapshotOfSelectedRows();
  26487. /** Returns the viewport that this ListBox uses.
  26488. You may need to use this to change parameters such as whether scrollbars
  26489. are shown, etc.
  26490. */
  26491. Viewport* getViewport() const throw();
  26492. /** @internal */
  26493. bool keyPressed (const KeyPress& key);
  26494. /** @internal */
  26495. bool keyStateChanged();
  26496. /** @internal */
  26497. void paint (Graphics& g);
  26498. /** @internal */
  26499. void paintOverChildren (Graphics& g);
  26500. /** @internal */
  26501. void resized();
  26502. /** @internal */
  26503. void visibilityChanged();
  26504. /** @internal */
  26505. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26506. /** @internal */
  26507. void mouseMove (const MouseEvent&);
  26508. /** @internal */
  26509. void mouseExit (const MouseEvent&);
  26510. /** @internal */
  26511. void mouseUp (const MouseEvent&);
  26512. /** @internal */
  26513. void colourChanged();
  26514. juce_UseDebuggingNewOperator
  26515. private:
  26516. friend class ListViewport;
  26517. friend class TableListBox;
  26518. ListBoxModel* model;
  26519. ListViewport* viewport;
  26520. Component* headerComponent;
  26521. int totalItems, rowHeight, minimumRowWidth;
  26522. int outlineThickness;
  26523. int lastMouseX, lastMouseY, lastRowSelected;
  26524. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26525. SparseSet <int> selected;
  26526. void selectRowInternal (const int rowNumber,
  26527. bool dontScrollToShowThisRow,
  26528. bool deselectOthersFirst,
  26529. bool isMouseClick);
  26530. ListBox (const ListBox&);
  26531. const ListBox& operator= (const ListBox&);
  26532. };
  26533. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26534. /********* End of inlined file: juce_ListBox.h *********/
  26535. /********* Start of inlined file: juce_TextButton.h *********/
  26536. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26537. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26538. /**
  26539. A button that uses the standard lozenge-shaped background with a line of
  26540. text on it.
  26541. @see Button, DrawableButton
  26542. */
  26543. class JUCE_API TextButton : public Button
  26544. {
  26545. public:
  26546. /** Creates a TextButton.
  26547. @param buttonName the text to put in the button (the component's name is also
  26548. initially set to this string, but these can be changed later
  26549. using the setName() and setButtonText() methods)
  26550. @param toolTip an optional string to use as a toolip
  26551. @see Button
  26552. */
  26553. TextButton (const String& buttonName,
  26554. const String& toolTip = String::empty);
  26555. /** Destructor. */
  26556. ~TextButton();
  26557. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26558. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26559. methods.
  26560. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26561. */
  26562. enum ColourIds
  26563. {
  26564. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26565. 'off'). The look-and-feel class might re-interpret this to add
  26566. effects, etc. */
  26567. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26568. 'on'). The look-and-feel class might re-interpret this to add
  26569. effects, etc. */
  26570. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26571. };
  26572. /** Resizes the button to fit neatly around its current text.
  26573. If newHeight is >= 0, the button's height will be changed to this
  26574. value. If it's less than zero, its height will be unaffected.
  26575. */
  26576. void changeWidthToFitText (const int newHeight = -1);
  26577. /** This can be overridden to use different fonts than the default one.
  26578. Note that you'll need to set the font's size appropriately, too.
  26579. */
  26580. virtual const Font getFont();
  26581. juce_UseDebuggingNewOperator
  26582. protected:
  26583. /** @internal */
  26584. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26585. /** @internal */
  26586. void colourChanged();
  26587. private:
  26588. TextButton (const TextButton&);
  26589. const TextButton& operator= (const TextButton&);
  26590. };
  26591. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26592. /********* End of inlined file: juce_TextButton.h *********/
  26593. /**
  26594. A component displaying a list of plugins, with options to scan for them,
  26595. add, remove and sort them.
  26596. */
  26597. class JUCE_API PluginListComponent : public Component,
  26598. public ListBoxModel,
  26599. public ChangeListener,
  26600. public ButtonListener,
  26601. public Timer
  26602. {
  26603. public:
  26604. /**
  26605. Creates the list component.
  26606. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26607. The properties file, if supplied, is used to store the user's last search paths.
  26608. */
  26609. PluginListComponent (KnownPluginList& listToRepresent,
  26610. const File& deadMansPedalFile,
  26611. PropertiesFile* const propertiesToUse);
  26612. /** Destructor. */
  26613. ~PluginListComponent();
  26614. /** @internal */
  26615. void resized();
  26616. /** @internal */
  26617. bool isInterestedInFileDrag (const StringArray& files);
  26618. /** @internal */
  26619. void filesDropped (const StringArray& files, int, int);
  26620. /** @internal */
  26621. int getNumRows();
  26622. /** @internal */
  26623. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26624. /** @internal */
  26625. void deleteKeyPressed (int lastRowSelected);
  26626. /** @internal */
  26627. void buttonClicked (Button* b);
  26628. /** @internal */
  26629. void changeListenerCallback (void*);
  26630. /** @internal */
  26631. void timerCallback();
  26632. juce_UseDebuggingNewOperator
  26633. private:
  26634. KnownPluginList& list;
  26635. File deadMansPedalFile;
  26636. ListBox* listBox;
  26637. TextButton* optionsButton;
  26638. PropertiesFile* propertiesToUse;
  26639. int typeToScan;
  26640. void scanFor (AudioPluginFormat* format);
  26641. PluginListComponent (const PluginListComponent&);
  26642. const PluginListComponent& operator= (const PluginListComponent&);
  26643. };
  26644. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26645. /********* End of inlined file: juce_PluginListComponent.h *********/
  26646. #endif
  26647. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26648. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  26649. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26650. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26651. /********* Start of inlined file: juce_AudioFormat.h *********/
  26652. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26653. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26654. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  26655. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26656. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26657. /**
  26658. Writes samples to an audio file stream.
  26659. A subclass that writes a specific type of audio format will be created by
  26660. an AudioFormat object.
  26661. After creating one of these with the AudioFormat::createWriterFor() method
  26662. you can call its write() method to store the samples, and then delete it.
  26663. @see AudioFormat, AudioFormatReader
  26664. */
  26665. class JUCE_API AudioFormatWriter
  26666. {
  26667. protected:
  26668. /** Creates an AudioFormatWriter object.
  26669. @param destStream the stream to write to - this will be deleted
  26670. by this object when it is no longer needed
  26671. @param formatName the description that will be returned by the getFormatName()
  26672. method
  26673. @param sampleRate the sample rate to use - the base class just stores
  26674. this value, it doesn't do anything with it
  26675. @param numberOfChannels the number of channels to write - the base class just stores
  26676. this value, it doesn't do anything with it
  26677. @param bitsPerSample the bit depth of the stream - the base class just stores
  26678. this value, it doesn't do anything with it
  26679. */
  26680. AudioFormatWriter (OutputStream* const destStream,
  26681. const String& formatName,
  26682. const double sampleRate,
  26683. const unsigned int numberOfChannels,
  26684. const unsigned int bitsPerSample);
  26685. public:
  26686. /** Destructor. */
  26687. virtual ~AudioFormatWriter();
  26688. /** Returns a description of what type of format this is.
  26689. E.g. "AIFF file"
  26690. */
  26691. const String getFormatName() const throw() { return formatName; }
  26692. /** Writes a set of samples to the audio stream.
  26693. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  26694. can use AudioSampleBuffer::writeToAudioWriter().
  26695. @param samplesToWrite an array of arrays containing the sample data for
  26696. each channel to write. This is a zero-terminated
  26697. array of arrays, and can contain a different number
  26698. of channels than the actual stream uses, and the
  26699. writer should do its best to cope with this.
  26700. If the format is fixed-point, each channel will be formatted
  26701. as an array of signed integers using the full 32-bit
  26702. range -0x80000000 to 0x7fffffff, regardless of the source's
  26703. bit-depth. If it is a floating-point format, you should treat
  26704. the arrays as arrays of floats, and just cast it to an (int**)
  26705. to pass it into the method.
  26706. @param numSamples the number of samples to write
  26707. */
  26708. virtual bool write (const int** samplesToWrite,
  26709. int numSamples) = 0;
  26710. /** Reads a section of samples from an AudioFormatReader, and writes these to
  26711. the output.
  26712. This will take care of any floating-point conversion that's required to convert
  26713. between the two formats. It won't deal with sample-rate conversion, though.
  26714. @returns false if it can't read or write properly during the operation
  26715. */
  26716. bool writeFromAudioReader (AudioFormatReader& reader,
  26717. int64 startSample,
  26718. int numSamplesToRead);
  26719. /** Reads some samples from an AudioSource, and writes these to the output.
  26720. The source must already have been initialised with the AudioSource::prepareToPlay() method
  26721. @param source the source to read from
  26722. @param numSamplesToRead total number of samples to read and write
  26723. @param samplesPerBlock the maximum number of samples to fetch from the source
  26724. @returns false if it can't read or write properly during the operation
  26725. */
  26726. bool writeFromAudioSource (AudioSource& source,
  26727. int numSamplesToRead,
  26728. const int samplesPerBlock = 2048);
  26729. /** Returns the sample rate being used. */
  26730. double getSampleRate() const throw() { return sampleRate; }
  26731. /** Returns the number of channels being written. */
  26732. int getNumChannels() const throw() { return numChannels; }
  26733. /** Returns the bit-depth of the data being written. */
  26734. int getBitsPerSample() const throw() { return bitsPerSample; }
  26735. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  26736. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  26737. juce_UseDebuggingNewOperator
  26738. protected:
  26739. /** The sample rate of the stream. */
  26740. double sampleRate;
  26741. /** The number of channels being written to the stream. */
  26742. unsigned int numChannels;
  26743. /** The bit depth of the file. */
  26744. unsigned int bitsPerSample;
  26745. /** True if it's a floating-point format, false if it's fixed-point. */
  26746. bool usesFloatingPointData;
  26747. /** The output stream for Use by subclasses. */
  26748. OutputStream* output;
  26749. private:
  26750. String formatName;
  26751. };
  26752. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26753. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  26754. /**
  26755. Subclasses of AudioFormat are used to read and write different audio
  26756. file formats.
  26757. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  26758. */
  26759. class JUCE_API AudioFormat
  26760. {
  26761. public:
  26762. /** Destructor. */
  26763. virtual ~AudioFormat();
  26764. /** Returns the name of this format.
  26765. e.g. "WAV file" or "AIFF file"
  26766. */
  26767. const String& getFormatName() const;
  26768. /** Returns all the file extensions that might apply to a file of this format.
  26769. The first item will be the one that's preferred when creating a new file.
  26770. So for a wav file this might just return ".wav"; for an AIFF file it might
  26771. return two items, ".aif" and ".aiff"
  26772. */
  26773. const StringArray& getFileExtensions() const;
  26774. /** Returns true if this the given file can be read by this format.
  26775. Subclasses shouldn't do too much work here, just check the extension or
  26776. file type. The base class implementation just checks the file's extension
  26777. against one of the ones that was registered in the constructor.
  26778. */
  26779. virtual bool canHandleFile (const File& fileToTest);
  26780. /** Returns a set of sample rates that the format can read and write. */
  26781. virtual const Array <int> getPossibleSampleRates() = 0;
  26782. /** Returns a set of bit depths that the format can read and write. */
  26783. virtual const Array <int> getPossibleBitDepths() = 0;
  26784. /** Returns true if the format can do 2-channel audio. */
  26785. virtual bool canDoStereo() = 0;
  26786. /** Returns true if the format can do 1-channel audio. */
  26787. virtual bool canDoMono() = 0;
  26788. /** Returns true if the format uses compressed data. */
  26789. virtual bool isCompressed();
  26790. /** Returns a list of different qualities that can be used when writing.
  26791. Non-compressed formats will just return an empty array, but for something
  26792. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  26793. When calling createWriterFor(), an index from this array is passed in to
  26794. tell the format which option is required.
  26795. */
  26796. virtual const StringArray getQualityOptions();
  26797. /** Tries to create an object that can read from a stream containing audio
  26798. data in this format.
  26799. The reader object that is returned can be used to read from the stream, and
  26800. should then be deleted by the caller.
  26801. @param sourceStream the stream to read from - the AudioFormatReader object
  26802. that is returned will delete this stream when it no longer
  26803. needs it.
  26804. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  26805. should delete the stream object that was passed-in. (If a valid
  26806. reader is returned, it will always be in charge of deleting the
  26807. stream, so this parameter is ignored)
  26808. @see AudioFormatReader
  26809. */
  26810. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26811. const bool deleteStreamIfOpeningFails) = 0;
  26812. /** Tries to create an object that can write to a stream with this audio format.
  26813. The writer object that is returned can be used to write to the stream, and
  26814. should then be deleted by the caller.
  26815. If the stream can't be created for some reason (e.g. the parameters passed in
  26816. here aren't suitable), this will return 0.
  26817. @param streamToWriteTo the stream that the data will go to - this will be
  26818. deleted by the AudioFormatWriter object when it's no longer
  26819. needed. If no AudioFormatWriter can be created by this method,
  26820. the stream will NOT be deleted, so that the caller can re-use it
  26821. to try to open a different format, etc
  26822. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  26823. returned by getPossibleSampleRates()
  26824. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  26825. the choice will depend on the results of canDoMono() and
  26826. canDoStereo()
  26827. @param bitsPerSample the bits per sample to use - this must be one of the values
  26828. returned by getPossibleBitDepths()
  26829. @param metadataValues a set of metadata values that the writer should try to write
  26830. to the stream. Exactly what these are depends on the format,
  26831. and the subclass doesn't actually have to do anything with
  26832. them if it doesn't want to. Have a look at the specific format
  26833. implementation classes to see possible values that can be
  26834. used
  26835. @param qualityOptionIndex the index of one of compression qualities returned by the
  26836. getQualityOptions() method. If there aren't any quality options
  26837. for this format, just pass 0 in this parameter, as it'll be
  26838. ignored
  26839. @see AudioFormatWriter
  26840. */
  26841. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26842. double sampleRateToUse,
  26843. unsigned int numberOfChannels,
  26844. int bitsPerSample,
  26845. const StringPairArray& metadataValues,
  26846. int qualityOptionIndex) = 0;
  26847. protected:
  26848. /** Creates an AudioFormat object.
  26849. @param formatName this sets the value that will be returned by getFormatName()
  26850. @param fileExtensions a zero-terminated list of file extensions - this is what will
  26851. be returned by getFileExtension()
  26852. */
  26853. AudioFormat (const String& formatName,
  26854. const tchar** const fileExtensions);
  26855. private:
  26856. String formatName;
  26857. StringArray fileExtensions;
  26858. };
  26859. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  26860. /********* End of inlined file: juce_AudioFormat.h *********/
  26861. /**
  26862. Reads and Writes AIFF format audio files.
  26863. @see AudioFormat
  26864. */
  26865. class JUCE_API AiffAudioFormat : public AudioFormat
  26866. {
  26867. public:
  26868. /** Creates an format object. */
  26869. AiffAudioFormat();
  26870. /** Destructor. */
  26871. ~AiffAudioFormat();
  26872. const Array <int> getPossibleSampleRates();
  26873. const Array <int> getPossibleBitDepths();
  26874. bool canDoStereo();
  26875. bool canDoMono();
  26876. #if JUCE_MAC
  26877. bool canHandleFile (const File& fileToTest);
  26878. #endif
  26879. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26880. const bool deleteStreamIfOpeningFails);
  26881. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26882. double sampleRateToUse,
  26883. unsigned int numberOfChannels,
  26884. int bitsPerSample,
  26885. const StringPairArray& metadataValues,
  26886. int qualityOptionIndex);
  26887. juce_UseDebuggingNewOperator
  26888. };
  26889. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26890. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  26891. #endif
  26892. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26893. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  26894. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26895. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26896. /**
  26897. */
  26898. class AudioCDBurner
  26899. {
  26900. public:
  26901. /** Returns a list of available optical drives.
  26902. Use openDevice() to open one of the items from this list.
  26903. */
  26904. static const StringArray findAvailableDevices();
  26905. /** Tries to open one of the optical drives.
  26906. The deviceIndex is an index into the array returned by findAvailableDevices().
  26907. */
  26908. static AudioCDBurner* openDevice (const int deviceIndex);
  26909. /** Destructor. */
  26910. ~AudioCDBurner();
  26911. /** Returns true if there's a writable disk in the drive.
  26912. */
  26913. bool isDiskPresent() const;
  26914. /** Returns the number of free blocks on the disk.
  26915. There are 75 blocks per second, at 44100Hz.
  26916. */
  26917. int getNumAvailableAudioBlocks() const;
  26918. /** Adds a track to be written.
  26919. The source passed-in here will be kept by this object, and it will
  26920. be used and deleted at some point in the future, either during the
  26921. burn() method or when this AudioCDBurner object is deleted. Your caller
  26922. method shouldn't keep a reference to it or use it again after passing
  26923. it in here.
  26924. */
  26925. bool addAudioTrack (AudioSource* source, int numSamples);
  26926. /**
  26927. Return true to cancel the current burn operation
  26928. */
  26929. class BurnProgressListener
  26930. {
  26931. public:
  26932. BurnProgressListener() throw() {}
  26933. virtual ~BurnProgressListener() {}
  26934. /** Called at intervals to report on the progress of the AudioCDBurner.
  26935. To cancel the burn, return true from this.
  26936. */
  26937. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  26938. };
  26939. const String burn (BurnProgressListener* listener,
  26940. const bool ejectDiscAfterwards,
  26941. const bool peformFakeBurnForTesting);
  26942. juce_UseDebuggingNewOperator
  26943. private:
  26944. AudioCDBurner (const int deviceIndex);
  26945. void* internal;
  26946. };
  26947. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26948. /********* End of inlined file: juce_AudioCDBurner.h *********/
  26949. #endif
  26950. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26951. /********* Start of inlined file: juce_AudioCDReader.h *********/
  26952. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  26953. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  26954. #if JUCE_MAC
  26955. #endif
  26956. /**
  26957. A type of AudioFormatReader that reads from an audio CD.
  26958. One of these can be used to read a CD as if it's one big audio stream. Use the
  26959. getPositionOfTrackStart() method to find where the individual tracks are
  26960. within the stream.
  26961. @see AudioFormatReader
  26962. */
  26963. class JUCE_API AudioCDReader : public AudioFormatReader
  26964. {
  26965. public:
  26966. /** Returns a list of names of Audio CDs currently available for reading.
  26967. If there's a CD drive but no CD in it, this might return an empty list, or
  26968. possibly a device that can be opened but which has no tracks, depending
  26969. on the platform.
  26970. @see createReaderForCD
  26971. */
  26972. static const StringArray getAvailableCDNames();
  26973. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  26974. @param index the index of one of the available CDs - use getAvailableCDNames()
  26975. to find out how many there are.
  26976. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  26977. caller will be responsible for deleting the object returned.
  26978. */
  26979. static AudioCDReader* createReaderForCD (const int index);
  26980. /** Destructor. */
  26981. ~AudioCDReader();
  26982. /** Implementation of the AudioFormatReader method. */
  26983. bool read (int** destSamples,
  26984. int64 startSampleInFile,
  26985. int numSamples);
  26986. /** Checks whether the CD has been removed from the drive.
  26987. */
  26988. bool isCDStillPresent() const;
  26989. /** Returns the total number of tracks (audio + data).
  26990. */
  26991. int getNumTracks() const;
  26992. /** Finds the sample offset of the start of a track.
  26993. @param trackNum the track number, where 0 is the first track.
  26994. */
  26995. int getPositionOfTrackStart (int trackNum) const;
  26996. /** Returns true if a given track is an audio track.
  26997. @param trackNum the track number, where 0 is the first track.
  26998. */
  26999. bool isTrackAudio (int trackNum) const;
  27000. /** Refreshes the object's table of contents.
  27001. If the disc has been ejected and a different one put in since this
  27002. object was created, this will cause it to update its idea of how many tracks
  27003. there are, etc.
  27004. */
  27005. void refreshTrackLengths();
  27006. /** Enables scanning for indexes within tracks.
  27007. @see getLastIndex
  27008. */
  27009. void enableIndexScanning (bool enabled);
  27010. /** Returns the index number found during the last read() call.
  27011. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27012. Then when the read() method is called, if it comes across an index within that
  27013. block, the index number is stored and returned by this method.
  27014. Some devices might not support indexes, of course.
  27015. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27016. @see enableIndexScanning
  27017. */
  27018. int getLastIndex() const;
  27019. /** Scans a track to find the position of any indexes within it.
  27020. @param trackNumber the track to look in, where 0 is the first track on the disc
  27021. @returns an array of sample positions of any index points found (not including
  27022. the index that marks the start of the track)
  27023. */
  27024. const Array <int> findIndexesInTrack (const int trackNumber);
  27025. /** Returns the CDDB id number for the CD.
  27026. It's not a great way of identifying a disc, but it's traditional.
  27027. */
  27028. int getCDDBId();
  27029. /** Tries to eject the disk.
  27030. Of course this might not be possible, if some other process is using it.
  27031. */
  27032. void ejectDisk();
  27033. juce_UseDebuggingNewOperator
  27034. private:
  27035. #if JUCE_MAC
  27036. File volumeDir;
  27037. OwnedArray<File> tracks;
  27038. Array <int> trackStartSamples;
  27039. int currentReaderTrack;
  27040. AudioFormatReader* reader;
  27041. AudioCDReader (const File& volume);
  27042. public:
  27043. static int compareElements (const File* const, const File* const) throw();
  27044. private:
  27045. #elif JUCE_WIN32
  27046. int numTracks;
  27047. int trackStarts[100];
  27048. bool audioTracks [100];
  27049. void* handle;
  27050. bool indexingEnabled;
  27051. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27052. MemoryBlock buffer;
  27053. AudioCDReader (void* handle);
  27054. int getIndexAt (int samplePos);
  27055. #elif JUCE_LINUX
  27056. AudioCDReader();
  27057. #endif
  27058. AudioCDReader (const AudioCDReader&);
  27059. const AudioCDReader& operator= (const AudioCDReader&);
  27060. };
  27061. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27062. /********* End of inlined file: juce_AudioCDReader.h *********/
  27063. #endif
  27064. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27065. #endif
  27066. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27067. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27068. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27069. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27070. /**
  27071. A class for keeping a list of available audio formats, and for deciding which
  27072. one to use to open a given file.
  27073. You can either use this class as a singleton object, or create instances of it
  27074. yourself. Once created, use its registerFormat() method to tell it which
  27075. formats it should use.
  27076. @see AudioFormat
  27077. */
  27078. class JUCE_API AudioFormatManager
  27079. {
  27080. public:
  27081. /** Creates an empty format manager.
  27082. Before it'll be any use, you'll need to call registerFormat() with all the
  27083. formats you want it to be able to recognise.
  27084. */
  27085. AudioFormatManager();
  27086. /** Destructor. */
  27087. ~AudioFormatManager();
  27088. juce_DeclareSingleton (AudioFormatManager, false);
  27089. /** Adds a format to the manager's list of available file types.
  27090. The object passed-in will be deleted by this object, so don't keep a pointer
  27091. to it!
  27092. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27093. return this one when called.
  27094. */
  27095. void registerFormat (AudioFormat* newFormat,
  27096. const bool makeThisTheDefaultFormat);
  27097. /** Handy method to make it easy to register the formats that come with Juce.
  27098. Currently, this will add WAV and AIFF to the list.
  27099. */
  27100. void registerBasicFormats();
  27101. /** Clears the list of known formats. */
  27102. void clearFormats();
  27103. /** Returns the number of currently registered file formats. */
  27104. int getNumKnownFormats() const;
  27105. /** Returns one of the registered file formats. */
  27106. AudioFormat* getKnownFormat (const int index) const;
  27107. /** Looks for which of the known formats is listed as being for a given file
  27108. extension.
  27109. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27110. */
  27111. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27112. /** Returns the format which has been set as the default one.
  27113. You can set a format as being the default when it is registered. It's useful
  27114. when you want to write to a file, because the best format may change between
  27115. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27116. If none has been set as the default, this method will just return the first
  27117. one in the list.
  27118. */
  27119. AudioFormat* getDefaultFormat() const;
  27120. /** Returns a set of wildcards for file-matching that contains the extensions for
  27121. all known formats.
  27122. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27123. */
  27124. const String getWildcardForAllFormats() const;
  27125. /** Searches through the known formats to try to create a suitable reader for
  27126. this file.
  27127. If none of the registered formats can open the file, it'll return 0. If it
  27128. returns a reader, it's the caller's responsibility to delete the reader.
  27129. */
  27130. AudioFormatReader* createReaderFor (const File& audioFile);
  27131. /** Searches through the known formats to try to create a suitable reader for
  27132. this stream.
  27133. The stream object that is passed-in will be deleted by this method or by the
  27134. reader that is returned, so the caller should not keep any references to it.
  27135. The stream that is passed-in must be capable of being repositioned so
  27136. that all the formats can have a go at opening it.
  27137. If none of the registered formats can open the stream, it'll return 0. If it
  27138. returns a reader, it's the caller's responsibility to delete the reader.
  27139. */
  27140. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27141. juce_UseDebuggingNewOperator
  27142. private:
  27143. VoidArray knownFormats;
  27144. int defaultFormatIndex;
  27145. };
  27146. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27147. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27148. #endif
  27149. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27150. #endif
  27151. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27152. #endif
  27153. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27154. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27155. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27156. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27157. /**
  27158. This class is used to wrap an AudioFormatReader and only read from a
  27159. subsection of the file.
  27160. So if you have a reader which can read a 1000 sample file, you could wrap it
  27161. in one of these to only access, e.g. samples 100 to 200, and any samples
  27162. outside that will come back as 0. Accessing sample 0 from this reader will
  27163. actually read the first sample from the other's subsection, which might
  27164. be at a non-zero position.
  27165. @see AudioFormatReader
  27166. */
  27167. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27168. {
  27169. public:
  27170. /** Creates a AudioSubsectionReader for a given data source.
  27171. @param sourceReader the source reader from which we'll be taking data
  27172. @param subsectionStartSample the sample within the source reader which will be
  27173. mapped onto sample 0 for this reader.
  27174. @param subsectionLength the number of samples from the source that will
  27175. make up the subsection. If this reader is asked for
  27176. any samples beyond this region, it will return zero.
  27177. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27178. this object is deleted.
  27179. */
  27180. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27181. const int64 subsectionStartSample,
  27182. const int64 subsectionLength,
  27183. const bool deleteSourceWhenDeleted);
  27184. /** Destructor. */
  27185. ~AudioSubsectionReader();
  27186. bool read (int** destSamples,
  27187. int64 startSample,
  27188. int numSamples);
  27189. void readMaxLevels (int64 startSample,
  27190. int64 numSamples,
  27191. float& lowestLeft,
  27192. float& highestLeft,
  27193. float& lowestRight,
  27194. float& highestRight);
  27195. juce_UseDebuggingNewOperator
  27196. private:
  27197. AudioFormatReader* const source;
  27198. int64 startSample, length;
  27199. const bool deleteSourceWhenDeleted;
  27200. AudioSubsectionReader (const AudioSubsectionReader&);
  27201. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27202. };
  27203. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27204. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27205. #endif
  27206. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27207. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27208. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27209. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27210. class AudioThumbnailCache;
  27211. /**
  27212. Makes it easy to quickly draw scaled views of the waveform shape of an
  27213. audio file.
  27214. To use this class, just create an AudioThumbNail class for the file you want
  27215. to draw, call setSource to tell it which file or resource to use, then call
  27216. drawChannel() to draw it.
  27217. The class will asynchronously scan the wavefile to create its scaled-down view,
  27218. so you should make your UI repaint itself as this data comes in. To do this, the
  27219. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27220. listeners should repaint themselves.
  27221. The thumbnail stores an internal low-res version of the wave data, and this can
  27222. be loaded and saved to avoid having to scan the file again.
  27223. @see AudioThumbnailCache
  27224. */
  27225. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27226. public TimeSliceClient,
  27227. private Timer
  27228. {
  27229. public:
  27230. /** Creates an audio thumbnail.
  27231. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27232. of the audio data, this is the scale at which it should be done
  27233. @param formatManagerToUse the audio format manager that is used to open the file
  27234. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27235. thread and storage that is used to by the thumbnail, and the cache
  27236. object can be shared between multiple thumbnails
  27237. */
  27238. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27239. AudioFormatManager& formatManagerToUse,
  27240. AudioThumbnailCache& cacheToUse);
  27241. /** Destructor. */
  27242. ~AudioThumbnail();
  27243. /** Specifies the file or stream that contains the audio file.
  27244. For a file, just call
  27245. @code
  27246. setSource (new FileInputSource (file))
  27247. @endcode
  27248. You can pass a zero in here to clear the thumbnail.
  27249. The source that is passed in will be deleted by this object when it is no
  27250. longer needed
  27251. */
  27252. void setSource (InputSource* const newSource);
  27253. /** Reloads the low res thumbnail data from an input stream.
  27254. The thumb will automatically attempt to reload itself from its
  27255. AudioThumbnailCache.
  27256. */
  27257. void loadFrom (InputStream& input);
  27258. /** Saves the low res thumbnail data to an output stream.
  27259. The thumb will automatically attempt to save itself to its
  27260. AudioThumbnailCache after it finishes scanning the wave file.
  27261. */
  27262. void saveTo (OutputStream& output) const;
  27263. /** Returns the number of channels in the file.
  27264. */
  27265. int getNumChannels() const throw();
  27266. /** Returns the length of the audio file.
  27267. */
  27268. double getTotalLength() const throw();
  27269. /** Renders the waveform shape for a channel.
  27270. The waveform will be drawn within the specified rectangle, where startTime
  27271. and endTime specify the times within the audio file that should be positioned
  27272. at the left and right edges of the rectangle.
  27273. The waveform will be scaled vertically so that a full-volume sample will fill
  27274. the rectangle vertically, but you can also specify an extra vertical scale factor
  27275. with the verticalZoomFactor parameter.
  27276. */
  27277. void drawChannel (Graphics& g,
  27278. int x, int y, int w, int h,
  27279. double startTime,
  27280. double endTime,
  27281. int channelNum,
  27282. const float verticalZoomFactor);
  27283. /** Returns true if the low res preview is fully generated.
  27284. */
  27285. bool isFullyLoaded() const throw();
  27286. /** @internal */
  27287. bool useTimeSlice();
  27288. /** @internal */
  27289. void timerCallback();
  27290. juce_UseDebuggingNewOperator
  27291. private:
  27292. AudioFormatManager& formatManagerToUse;
  27293. AudioThumbnailCache& cache;
  27294. InputSource* source;
  27295. CriticalSection readerLock;
  27296. AudioFormatReader* reader;
  27297. MemoryBlock data, cachedLevels;
  27298. int orginalSamplesPerThumbnailSample;
  27299. int numChannelsCached, numSamplesCached;
  27300. double cachedStart, cachedTimePerPixel;
  27301. bool cacheNeedsRefilling;
  27302. void clear();
  27303. AudioFormatReader* createReader() const;
  27304. void generateSection (AudioFormatReader& reader,
  27305. int64 startSample,
  27306. int numSamples);
  27307. char* getChannelData (int channel) const;
  27308. void refillCache (const int numSamples,
  27309. double startTime,
  27310. const double timePerPixel);
  27311. friend class AudioThumbnailCache;
  27312. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27313. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27314. // returns true if more needs to be read
  27315. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27316. };
  27317. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27318. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27319. #endif
  27320. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27321. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27322. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27323. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27324. struct ThumbnailCacheEntry;
  27325. /**
  27326. An instance of this class is used to manage multiple AudioThumbnail objects.
  27327. The cache runs a single background thread that is shared by all the thumbnails
  27328. that need it, and it maintains a set of low-res previews in memory, to avoid
  27329. having to re-scan audio files too often.
  27330. @see AudioThumbnail
  27331. */
  27332. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27333. {
  27334. public:
  27335. /** Creates a cache object.
  27336. The maxNumThumbsToStore parameter lets you specify how many previews should
  27337. be kept in memory at once.
  27338. */
  27339. AudioThumbnailCache (const int maxNumThumbsToStore);
  27340. /** Destructor. */
  27341. ~AudioThumbnailCache();
  27342. /** Clears out any stored thumbnails.
  27343. */
  27344. void clear();
  27345. /** Reloads the specified thumb if this cache contains the appropriate stored
  27346. data.
  27347. This is called automatically by the AudioThumbnail class, so you shouldn't
  27348. normally need to call it directly.
  27349. */
  27350. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27351. /** Stores the cachable data from the specified thumb in this cache.
  27352. This is called automatically by the AudioThumbnail class, so you shouldn't
  27353. normally need to call it directly.
  27354. */
  27355. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27356. juce_UseDebuggingNewOperator
  27357. private:
  27358. OwnedArray <ThumbnailCacheEntry> thumbs;
  27359. int maxNumThumbsToStore;
  27360. friend class AudioThumbnail;
  27361. void addThumbnail (AudioThumbnail* const thumb);
  27362. void removeThumbnail (AudioThumbnail* const thumb);
  27363. };
  27364. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27365. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27366. #endif
  27367. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27368. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27369. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27370. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27371. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27372. /**
  27373. Reads and writes the lossless-compression FLAC audio format.
  27374. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27375. and make sure your include search path and library search path are set up to find
  27376. the FLAC header files and static libraries.
  27377. @see AudioFormat
  27378. */
  27379. class JUCE_API FlacAudioFormat : public AudioFormat
  27380. {
  27381. public:
  27382. FlacAudioFormat();
  27383. ~FlacAudioFormat();
  27384. const Array <int> getPossibleSampleRates();
  27385. const Array <int> getPossibleBitDepths();
  27386. bool canDoStereo();
  27387. bool canDoMono();
  27388. bool isCompressed();
  27389. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27390. const bool deleteStreamIfOpeningFails);
  27391. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27392. double sampleRateToUse,
  27393. unsigned int numberOfChannels,
  27394. int bitsPerSample,
  27395. const StringPairArray& metadataValues,
  27396. int qualityOptionIndex);
  27397. juce_UseDebuggingNewOperator
  27398. };
  27399. #endif
  27400. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27401. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27402. #endif
  27403. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27404. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27405. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27406. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27407. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27408. /**
  27409. Reads and writes the Ogg-Vorbis audio format.
  27410. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27411. and make sure your include search path and library search path are set up to find
  27412. the Vorbis and Ogg header files and static libraries.
  27413. @see AudioFormat,
  27414. */
  27415. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27416. {
  27417. public:
  27418. OggVorbisAudioFormat();
  27419. ~OggVorbisAudioFormat();
  27420. const Array <int> getPossibleSampleRates();
  27421. const Array <int> getPossibleBitDepths();
  27422. bool canDoStereo();
  27423. bool canDoMono();
  27424. bool isCompressed();
  27425. const StringArray getQualityOptions();
  27426. /** Tries to estimate the quality level of an ogg file based on its size.
  27427. If it can't read the file for some reason, this will just return 1 (medium quality),
  27428. otherwise it will return the approximate quality setting that would have been used
  27429. to create the file.
  27430. @see getQualityOptions
  27431. */
  27432. int estimateOggFileQuality (const File& source);
  27433. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27434. const bool deleteStreamIfOpeningFails);
  27435. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27436. double sampleRateToUse,
  27437. unsigned int numberOfChannels,
  27438. int bitsPerSample,
  27439. const StringPairArray& metadataValues,
  27440. int qualityOptionIndex);
  27441. juce_UseDebuggingNewOperator
  27442. };
  27443. #endif
  27444. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27445. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27446. #endif
  27447. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27448. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27449. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27450. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27451. #if JUCE_QUICKTIME
  27452. /**
  27453. Uses QuickTime to read the audio track a movie or media file.
  27454. As well as QuickTime movies, this should also manage to open other audio
  27455. files that quicktime can understand, like mp3, m4a, etc.
  27456. @see AudioFormat
  27457. */
  27458. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27459. {
  27460. public:
  27461. /** Creates a format object. */
  27462. QuickTimeAudioFormat();
  27463. /** Destructor. */
  27464. ~QuickTimeAudioFormat();
  27465. const Array <int> getPossibleSampleRates();
  27466. const Array <int> getPossibleBitDepths();
  27467. bool canDoStereo();
  27468. bool canDoMono();
  27469. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27470. const bool deleteStreamIfOpeningFails);
  27471. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27472. double sampleRateToUse,
  27473. unsigned int numberOfChannels,
  27474. int bitsPerSample,
  27475. const StringPairArray& metadataValues,
  27476. int qualityOptionIndex);
  27477. juce_UseDebuggingNewOperator
  27478. };
  27479. #endif
  27480. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27481. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27482. #endif
  27483. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27484. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27485. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27486. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27487. /**
  27488. Reads and Writes WAV format audio files.
  27489. @see AudioFormat
  27490. */
  27491. class JUCE_API WavAudioFormat : public AudioFormat
  27492. {
  27493. public:
  27494. /** Creates a format object. */
  27495. WavAudioFormat();
  27496. /** Destructor. */
  27497. ~WavAudioFormat();
  27498. /** Metadata property name used by wav readers and writers for adding
  27499. a BWAV chunk to the file.
  27500. @see AudioFormatReader::metadataValues, createWriterFor
  27501. */
  27502. static const tchar* const bwavDescription;
  27503. /** Metadata property name used by wav readers and writers for adding
  27504. a BWAV chunk to the file.
  27505. @see AudioFormatReader::metadataValues, createWriterFor
  27506. */
  27507. static const tchar* const bwavOriginator;
  27508. /** Metadata property name used by wav readers and writers for adding
  27509. a BWAV chunk to the file.
  27510. @see AudioFormatReader::metadataValues, createWriterFor
  27511. */
  27512. static const tchar* const bwavOriginatorRef;
  27513. /** Metadata property name used by wav readers and writers for adding
  27514. a BWAV chunk to the file.
  27515. Date format is: yyyy-mm-dd
  27516. @see AudioFormatReader::metadataValues, createWriterFor
  27517. */
  27518. static const tchar* const bwavOriginationDate;
  27519. /** Metadata property name used by wav readers and writers for adding
  27520. a BWAV chunk to the file.
  27521. Time format is: hh-mm-ss
  27522. @see AudioFormatReader::metadataValues, createWriterFor
  27523. */
  27524. static const tchar* const bwavOriginationTime;
  27525. /** Metadata property name used by wav readers and writers for adding
  27526. a BWAV chunk to the file.
  27527. This is the number of samples from the start of an edit that the
  27528. file is supposed to begin at. Seems like an obvious mistake to
  27529. only allow a file to occur in an edit once, but that's the way
  27530. it is..
  27531. @see AudioFormatReader::metadataValues, createWriterFor
  27532. */
  27533. static const tchar* const bwavTimeReference;
  27534. /** Metadata property name used by wav readers and writers for adding
  27535. a BWAV chunk to the file.
  27536. This is a
  27537. @see AudioFormatReader::metadataValues, createWriterFor
  27538. */
  27539. static const tchar* const bwavCodingHistory;
  27540. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27541. This just makes it easier than using the property names directly, and it
  27542. fills out the time and date in the right format.
  27543. */
  27544. static const StringPairArray createBWAVMetadata (const String& description,
  27545. const String& originator,
  27546. const String& originatorRef,
  27547. const Time& dateAndTime,
  27548. const int64 timeReferenceSamples,
  27549. const String& codingHistory);
  27550. const Array <int> getPossibleSampleRates();
  27551. const Array <int> getPossibleBitDepths();
  27552. bool canDoStereo();
  27553. bool canDoMono();
  27554. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27555. const bool deleteStreamIfOpeningFails);
  27556. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27557. double sampleRateToUse,
  27558. unsigned int numberOfChannels,
  27559. int bitsPerSample,
  27560. const StringPairArray& metadataValues,
  27561. int qualityOptionIndex);
  27562. juce_UseDebuggingNewOperator
  27563. };
  27564. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27565. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27566. #endif
  27567. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27568. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  27569. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27570. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27571. /********* Start of inlined file: juce_ActionListenerList.h *********/
  27572. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27573. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27574. /**
  27575. A set of ActionListeners.
  27576. Listeners can be added and removed from the list, and messages can be
  27577. broadcast to all the listeners.
  27578. @see ActionListener, ActionBroadcaster
  27579. */
  27580. class JUCE_API ActionListenerList : public MessageListener
  27581. {
  27582. public:
  27583. /** Creates an empty list. */
  27584. ActionListenerList() throw();
  27585. /** Destructor. */
  27586. ~ActionListenerList() throw();
  27587. /** Adds a listener to the list.
  27588. (Trying to add a listener that's already on the list will have no effect).
  27589. */
  27590. void addActionListener (ActionListener* const listener) throw();
  27591. /** Removes a listener from the list.
  27592. If the listener isn't on the list, this won't have any effect.
  27593. */
  27594. void removeActionListener (ActionListener* const listener) throw();
  27595. /** Removes all listeners from the list. */
  27596. void removeAllActionListeners() throw();
  27597. /** Broadcasts a message to all the registered listeners.
  27598. This sends the message asynchronously.
  27599. If a listener is on the list when this method is called but is removed from
  27600. the list before the message arrives, it won't receive the message. Similarly
  27601. listeners that are added to the list after the message is sent but before it
  27602. arrives won't get the message either.
  27603. */
  27604. void sendActionMessage (const String& message) const;
  27605. /** @internal */
  27606. void handleMessage (const Message&);
  27607. juce_UseDebuggingNewOperator
  27608. private:
  27609. SortedSet <void*> actionListeners_;
  27610. CriticalSection actionListenerLock_;
  27611. ActionListenerList (const ActionListenerList&);
  27612. const ActionListenerList& operator= (const ActionListenerList&);
  27613. };
  27614. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27615. /********* End of inlined file: juce_ActionListenerList.h *********/
  27616. /** Manages a list of ActionListeners, and can send them messages.
  27617. To quickly add methods to your class that can add/remove action
  27618. listeners and broadcast to them, you can derive from this.
  27619. @see ActionListenerList, ActionListener
  27620. */
  27621. class JUCE_API ActionBroadcaster
  27622. {
  27623. public:
  27624. /** Creates an ActionBroadcaster. */
  27625. ActionBroadcaster() throw();
  27626. /** Destructor. */
  27627. virtual ~ActionBroadcaster();
  27628. /** Adds a listener to the list.
  27629. (Trying to add a listener that's already on the list will have no effect).
  27630. */
  27631. void addActionListener (ActionListener* const listener);
  27632. /** Removes a listener from the list.
  27633. If the listener isn't on the list, this won't have any effect.
  27634. */
  27635. void removeActionListener (ActionListener* const listener);
  27636. /** Removes all listeners from the list. */
  27637. void removeAllActionListeners();
  27638. /** Broadcasts a message to all the registered listeners.
  27639. @see ActionListenerList::sendActionMessage
  27640. */
  27641. void sendActionMessage (const String& message) const;
  27642. private:
  27643. ActionListenerList actionListenerList;
  27644. ActionBroadcaster (const ActionBroadcaster&);
  27645. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  27646. };
  27647. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27648. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  27649. #endif
  27650. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  27651. #endif
  27652. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27653. #endif
  27654. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  27655. #endif
  27656. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  27657. #endif
  27658. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  27659. #endif
  27660. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  27661. #endif
  27662. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27663. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  27664. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27665. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27666. class InterprocessConnectionServer;
  27667. /**
  27668. Manages a simple two-way messaging connection to another process, using either
  27669. a socket or a named pipe as the transport medium.
  27670. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  27671. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27672. and incoming messages will result in a callback via the messageReceived()
  27673. method.
  27674. To open a pipe and wait for another client to connect to it, use the createPipe()
  27675. method.
  27676. To act as a socket server and create connections for one or more client, see the
  27677. InterprocessConnectionServer class.
  27678. @see InterprocessConnectionServer, Socket, NamedPipe
  27679. */
  27680. class JUCE_API InterprocessConnection : public Thread,
  27681. private MessageListener
  27682. {
  27683. public:
  27684. /** Creates a connection.
  27685. Connections are created manually, connecting them with the connectToSocket()
  27686. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  27687. when a client wants to connect.
  27688. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  27689. connectionLost() and messageReceived() methods will
  27690. always be made using the message thread; if false,
  27691. these will be called immediately on the connection's
  27692. own thread.
  27693. @param magicMessageHeaderNumber a magic number to use in the header to check the
  27694. validity of the data blocks being sent and received. This
  27695. can be any number, but the sender and receiver must obviously
  27696. use matching values or they won't recognise each other.
  27697. */
  27698. InterprocessConnection (const bool callbacksOnMessageThread = true,
  27699. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  27700. /** Destructor. */
  27701. ~InterprocessConnection();
  27702. /** Tries to connect this object to a socket.
  27703. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  27704. object waiting to receive client connections on this port number.
  27705. @param hostName the host computer, either a network address or name
  27706. @param portNumber the socket port number to try to connect to
  27707. @param timeOutMillisecs how long to keep trying before giving up
  27708. @returns true if the connection is established successfully
  27709. @see Socket
  27710. */
  27711. bool connectToSocket (const String& hostName,
  27712. const int portNumber,
  27713. const int timeOutMillisecs);
  27714. /** Tries to connect the object to an existing named pipe.
  27715. For this to work, another process on the same computer must already have opened
  27716. an InterprocessConnection object and used createPipe() to create a pipe for this
  27717. to connect to.
  27718. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27719. @returns true if it connects successfully.
  27720. @see createPipe, NamedPipe
  27721. */
  27722. bool connectToPipe (const String& pipeName,
  27723. const int pipeReceiveMessageTimeoutMs = -1);
  27724. /** Tries to create a new pipe for other processes to connect to.
  27725. This creates a pipe with the given name, so that other processes can use
  27726. connectToPipe() to connect to the other end.
  27727. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27728. If another process is already using this pipe, this will fail and return false.
  27729. */
  27730. bool createPipe (const String& pipeName,
  27731. const int pipeReceiveMessageTimeoutMs = -1);
  27732. /** Disconnects and closes any currently-open sockets or pipes. */
  27733. void disconnect();
  27734. /** True if a socket or pipe is currently active. */
  27735. bool isConnected() const;
  27736. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  27737. StreamingSocket* getSocket() const throw() { return socket; }
  27738. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  27739. NamedPipe* getPipe() const throw() { return pipe; }
  27740. /** Returns the name of the machine at the other end of this connection.
  27741. This will return an empty string if the other machine isn't known for
  27742. some reason.
  27743. */
  27744. const String getConnectedHostName() const;
  27745. /** Tries to send a message to the other end of this connection.
  27746. This will fail if it's not connected, or if there's some kind of write error. If
  27747. it succeeds, the connection object at the other end will receive the message by
  27748. a callback to its messageReceived() method.
  27749. @see messageReceived
  27750. */
  27751. bool sendMessage (const MemoryBlock& message);
  27752. /** Called when the connection is first connected.
  27753. If the connection was created with the callbacksOnMessageThread flag set, then
  27754. this will be called on the message thread; otherwise it will be called on a server
  27755. thread.
  27756. */
  27757. virtual void connectionMade() = 0;
  27758. /** Called when the connection is broken.
  27759. If the connection was created with the callbacksOnMessageThread flag set, then
  27760. this will be called on the message thread; otherwise it will be called on a server
  27761. thread.
  27762. */
  27763. virtual void connectionLost() = 0;
  27764. /** Called when a message arrives.
  27765. When the object at the other end of this connection sends us a message with sendMessage(),
  27766. this callback is used to deliver it to us.
  27767. If the connection was created with the callbacksOnMessageThread flag set, then
  27768. this will be called on the message thread; otherwise it will be called on a server
  27769. thread.
  27770. @see sendMessage
  27771. */
  27772. virtual void messageReceived (const MemoryBlock& message) = 0;
  27773. juce_UseDebuggingNewOperator
  27774. private:
  27775. CriticalSection pipeAndSocketLock;
  27776. StreamingSocket* socket;
  27777. NamedPipe* pipe;
  27778. bool callbackConnectionState;
  27779. const bool useMessageThread;
  27780. const uint32 magicMessageHeader;
  27781. int pipeReceiveMessageTimeout;
  27782. friend class InterprocessConnectionServer;
  27783. void initialiseWithSocket (StreamingSocket* const socket_);
  27784. void initialiseWithPipe (NamedPipe* const pipe_);
  27785. void handleMessage (const Message& message);
  27786. void connectionMadeInt();
  27787. void connectionLostInt();
  27788. void deliverDataInt (const MemoryBlock& data);
  27789. bool readNextMessageInt();
  27790. void run();
  27791. InterprocessConnection (const InterprocessConnection&);
  27792. const InterprocessConnection& operator= (const InterprocessConnection&);
  27793. };
  27794. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27795. /********* End of inlined file: juce_InterprocessConnection.h *********/
  27796. #endif
  27797. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27798. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  27799. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27800. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27801. /**
  27802. An object that waits for client sockets to connect to a port on this host, and
  27803. creates InterprocessConnection objects for each one.
  27804. To use this, create a class derived from it which implements the createConnectionObject()
  27805. method, so that it creates suitable connection objects for each client that tries
  27806. to connect.
  27807. @see InterprocessConnection
  27808. */
  27809. class JUCE_API InterprocessConnectionServer : private Thread
  27810. {
  27811. public:
  27812. /** Creates an uninitialised server object.
  27813. */
  27814. InterprocessConnectionServer();
  27815. /** Destructor. */
  27816. ~InterprocessConnectionServer();
  27817. /** Starts an internal thread which listens on the given port number.
  27818. While this is running, in another process tries to connect with the
  27819. InterprocessConnection::connectToSocket() method, this object will call
  27820. createConnectionObject() to create a connection to that client.
  27821. Use stop() to stop the thread running.
  27822. @see createConnectionObject, stop
  27823. */
  27824. bool beginWaitingForSocket (const int portNumber);
  27825. /** Terminates the listener thread, if it's active.
  27826. @see beginWaitingForSocket
  27827. */
  27828. void stop();
  27829. protected:
  27830. /** Creates a suitable connection object for a client process that wants to
  27831. connect to this one.
  27832. This will be called by the listener thread when a client process tries
  27833. to connect, and must return a new InterprocessConnection object that will
  27834. then run as this end of the connection.
  27835. @see InterprocessConnection
  27836. */
  27837. virtual InterprocessConnection* createConnectionObject() = 0;
  27838. public:
  27839. juce_UseDebuggingNewOperator
  27840. private:
  27841. StreamingSocket* volatile socket;
  27842. void run();
  27843. InterprocessConnectionServer (const InterprocessConnectionServer&);
  27844. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  27845. };
  27846. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27847. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  27848. #endif
  27849. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  27850. #endif
  27851. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  27852. #endif
  27853. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27854. /********* Start of inlined file: juce_MessageManager.h *********/
  27855. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27856. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  27857. class Component;
  27858. class MessageManagerLock;
  27859. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  27860. */
  27861. typedef void* (MessageCallbackFunction) (void* userData);
  27862. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  27863. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  27864. */
  27865. class JUCE_API MessageManager : private DeletedAtShutdown
  27866. {
  27867. public:
  27868. /** Returns the global instance of the MessageManager. */
  27869. static MessageManager* getInstance() throw();
  27870. /** Runs the event dispatch loop until a stop message is posted.
  27871. This method is only intended to be run by the application's startup routine,
  27872. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  27873. @see stopDispatchLoop
  27874. */
  27875. void runDispatchLoop();
  27876. /** Sends a signal that the dispatch loop should terminate.
  27877. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  27878. will be interrupted and will return.
  27879. @see runDispatchLoop
  27880. */
  27881. void stopDispatchLoop();
  27882. /** Returns true if the stopDispatchLoop() method has been called.
  27883. */
  27884. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  27885. /** Synchronously dispatches messages until a given time has elapsed.
  27886. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  27887. otherwise returns true.
  27888. */
  27889. bool runDispatchLoopUntil (int millisecondsToRunFor);
  27890. /** Calls a function using the message-thread.
  27891. This can be used by any thread to cause this function to be called-back
  27892. by the message thread. If it's the message-thread that's calling this method,
  27893. then the function will just be called; if another thread is calling, a message
  27894. will be posted to the queue, and this method will block until that message
  27895. is delivered, the function is called, and the result is returned.
  27896. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  27897. thread has a critical section locked, which an unrelated message callback then tries to lock
  27898. before the message thread gets round to processing this callback.
  27899. @param callback the function to call - its signature must be @code
  27900. void* myCallbackFunction (void*) @endcode
  27901. @param userData a user-defined pointer that will be passed to the function that gets called
  27902. @returns the value that the callback function returns.
  27903. @see MessageManagerLock
  27904. */
  27905. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  27906. void* userData);
  27907. /** Returns true if the caller-thread is the message thread. */
  27908. bool isThisTheMessageThread() const throw();
  27909. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  27910. (Best to ignore this method unless you really know what you're doing..)
  27911. @see getCurrentMessageThread
  27912. */
  27913. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  27914. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  27915. (Best to ignore this method unless you really know what you're doing..)
  27916. @see setCurrentMessageThread
  27917. */
  27918. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  27919. /** Returns true if the caller thread has currenltly got the message manager locked.
  27920. see the MessageManagerLock class for more info about this.
  27921. This will be true if the caller is the message thread, because that automatically
  27922. gains a lock while a message is being dispatched.
  27923. */
  27924. bool currentThreadHasLockedMessageManager() const throw();
  27925. /** Sends a message to all other JUCE applications that are running.
  27926. @param messageText the string that will be passed to the actionListenerCallback()
  27927. method of the broadcast listeners in the other app.
  27928. @see registerBroadcastListener, ActionListener
  27929. */
  27930. static void broadcastMessage (const String& messageText) throw();
  27931. /** Registers a listener to get told about broadcast messages.
  27932. The actionListenerCallback() callback's string parameter
  27933. is the message passed into broadcastMessage().
  27934. @see broadcastMessage
  27935. */
  27936. void registerBroadcastListener (ActionListener* listener) throw();
  27937. /** Deregisters a broadcast listener. */
  27938. void deregisterBroadcastListener (ActionListener* listener) throw();
  27939. /** @internal */
  27940. void deliverMessage (void*);
  27941. /** @internal */
  27942. void deliverBroadcastMessage (const String&);
  27943. juce_UseDebuggingNewOperator
  27944. private:
  27945. MessageManager() throw();
  27946. ~MessageManager() throw();
  27947. friend class MessageListener;
  27948. friend class ChangeBroadcaster;
  27949. friend class ActionBroadcaster;
  27950. static MessageManager* instance;
  27951. SortedSet<const MessageListener*> messageListeners;
  27952. ActionListenerList* broadcastListeners;
  27953. friend class JUCEApplication;
  27954. bool quitMessagePosted, quitMessageReceived;
  27955. Thread::ThreadID messageThreadId;
  27956. VoidArray modalComponents;
  27957. static void* exitModalLoopCallback (void*);
  27958. void postMessageToQueue (Message* const message);
  27959. static void doPlatformSpecificInitialisation();
  27960. static void doPlatformSpecificShutdown();
  27961. friend class MessageManagerLock;
  27962. CriticalSection messageDispatchLock;
  27963. Thread::ThreadID currentLockingThreadId;
  27964. MessageManager (const MessageManager&);
  27965. const MessageManager& operator= (const MessageManager&);
  27966. };
  27967. /** Used to make sure that the calling thread has exclusive access to the message loop.
  27968. Because it's not thread-safe to call any of the Component or other UI classes
  27969. from threads other than the message thread, one of these objects can be used to
  27970. lock the message loop and allow this to be done. The message thread will be
  27971. suspended for the lifetime of the MessageManagerLock object, so create one on
  27972. the stack like this: @code
  27973. void MyThread::run()
  27974. {
  27975. someData = 1234;
  27976. const MessageManagerLock mmLock;
  27977. // the event loop will now be locked so it's safe to make a few calls..
  27978. myComponent->setBounds (newBounds);
  27979. myComponent->repaint();
  27980. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  27981. }
  27982. @endcode
  27983. Obviously be careful not to create one of these and leave it lying around, or
  27984. your app will grind to a halt!
  27985. Another caveat is that using this in conjunction with other CriticalSections
  27986. can create lots of interesting ways of producing a deadlock! In particular, if
  27987. your message thread calls stopThread() for a thread that uses these locks,
  27988. you'll get an (occasional) deadlock..
  27989. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  27990. */
  27991. class JUCE_API MessageManagerLock
  27992. {
  27993. public:
  27994. /** Tries to acquire a lock on the message manager.
  27995. If this constructor
  27996. When this constructor returns, the message manager will have finished processing the
  27997. last message and will not send another message until this MessageManagerLock is
  27998. deleted.
  27999. If the current thread already has the lock, nothing will be done, so it's perfectly
  28000. safe to create these locks recursively.
  28001. */
  28002. MessageManagerLock() throw();
  28003. /** Releases the current thread's lock on the message manager.
  28004. Make sure this object is created and deleted by the same thread,
  28005. otherwise there are no guarantees what will happen!
  28006. */
  28007. ~MessageManagerLock() throw();
  28008. /** Tries to acquire a lock on the message manager.
  28009. This does the same thing as the normal constructor, but while it's waiting to get
  28010. the lock, it checks the specified thread to see if it has been given the
  28011. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  28012. without gaining the lock.
  28013. To find out whether the lock was successful, call lockWasGained(). If this is
  28014. false, your thread is being told to die, so you'd better get out of there.
  28015. If the current thread already has the lock, nothing will be done, so it's perfectly
  28016. safe to create these locks recursively.
  28017. E.g.
  28018. @code
  28019. void run()
  28020. {
  28021. ...
  28022. while (! threadShouldExit())
  28023. {
  28024. MessageManagerLock mml (Thread::getCurrentThread());
  28025. if (! mml.lockWasGained)
  28026. return; // another thread is trying to kill us!
  28027. ..do some locked stuff here..
  28028. }
  28029. ..and now the MM is now unlocked..
  28030. }
  28031. @endcode
  28032. */
  28033. MessageManagerLock (Thread* const threadToCheckForExitSignal) throw();
  28034. /** Returns true if the lock was successfully acquired.
  28035. (See the constructor that takes a Thread for more info).
  28036. */
  28037. bool lockWasGained() const throw() { return locked; }
  28038. private:
  28039. Thread::ThreadID lastLockingThreadId;
  28040. bool locked;
  28041. };
  28042. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28043. /********* End of inlined file: juce_MessageManager.h *********/
  28044. #endif
  28045. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28046. /********* Start of inlined file: juce_MultiTimer.h *********/
  28047. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28048. #define __JUCE_MULTITIMER_JUCEHEADER__
  28049. /**
  28050. A type of timer class that can run multiple timers with different frequencies,
  28051. all of which share a single callback.
  28052. This class is very similar to the Timer class, but allows you run multiple
  28053. separate timers, where each one has a unique ID number. The methods in this
  28054. class are exactly equivalent to those in Timer, but with the addition of
  28055. this ID number.
  28056. To use it, you need to create a subclass of MultiTimer, implementing the
  28057. timerCallback() method. Then you can start timers with startTimer(), and
  28058. each time the callback is triggered, it passes in the ID of the timer that
  28059. caused it.
  28060. @see Timer
  28061. */
  28062. class JUCE_API MultiTimer
  28063. {
  28064. protected:
  28065. /** Creates a MultiTimer.
  28066. When created, no timers are running, so use startTimer() to start things off.
  28067. */
  28068. MultiTimer() throw();
  28069. /** Creates a copy of another timer.
  28070. Note that this timer will not contain any running timers, even if the one you're
  28071. copying from was running.
  28072. */
  28073. MultiTimer (const MultiTimer& other) throw();
  28074. public:
  28075. /** Destructor. */
  28076. virtual ~MultiTimer();
  28077. /** The user-defined callback routine that actually gets called by each of the
  28078. timers that are running.
  28079. It's perfectly ok to call startTimer() or stopTimer() from within this
  28080. callback to change the subsequent intervals.
  28081. */
  28082. virtual void timerCallback (const int timerId) = 0;
  28083. /** Starts a timer and sets the length of interval required.
  28084. If the timer is already started, this will reset it, so the
  28085. time between calling this method and the next timer callback
  28086. will not be less than the interval length passed in.
  28087. @param timerId a unique Id number that identifies the timer to
  28088. start. This is the id that will be passed back
  28089. to the timerCallback() method when this timer is
  28090. triggered
  28091. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28092. rounded up to 1)
  28093. */
  28094. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28095. /** Stops a timer.
  28096. If a timer has been started with the given ID number, it will be cancelled.
  28097. No more callbacks will be made for the specified timer after this method returns.
  28098. If this is called from a different thread, any callbacks that may
  28099. be currently executing may be allowed to finish before the method
  28100. returns.
  28101. */
  28102. void stopTimer (const int timerId) throw();
  28103. /** Checks whether a timer has been started for a specified ID.
  28104. @returns true if a timer with the given ID is running.
  28105. */
  28106. bool isTimerRunning (const int timerId) const throw();
  28107. /** Returns the interval for a specified timer ID.
  28108. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28109. is running for the ID number specified.
  28110. */
  28111. int getTimerInterval (const int timerId) const throw();
  28112. private:
  28113. CriticalSection timerListLock;
  28114. VoidArray timers;
  28115. const MultiTimer& operator= (const MultiTimer&);
  28116. };
  28117. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28118. /********* End of inlined file: juce_MultiTimer.h *********/
  28119. #endif
  28120. #ifndef __JUCE_TIMER_JUCEHEADER__
  28121. #endif
  28122. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28123. #endif
  28124. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28125. /********* Start of inlined file: juce_GradientBrush.h *********/
  28126. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28127. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28128. /********* Start of inlined file: juce_ColourGradient.h *********/
  28129. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28130. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28131. /**
  28132. Structure used to define a colour gradient for painting areas.
  28133. @see GradientBrush
  28134. */
  28135. class JUCE_API ColourGradient
  28136. {
  28137. public:
  28138. /** Creates a gradient object.
  28139. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28140. colour2 should be. In between them there's a gradient.
  28141. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28142. its centre.
  28143. The alpha transparencies of the colours are used, so note that
  28144. if you 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. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28148. will be white all the way across.
  28149. @see ColourGradient
  28150. */
  28151. ColourGradient (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 an uninitialised gradient.
  28159. If you use this constructor instead of the other one, be sure to set all the
  28160. object's public member variables before using it!
  28161. */
  28162. ColourGradient() throw();
  28163. /** Destructor */
  28164. ~ColourGradient() throw();
  28165. /** Removes any colours that have been added.
  28166. This will also remove any start and end colours, so the gradient won't work. You'll
  28167. need to add more colours with addColour().
  28168. */
  28169. void clearColours() throw();
  28170. /** Adds a colour at a point along the length of the gradient.
  28171. This allows the gradient to go through a spectrum of colours, instead of just a
  28172. start and end colour.
  28173. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28174. of the distance along the line between the two points
  28175. at which the colour should occur.
  28176. @param colour the colour that should be used at this point
  28177. */
  28178. void addColour (const double proportionAlongGradient,
  28179. const Colour& colour) throw();
  28180. /** Multiplies the alpha value of all the colours by the given scale factor */
  28181. void multiplyOpacity (const float multiplier) throw();
  28182. /** Returns the number of colour-stops that have been added. */
  28183. int getNumColours() const throw();
  28184. /** Returns the position along the length of the gradient of the colour with this index.
  28185. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28186. */
  28187. double getColourPosition (const int index) const throw();
  28188. /** Returns the colour that was added with a given index.
  28189. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28190. */
  28191. const Colour getColour (const int index) const throw();
  28192. /** Creates a set of interpolated premultiplied ARGB values.
  28193. The caller must delete the array that is returned using juce_free().
  28194. */
  28195. PixelARGB* createLookupTable (int& numEntries) const throw();
  28196. /** Returns true if all colours are opaque. */
  28197. bool isOpaque() const throw();
  28198. /** Returns true if all colours are completely transparent. */
  28199. bool isInvisible() const throw();
  28200. float x1;
  28201. float y1;
  28202. float x2;
  28203. float y2;
  28204. /** If true, the gradient should be filled circularly, centred around
  28205. (x1, y1), with (x2, y2) defining a point on the circumference.
  28206. If false, the gradient is linear between the two points.
  28207. */
  28208. bool isRadial;
  28209. /** A transform to apply to the resultant gradient shape */
  28210. AffineTransform transform;
  28211. juce_UseDebuggingNewOperator
  28212. private:
  28213. Array <uint32> colours;
  28214. };
  28215. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28216. /********* End of inlined file: juce_ColourGradient.h *********/
  28217. /**
  28218. A Brush that fills areas with a colour gradient.
  28219. The gradient can either be linear or circular.
  28220. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28221. */
  28222. class JUCE_API GradientBrush : public Brush
  28223. {
  28224. public:
  28225. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28226. (x1, y1) is the location relative to the origin of the Graphics context,
  28227. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28228. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28229. its centre.
  28230. The alpha transparencies of the colours are used, so the brush
  28231. need not be completely opaque. Note that this means that if you
  28232. blend from transparent to a solid colour, the RGB of the transparent
  28233. colour will become visible in parts of the gradient. e.g. blending
  28234. from Colour::transparentBlack to Colours::white will produce a
  28235. grey colour, but Colour::transparentWhite to Colours::white will be
  28236. white all the way across.
  28237. @see ColourGradient
  28238. */
  28239. GradientBrush (const Colour& colour1,
  28240. const float x1,
  28241. const float y1,
  28242. const Colour& colour2,
  28243. const float x2,
  28244. const float y2,
  28245. const bool isRadial) throw();
  28246. /** Creates a gradient brush from a ColourGradient object.
  28247. */
  28248. GradientBrush (const ColourGradient& gradient) throw();
  28249. /** Destructor. */
  28250. ~GradientBrush() throw();
  28251. Brush* createCopy() const throw();
  28252. void applyTransform (const AffineTransform& transform) throw();
  28253. void multiplyOpacity (const float multiple) throw();
  28254. bool isInvisible() const throw();
  28255. void paintPath (LowLevelGraphicsContext& context,
  28256. const Path& path, const AffineTransform& transform) throw();
  28257. void paintRectangle (LowLevelGraphicsContext& context,
  28258. int x, int y, int w, int h) throw();
  28259. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28260. const Image& alphaChannelImage, int imageX, int imageY,
  28261. int x, int y, int w, int h) throw();
  28262. juce_UseDebuggingNewOperator
  28263. protected:
  28264. ColourGradient gradient;
  28265. private:
  28266. GradientBrush (const GradientBrush&);
  28267. const GradientBrush& operator= (const GradientBrush&);
  28268. };
  28269. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28270. /********* End of inlined file: juce_GradientBrush.h *********/
  28271. #endif
  28272. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28273. /********* Start of inlined file: juce_ImageBrush.h *********/
  28274. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28275. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28276. /********* Start of inlined file: juce_Image.h *********/
  28277. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28278. #define __JUCE_IMAGE_JUCEHEADER__
  28279. /**
  28280. Holds a fixed-size bitmap.
  28281. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28282. To draw into an image, create a Graphics object for it.
  28283. e.g. @code
  28284. // create a transparent 500x500 image..
  28285. Image myImage (Image::RGB, 500, 500, true);
  28286. Graphics g (myImage);
  28287. g.setColour (Colours::red);
  28288. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28289. @endcode
  28290. Other useful ways to create an image are with the ImageCache class, or the
  28291. ImageFileFormat, which provides a way to load common image files.
  28292. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28293. */
  28294. class JUCE_API Image
  28295. {
  28296. public:
  28297. enum PixelFormat
  28298. {
  28299. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28300. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28301. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28302. };
  28303. /** Creates an in-memory image with a specified size and format.
  28304. @param format the number of colour channels in the image
  28305. @param imageWidth the desired width of the image, in pixels - this value must be
  28306. greater than zero (otherwise a width of 1 will be used)
  28307. @param imageHeight the desired width of the image, in pixels - this value must be
  28308. greater than zero (otherwise a height of 1 will be used)
  28309. @param clearImage if true, the image will initially be cleared to black or transparent
  28310. black. If false, the image may contain random data, and the
  28311. user will have to deal with this
  28312. */
  28313. Image (const PixelFormat format,
  28314. const int imageWidth,
  28315. const int imageHeight,
  28316. const bool clearImage);
  28317. /** Creates a copy of another image.
  28318. @see createCopy
  28319. */
  28320. Image (const Image& other);
  28321. /** Destructor. */
  28322. virtual ~Image();
  28323. /** Returns the image's width (in pixels). */
  28324. int getWidth() const throw() { return imageWidth; }
  28325. /** Returns the image's height (in pixels). */
  28326. int getHeight() const throw() { return imageHeight; }
  28327. /** Returns the image's pixel format. */
  28328. PixelFormat getFormat() const throw() { return format; }
  28329. /** True if the image's format is ARGB. */
  28330. bool isARGB() const throw() { return format == ARGB; }
  28331. /** True if the image's format is RGB. */
  28332. bool isRGB() const throw() { return format == RGB; }
  28333. /** True if the image contains an alpha-channel. */
  28334. bool hasAlphaChannel() const throw() { return format != RGB; }
  28335. /** Clears a section of the image with a given colour.
  28336. This won't do any alpha-blending - it just sets all pixels in the image to
  28337. the given colour (which may be non-opaque if the image has an alpha channel).
  28338. */
  28339. virtual void clear (int x, int y, int w, int h,
  28340. const Colour& colourToClearTo = Colour (0x00000000));
  28341. /** Returns a new image that's a copy of this one.
  28342. A new size for the copied image can be specified, or values less than
  28343. zero can be passed-in to use the image's existing dimensions.
  28344. It's up to the caller to delete the image when no longer needed.
  28345. */
  28346. virtual Image* createCopy (int newWidth = -1,
  28347. int newHeight = -1,
  28348. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28349. /** Returns the colour of one of the pixels in the image.
  28350. If the co-ordinates given are beyond the image's boundaries, this will
  28351. return Colours::transparentBlack.
  28352. (0, 0) is the image's top-left corner.
  28353. @see getAlphaAt, setPixelAt, blendPixelAt
  28354. */
  28355. virtual const Colour getPixelAt (const int x, const int y) const;
  28356. /** Sets the colour of one of the image's pixels.
  28357. If the co-ordinates are beyond the image's boundaries, then nothing will
  28358. happen.
  28359. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28360. just replace the existing pixel with the given one. The colour's opacity
  28361. will be ignored if this image doesn't have an alpha-channel.
  28362. (0, 0) is the image's top-left corner.
  28363. @see blendPixelAt
  28364. */
  28365. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28366. /** Changes the opacity of a pixel.
  28367. This only has an effect if the image has an alpha channel and if the
  28368. given co-ordinates are inside the image's boundary.
  28369. The multiplier must be in the range 0 to 1.0, and the current alpha
  28370. at the given co-ordinates will be multiplied by this value.
  28371. @see getAlphaAt, setPixelAt
  28372. */
  28373. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28374. /** Changes the overall opacity of the image.
  28375. This will multiply the alpha value of each pixel in the image by the given
  28376. amount (limiting the resulting alpha values between 0 and 255). This allows
  28377. you to make an image more or less transparent.
  28378. If the image doesn't have an alpha channel, this won't have any effect.
  28379. */
  28380. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28381. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28382. */
  28383. virtual void desaturate();
  28384. /** Locks some of the pixels in the image so they can be read and written to.
  28385. This returns a pointer to some memory containing the pixels in the given
  28386. rectangle. It also returns values for the line and pixel stride used within
  28387. the data. The format of the pixel data is the same as that of this image.
  28388. When you've finished reading and changing the data, you must call
  28389. releasePixelDataReadWrite() to give the pixels back to the image.
  28390. For images that are stored in memory, this method may just return a direct
  28391. pointer to the image's data, but other types of image may be stored elsewhere,
  28392. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28393. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28394. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28395. instead.
  28396. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28397. */
  28398. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28399. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28400. */
  28401. virtual void releasePixelDataReadWrite (void* sourceData);
  28402. /** Locks some of the pixels in the image so they can be read.
  28403. This returns a pointer to some memory containing the pixels in the given
  28404. rectangle. It also returns values for the line and pixel stride used within
  28405. the data. The format of the pixel data is the same as that of this image.
  28406. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28407. to let the image free the memory if necessary.
  28408. For images that are stored in memory, this method may just return a direct
  28409. pointer to the image's data, but other types of image may be stored elsewhere,
  28410. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28411. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28412. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28413. instead.
  28414. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28415. */
  28416. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28417. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28418. */
  28419. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28420. /** Copies some pixel values to a rectangle of the image.
  28421. The format of the pixel data must match that of the image itself, and the
  28422. rectangle supplied must be within the image's bounds.
  28423. */
  28424. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28425. const uint8* sourcePixelData, int sourceLineStride);
  28426. /** Copies a section of the image to somewhere else within itself.
  28427. */
  28428. virtual void moveImageSection (int destX, int destY,
  28429. int sourceX, int sourceY,
  28430. int width, int height);
  28431. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28432. of the image.
  28433. @param result the list that will have the area added to it
  28434. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28435. above this level will be considered opaque
  28436. */
  28437. void createSolidAreaMask (RectangleList& result,
  28438. const float alphaThreshold = 0.5f) const;
  28439. juce_UseDebuggingNewOperator
  28440. /** Creates a context suitable for drawing onto this image.
  28441. Don't call this method directly! It's used internally by the Graphics class.
  28442. */
  28443. virtual LowLevelGraphicsContext* createLowLevelContext();
  28444. protected:
  28445. const PixelFormat format;
  28446. const int imageWidth, imageHeight;
  28447. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28448. Image (const PixelFormat format,
  28449. const int imageWidth,
  28450. const int imageHeight);
  28451. int pixelStride, lineStride;
  28452. uint8* imageData;
  28453. private:
  28454. const Image& operator= (const Image&);
  28455. };
  28456. #endif // __JUCE_IMAGE_JUCEHEADER__
  28457. /********* End of inlined file: juce_Image.h *********/
  28458. /**
  28459. A Brush that fills areas with tiled repetitions of an image.
  28460. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28461. */
  28462. class JUCE_API ImageBrush : public Brush
  28463. {
  28464. public:
  28465. /* Creates an image brush, ready for use in Graphics::setBrush().
  28466. (x, y) is an anchor point for the top-left of the image
  28467. A reference to the image passed in will be kept, so don't delete
  28468. it within the lifetime of this object
  28469. */
  28470. ImageBrush (Image* const image,
  28471. const int anchorX,
  28472. const int anchorY,
  28473. const float opacity) throw();
  28474. /** Destructor. */
  28475. ~ImageBrush() throw();
  28476. Brush* createCopy() const throw();
  28477. void applyTransform (const AffineTransform& transform) throw();
  28478. void multiplyOpacity (const float multiple) throw();
  28479. bool isInvisible() const throw();
  28480. void paintPath (LowLevelGraphicsContext& context,
  28481. const Path& path, const AffineTransform& transform) throw();
  28482. void paintRectangle (LowLevelGraphicsContext& context,
  28483. int x, int y, int w, int h) throw();
  28484. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28485. const Image& alphaChannelImage, int imageX, int imageY,
  28486. int x, int y, int w, int h) throw();
  28487. juce_UseDebuggingNewOperator
  28488. protected:
  28489. Image* image;
  28490. int anchorX, anchorY;
  28491. float opacity;
  28492. private:
  28493. ImageBrush (const ImageBrush&);
  28494. const ImageBrush& operator= (const ImageBrush&);
  28495. void getStartXY (int& x, int& y) const throw();
  28496. };
  28497. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28498. /********* End of inlined file: juce_ImageBrush.h *********/
  28499. #endif
  28500. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28501. #endif
  28502. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28503. #endif
  28504. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28505. #endif
  28506. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28507. #endif
  28508. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28509. #endif
  28510. #ifndef __JUCE_FONT_JUCEHEADER__
  28511. #endif
  28512. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28513. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28514. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28515. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28516. /**
  28517. An glyph from a particular font, with a particular size, style,
  28518. typeface and position.
  28519. @see GlyphArrangement, Font
  28520. */
  28521. class JUCE_API PositionedGlyph
  28522. {
  28523. public:
  28524. /** Returns the character the glyph represents. */
  28525. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28526. /** Checks whether the glyph is actually empty. */
  28527. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28528. /** Returns the position of the glyph's left-hand edge. */
  28529. float getLeft() const throw() { return x; }
  28530. /** Returns the position of the glyph's right-hand edge. */
  28531. float getRight() const throw() { return x + w; }
  28532. /** Returns the y position of the glyph's baseline. */
  28533. float getBaselineY() const throw() { return y; }
  28534. /** Returns the y position of the top of the glyph. */
  28535. float getTop() const throw() { return y - fontAscent; }
  28536. /** Returns the y position of the bottom of the glyph. */
  28537. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28538. /** Shifts the glyph's position by a relative amount. */
  28539. void moveBy (const float deltaX,
  28540. const float deltaY) throw();
  28541. /** Draws the glyph into a graphics context. */
  28542. void draw (const Graphics& g) const throw();
  28543. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28544. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28545. /** Returns the path for this glyph.
  28546. @param path the glyph's outline will be appended to this path
  28547. */
  28548. void createPath (Path& path) const throw();
  28549. /** Checks to see if a point lies within this glyph. */
  28550. bool hitTest (float x, float y) const throw();
  28551. juce_UseDebuggingNewOperator
  28552. private:
  28553. friend class GlyphArrangement;
  28554. float x, y, w;
  28555. float fontHeight, fontAscent, fontHorizontalScale;
  28556. bool isUnderlined;
  28557. const TypefaceGlyphInfo* glyphInfo;
  28558. PositionedGlyph() throw();
  28559. };
  28560. /**
  28561. A set of glyphs, each with a position.
  28562. You can create a GlyphArrangement, text to it and then draw it onto a
  28563. graphics context. It's used internally by the text methods in the
  28564. Graphics class, but can be used directly if more control is needed.
  28565. @see Font, PositionedGlyph
  28566. */
  28567. class JUCE_API GlyphArrangement
  28568. {
  28569. public:
  28570. /** Creates an empty arrangement. */
  28571. GlyphArrangement() throw();
  28572. /** Takes a copy of another arrangement. */
  28573. GlyphArrangement (const GlyphArrangement& other) throw();
  28574. /** Copies another arrangement onto this one.
  28575. To add another arrangement without clearing this one, use addGlyphArrangement().
  28576. */
  28577. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28578. /** Destructor. */
  28579. ~GlyphArrangement() throw();
  28580. /** Returns the total number of glyphs in the arrangement. */
  28581. int getNumGlyphs() const throw() { return numGlyphs; }
  28582. /** Returns one of the glyphs from the arrangement.
  28583. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28584. careful not to pass an out-of-range index here, as it
  28585. doesn't do any bounds-checking.
  28586. */
  28587. PositionedGlyph& getGlyph (const int index) const throw();
  28588. /** Clears all text from the arrangement and resets it.
  28589. */
  28590. void clear() throw();
  28591. /** Appends a line of text to the arrangement.
  28592. This will add the text as a single line, where x is the left-hand edge of the
  28593. first character, and y is the position for the text's baseline.
  28594. If the text contains new-lines or carriage-returns, this will ignore them - use
  28595. addJustifiedText() to add multi-line arrangements.
  28596. */
  28597. void addLineOfText (const Font& font,
  28598. const String& text,
  28599. const float x,
  28600. const float y) throw();
  28601. /** Adds a line of text, truncating it if it's wider than a specified size.
  28602. This is the same as addLineOfText(), but if the line's width exceeds the value
  28603. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  28604. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  28605. */
  28606. void addCurtailedLineOfText (const Font& font,
  28607. const String& text,
  28608. float x,
  28609. const float y,
  28610. const float maxWidthPixels,
  28611. const bool useEllipsis) throw();
  28612. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  28613. This will add text to the arrangement, breaking it into new lines either where there
  28614. is a new-line or carriage-return character in the text, or where a line's width
  28615. exceeds the value set in maxLineWidth.
  28616. Each line that is added will be laid out using the flags set in horizontalLayout, so
  28617. the lines can be left- or right-justified, or centred horizontally in the space
  28618. between x and (x + maxLineWidth).
  28619. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  28620. lines will be placed below it, separated by a distance of font.getHeight().
  28621. */
  28622. void addJustifiedText (const Font& font,
  28623. const String& text,
  28624. float x, float y,
  28625. const float maxLineWidth,
  28626. const Justification& horizontalLayout) throw();
  28627. /** Tries to fit some text withing a given space.
  28628. This does its best to make the given text readable within the specified rectangle,
  28629. so it useful for labelling things.
  28630. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  28631. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  28632. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  28633. it's been truncated.
  28634. A Justification parameter lets you specify how the text is laid out within the rectangle,
  28635. both horizontally and vertically.
  28636. @see Graphics::drawFittedText
  28637. */
  28638. void addFittedText (const Font& font,
  28639. const String& text,
  28640. float x, float y,
  28641. float width, float height,
  28642. const Justification& layout,
  28643. int maximumLinesToUse,
  28644. const float minimumHorizontalScale = 0.7f) throw();
  28645. /** Appends another glyph arrangement to this one. */
  28646. void addGlyphArrangement (const GlyphArrangement& other) throw();
  28647. /** Draws this glyph arrangement to a graphics context.
  28648. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  28649. method, which renders the glyphs as filled vectors.
  28650. */
  28651. void draw (const Graphics& g) const throw();
  28652. /** Draws this glyph arrangement to a graphics context.
  28653. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  28654. method for non-transformed arrangements.
  28655. */
  28656. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28657. /** Converts the set of glyphs into a path.
  28658. @param path the glyphs' outlines will be appended to this path
  28659. */
  28660. void createPath (Path& path) const throw();
  28661. /** Looks for a glyph that contains the given co-ordinate.
  28662. @returns the index of the glyph, or -1 if none were found.
  28663. */
  28664. int findGlyphIndexAt (float x, float y) const throw();
  28665. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  28666. @param startIndex the first glyph to test
  28667. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  28668. startIndex will be included
  28669. @param left on return, the leftmost co-ordinate of the rectangle
  28670. @param top on return, the top co-ordinate of the rectangle
  28671. @param right on return, the rightmost co-ordinate of the rectangle
  28672. @param bottom on return, the bottom co-ordinate of the rectangle
  28673. @param includeWhitespace if true, the extent of any whitespace characters will also
  28674. be taken into account
  28675. */
  28676. void getBoundingBox (int startIndex,
  28677. int numGlyphs,
  28678. float& left,
  28679. float& top,
  28680. float& right,
  28681. float& bottom,
  28682. const bool includeWhitespace) const throw();
  28683. /** Shifts a set of glyphs by a given amount.
  28684. @param startIndex the first glyph to transform
  28685. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  28686. startIndex will be used
  28687. @param deltaX the amount to add to their x-positions
  28688. @param deltaY the amount to add to their y-positions
  28689. */
  28690. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  28691. const float deltaX,
  28692. const float deltaY) throw();
  28693. /** Removes a set of glyphs from the arrangement.
  28694. @param startIndex the first glyph to remove
  28695. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  28696. startIndex will be deleted
  28697. */
  28698. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  28699. /** Expands or compresses a set of glyphs horizontally.
  28700. @param startIndex the first glyph to transform
  28701. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  28702. startIndex will be used
  28703. @param horizontalScaleFactor how much to scale their horizontal width by
  28704. */
  28705. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  28706. const float horizontalScaleFactor) throw();
  28707. /** Justifies a set of glyphs within a given space.
  28708. This moves the glyphs as a block so that the whole thing is located within the
  28709. given rectangle with the specified layout.
  28710. If the Justification::horizontallyJustified flag is specified, each line will
  28711. be stretched out to fill the specified width.
  28712. */
  28713. void justifyGlyphs (const int startIndex, const int numGlyphs,
  28714. const float x,
  28715. const float y,
  28716. const float width,
  28717. const float height,
  28718. const Justification& justification) throw();
  28719. juce_UseDebuggingNewOperator
  28720. private:
  28721. int numGlyphs, numAllocated;
  28722. PositionedGlyph* glyphs;
  28723. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  28724. void removeLast() throw();
  28725. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  28726. void incGlyphRefCount (const int index) const throw();
  28727. void decGlyphRefCount (const int index) const throw();
  28728. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  28729. };
  28730. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28731. /********* End of inlined file: juce_GlyphArrangement.h *********/
  28732. #endif
  28733. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28734. /********* Start of inlined file: juce_TextLayout.h *********/
  28735. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28736. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  28737. class Graphics;
  28738. /**
  28739. A laid-out arrangement of text.
  28740. You can add text in different fonts to a TextLayout object, then call its
  28741. layout() method to word-wrap it into lines. The layout can then be drawn
  28742. using a graphics context.
  28743. It's handy if you've got a message to display, because you can format it,
  28744. measure the extent of the layout, and then create a suitably-sized window
  28745. to show it in.
  28746. @see Font, Graphics::drawFittedText, GlyphArrangement
  28747. */
  28748. class JUCE_API TextLayout
  28749. {
  28750. public:
  28751. /** Creates an empty text layout.
  28752. Text can then be appended using the appendText() method.
  28753. */
  28754. TextLayout() throw();
  28755. /** Creates a copy of another layout object. */
  28756. TextLayout (const TextLayout& other) throw();
  28757. /** Creates a text layout from an initial string and font. */
  28758. TextLayout (const String& text, const Font& font) throw();
  28759. /** Destructor. */
  28760. ~TextLayout() throw();
  28761. /** Copies another layout onto this one. */
  28762. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  28763. /** Clears the layout, removing all its text. */
  28764. void clear() throw();
  28765. /** Adds a string to the end of the arrangement.
  28766. The string will be broken onto new lines wherever it contains
  28767. carriage-returns or linefeeds. After adding it, you can call layout()
  28768. to wrap long lines into a paragraph and justify it.
  28769. */
  28770. void appendText (const String& textToAppend,
  28771. const Font& fontToUse) throw();
  28772. /** Replaces all the text with a new string.
  28773. This is equivalent to calling clear() followed by appendText().
  28774. */
  28775. void setText (const String& newText,
  28776. const Font& fontToUse) throw();
  28777. /** Breaks the text up to form a paragraph with the given width.
  28778. @param maximumWidth any text wider than this will be split
  28779. across multiple lines
  28780. @param justification how the lines are to be laid-out horizontally
  28781. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  28782. width that keeps all the lines of text at a
  28783. similar length - this is good when you're displaying
  28784. a short message and don't want it to get split
  28785. onto two lines with only a couple of words on
  28786. the second line, which looks untidy.
  28787. */
  28788. void layout (int maximumWidth,
  28789. const Justification& justification,
  28790. const bool attemptToBalanceLineLengths) throw();
  28791. /** Returns the overall width of the entire text layout. */
  28792. int getWidth() const throw();
  28793. /** Returns the overall height of the entire text layout. */
  28794. int getHeight() const throw();
  28795. /** Returns the total number of lines of text. */
  28796. int getNumLines() const throw() { return totalLines; }
  28797. /** Returns the width of a particular line of text.
  28798. @param lineNumber the line, from 0 to (getNumLines() - 1)
  28799. */
  28800. int getLineWidth (const int lineNumber) const throw();
  28801. /** Renders the text at a specified position using a graphics context.
  28802. */
  28803. void draw (Graphics& g,
  28804. const int topLeftX,
  28805. const int topLeftY) const throw();
  28806. /** Renders the text within a specified rectangle using a graphics context.
  28807. The justification flags dictate how the block of text should be positioned
  28808. within the rectangle.
  28809. */
  28810. void drawWithin (Graphics& g,
  28811. int x, int y, int w, int h,
  28812. const Justification& layoutFlags) const throw();
  28813. juce_UseDebuggingNewOperator
  28814. private:
  28815. VoidArray tokens;
  28816. int totalLines;
  28817. };
  28818. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  28819. /********* End of inlined file: juce_TextLayout.h *********/
  28820. #endif
  28821. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  28822. #endif
  28823. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28824. /********* Start of inlined file: juce_EdgeTable.h *********/
  28825. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  28826. #define __JUCE_EDGETABLE_JUCEHEADER__
  28827. class Path;
  28828. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  28829. /**
  28830. A table of horizontal scan-line segments - used for rasterising Paths.
  28831. @see Path, Graphics
  28832. */
  28833. class JUCE_API EdgeTable
  28834. {
  28835. public:
  28836. /** Indicates the quality at which the edge table should be generated.
  28837. Higher values will have better quality anti-aliasing, but will take
  28838. longer to generate the edge table and to render it.
  28839. */
  28840. enum OversamplingLevel
  28841. {
  28842. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  28843. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  28844. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  28845. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  28846. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  28847. normal user-interface use. */
  28848. };
  28849. /** Creates an empty edge table ready to have paths added.
  28850. A table is created with a fixed vertical size, and only sections of paths
  28851. which lie within their range will be added to the table.
  28852. @param topY the lowest y co-ordinate that the table can contain
  28853. @param height the number of horizontal lines it can contain
  28854. @param verticalOversampling the amount of oversampling used for anti-aliasing
  28855. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  28856. worth changing this except for very special purposes
  28857. */
  28858. EdgeTable (const int topY,
  28859. const int height,
  28860. const OversamplingLevel verticalOversampling = Oversampling_4times,
  28861. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  28862. /** Creates a copy of another edge table. */
  28863. EdgeTable (const EdgeTable& other) throw();
  28864. /** Copies from another edge table. */
  28865. const EdgeTable& operator= (const EdgeTable& other) throw();
  28866. /** Destructor. */
  28867. ~EdgeTable() throw();
  28868. /** Adds edges to the table for a path.
  28869. This will add horizontal lines to the edge table for any parts of the path
  28870. which lie within the vertical bounds for which this table was created.
  28871. @param path the path to add
  28872. @param transform an optional transform to apply to the path while it's
  28873. being added
  28874. */
  28875. void addPath (const Path& path,
  28876. const AffineTransform& transform) throw();
  28877. /** Reduces the amount of space the table has allocated.
  28878. This will shrink the table down to use as little memory as possible - useful for
  28879. read-only tables that get stored and re-used for rendering.
  28880. */
  28881. void optimiseTable() throw();
  28882. /** Iterates the lines in the table, for rendering.
  28883. This function will iterate each line in the table, and call a user-defined class
  28884. to render each pixel or continuous line of pixels that the table contains.
  28885. @param iterationCallback this templated class must contain the following methods:
  28886. @code
  28887. inline void setEdgeTableYPos (int y);
  28888. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  28889. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  28890. @endcode
  28891. (these don't necessarily have to be 'const', but it might help it go faster)
  28892. @param clipLeft the left-hand edge of the rectangle which should be iterated
  28893. @param clipTop the top edge of the rectangle which should be iterated
  28894. @param clipRight the right-hand edge of the rectangle which should be iterated
  28895. @param clipBottom the bottom edge of the rectangle which should be iterated
  28896. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  28897. */
  28898. template <class EdgeTableIterationCallback>
  28899. void iterate (EdgeTableIterationCallback& iterationCallback,
  28900. const int clipLeft,
  28901. int clipTop,
  28902. const int clipRight,
  28903. int clipBottom,
  28904. const int subPixelXOffset) const
  28905. {
  28906. if (clipTop < top)
  28907. clipTop = top;
  28908. if (clipBottom > top + height)
  28909. clipBottom = top + height;
  28910. const int* singleLine = table + lineStrideElements
  28911. * ((clipTop - top) << (int) oversampling);
  28912. int mergedLineAllocation = 128;
  28913. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  28914. int* mergedLine = (int*) temp.getData();
  28915. const int timesOverSampling = 1 << (int) oversampling;
  28916. for (int y = clipTop; y < clipBottom; ++y)
  28917. {
  28918. int numMergedPoints = 0;
  28919. // sort all the oversampled lines into a single merged line ready to draw..
  28920. for (int over = timesOverSampling; --over >= 0;)
  28921. {
  28922. const int* l = singleLine;
  28923. singleLine += lineStrideElements;
  28924. int num = *l;
  28925. jassert (num >= 0);
  28926. if (num > 0)
  28927. {
  28928. if (numMergedPoints + num >= mergedLineAllocation)
  28929. {
  28930. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  28931. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  28932. mergedLine = (int*) temp.getData();
  28933. }
  28934. while (--num >= 0)
  28935. {
  28936. const int x = *++l;
  28937. const int winding = *++l;
  28938. int n = numMergedPoints << 1;
  28939. while (n > 0)
  28940. {
  28941. const int cx = mergedLine [n - 2];
  28942. if (cx <= x)
  28943. break;
  28944. mergedLine [n] = cx;
  28945. --n;
  28946. mergedLine [n + 2] = mergedLine [n];
  28947. --n;
  28948. }
  28949. mergedLine [n] = x;
  28950. mergedLine [n + 1] = winding;
  28951. ++numMergedPoints;
  28952. }
  28953. }
  28954. }
  28955. if (--numMergedPoints > 0)
  28956. {
  28957. const int* line = mergedLine;
  28958. int x = subPixelXOffset + *line;
  28959. int level = *++line;
  28960. int levelAccumulator = 0;
  28961. iterationCallback.setEdgeTableYPos (y);
  28962. while (--numMergedPoints >= 0)
  28963. {
  28964. const int endX = subPixelXOffset + *++line;
  28965. jassert (endX >= x);
  28966. const int absLevel = abs (level);
  28967. int endOfRun = (endX >> 8);
  28968. if (endOfRun == (x >> 8))
  28969. {
  28970. // small segment within the same pixel, so just save it for the next
  28971. // time round..
  28972. levelAccumulator += (endX - x) * absLevel;
  28973. }
  28974. else
  28975. {
  28976. // plot the fist pixel of this segment, including any accumulated
  28977. // levels from smaller segments that haven't been drawn yet
  28978. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  28979. levelAccumulator >>= 8;
  28980. if (levelAccumulator > 0xff)
  28981. levelAccumulator = 0xff;
  28982. x >>= 8;
  28983. if (x >= clipRight)
  28984. {
  28985. levelAccumulator = 0;
  28986. break;
  28987. }
  28988. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  28989. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  28990. if (++x >= clipRight)
  28991. {
  28992. levelAccumulator = 0;
  28993. break;
  28994. }
  28995. // if there's a segment of solid pixels, do it all in one go..
  28996. if (absLevel > 0 && endOfRun > x)
  28997. {
  28998. if (x < clipLeft)
  28999. x = clipLeft;
  29000. if (endOfRun > clipRight)
  29001. endOfRun = clipRight;
  29002. const int numPix = endOfRun - x;
  29003. if (numPix > 0)
  29004. iterationCallback.handleEdgeTableLine (x, numPix,
  29005. jmin (absLevel, 0xff));
  29006. }
  29007. // save the bit at the end to be drawn next time round the loop.
  29008. levelAccumulator = (endX & 0xff) * absLevel;
  29009. }
  29010. level += *++line;
  29011. x = endX;
  29012. }
  29013. if (levelAccumulator > 0)
  29014. {
  29015. levelAccumulator >>= 8;
  29016. if (levelAccumulator > 0xff)
  29017. levelAccumulator = 0xff;
  29018. x >>= 8;
  29019. if (x >= clipLeft && x < clipRight)
  29020. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29021. }
  29022. }
  29023. }
  29024. }
  29025. juce_UseDebuggingNewOperator
  29026. private:
  29027. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29028. int* table;
  29029. int top, height, maxEdgesPerLine, lineStrideElements;
  29030. OversamplingLevel oversampling;
  29031. // this will assume that the y co-ord is within bounds, and will avoid checking
  29032. // this for speed.
  29033. void addEdgePoint (const int x, const int y, const int winding) throw();
  29034. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29035. };
  29036. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29037. /********* End of inlined file: juce_EdgeTable.h *********/
  29038. #endif
  29039. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29040. #endif
  29041. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29042. #endif
  29043. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29044. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29045. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29046. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29047. /**
  29048. Interface class for graphics context objects, used internally by the Graphics class.
  29049. Users are not supposed to create instances of this class directly - do your drawing
  29050. via the Graphics object instead.
  29051. It's a base class for different types of graphics context, that may perform software-based
  29052. or OS-accelerated rendering.
  29053. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29054. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29055. context.
  29056. */
  29057. class JUCE_API LowLevelGraphicsContext
  29058. {
  29059. protected:
  29060. LowLevelGraphicsContext();
  29061. public:
  29062. virtual ~LowLevelGraphicsContext();
  29063. /** Returns true if this device is vector-based, e.g. a printer. */
  29064. virtual bool isVectorDevice() const = 0;
  29065. /** Moves the origin to a new position.
  29066. The co-ords are relative to the current origin, and indicate the new position
  29067. of (0, 0).
  29068. */
  29069. virtual void setOrigin (int x, int y) = 0;
  29070. /** Cliping co-ords are relative to the origin. */
  29071. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29072. /** Cliping co-ords are relative to the origin. */
  29073. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29074. /** Cliping co-ords are relative to the origin. */
  29075. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29076. virtual void saveState() = 0;
  29077. virtual void restoreState() = 0;
  29078. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29079. virtual const Rectangle getClipBounds() const = 0;
  29080. virtual bool isClipEmpty() const = 0;
  29081. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29082. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29083. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29084. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29085. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29086. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29087. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29088. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29089. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29090. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29091. virtual void blendImage (const Image& sourceImage,
  29092. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29093. float alpha) = 0;
  29094. virtual void blendImageRescaling (const Image& sourceImage,
  29095. int destX, int destY, int destW, int destH,
  29096. int sourceX, int sourceY, int sourceW, int sourceH,
  29097. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29098. virtual void blendImageWarping (const Image& sourceImage,
  29099. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29100. const AffineTransform& transform,
  29101. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29102. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29103. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29104. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29105. };
  29106. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29107. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29108. #endif
  29109. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29110. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29111. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29112. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29113. /**
  29114. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29115. into a PostScript document.
  29116. */
  29117. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29118. {
  29119. public:
  29120. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29121. const String& documentTitle,
  29122. const int totalWidth,
  29123. const int totalHeight);
  29124. ~LowLevelGraphicsPostScriptRenderer();
  29125. bool isVectorDevice() const;
  29126. void setOrigin (int x, int y);
  29127. bool reduceClipRegion (int x, int y, int w, int h);
  29128. bool reduceClipRegion (const RectangleList& clipRegion);
  29129. void excludeClipRegion (int x, int y, int w, int h);
  29130. void saveState();
  29131. void restoreState();
  29132. bool clipRegionIntersects (int x, int y, int w, int h);
  29133. const Rectangle getClipBounds() const;
  29134. bool isClipEmpty() const;
  29135. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29136. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29137. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29138. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29139. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29140. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29141. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29142. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29143. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29144. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29145. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29146. int sourceX, int sourceY, float alpha);
  29147. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29148. int sourceX, int sourceY, int sourceW, int sourceH,
  29149. float alpha, const Graphics::ResamplingQuality quality);
  29150. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29151. const AffineTransform& transform,
  29152. float alpha, const Graphics::ResamplingQuality quality);
  29153. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29154. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29155. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29156. juce_UseDebuggingNewOperator
  29157. protected:
  29158. OutputStream& out;
  29159. RectangleList* clip;
  29160. int totalWidth, totalHeight, xOffset, yOffset;
  29161. bool needToClip;
  29162. Colour lastColour;
  29163. struct SavedState
  29164. {
  29165. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29166. ~SavedState();
  29167. RectangleList* clip;
  29168. const int xOffset, yOffset;
  29169. private:
  29170. SavedState (const SavedState&);
  29171. const SavedState& operator= (const SavedState&);
  29172. };
  29173. OwnedArray <SavedState> stateStack;
  29174. void writeClip();
  29175. void writeColour (const Colour& colour);
  29176. void writePath (const Path& path) const;
  29177. void writeXY (const float x, const float y) const;
  29178. void writeTransform (const AffineTransform& trans) const;
  29179. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29180. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29181. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29182. };
  29183. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29184. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29185. #endif
  29186. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29187. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29188. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29189. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29190. /**
  29191. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29192. its rendering in memory.
  29193. User code is not supposed to create instances of this class directly - do all your
  29194. rendering via the Graphics class instead.
  29195. */
  29196. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29197. {
  29198. public:
  29199. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29200. ~LowLevelGraphicsSoftwareRenderer();
  29201. bool isVectorDevice() const;
  29202. void setOrigin (int x, int y);
  29203. bool reduceClipRegion (int x, int y, int w, int h);
  29204. bool reduceClipRegion (const RectangleList& clipRegion);
  29205. void excludeClipRegion (int x, int y, int w, int h);
  29206. void saveState();
  29207. void restoreState();
  29208. bool clipRegionIntersects (int x, int y, int w, int h);
  29209. const Rectangle getClipBounds() const;
  29210. bool isClipEmpty() const;
  29211. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29212. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29213. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29214. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29215. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29216. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29217. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29218. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29219. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29220. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29221. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29222. int sourceX, int sourceY, float alpha);
  29223. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29224. int sourceX, int sourceY, int sourceW, int sourceH,
  29225. float alpha, const Graphics::ResamplingQuality quality);
  29226. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29227. const AffineTransform& transform,
  29228. float alpha, const Graphics::ResamplingQuality quality);
  29229. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29230. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29231. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29232. RectangleList* getRawClipRegion() throw() { return clip; }
  29233. juce_UseDebuggingNewOperator
  29234. protected:
  29235. Image& image;
  29236. RectangleList* clip;
  29237. int xOffset, yOffset;
  29238. struct SavedState
  29239. {
  29240. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29241. ~SavedState();
  29242. RectangleList* clip;
  29243. const int xOffset, yOffset;
  29244. private:
  29245. SavedState (const SavedState&);
  29246. const SavedState& operator= (const SavedState&);
  29247. };
  29248. OwnedArray <SavedState> stateStack;
  29249. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29250. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29251. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29252. const Path& path, const AffineTransform& transform,
  29253. int& x, int& y, int& w, int& h) const;
  29254. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29255. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29256. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29257. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29258. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29259. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29260. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29261. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29262. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29263. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29264. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29265. float alpha);
  29266. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29267. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29268. const AffineTransform& transform,
  29269. float alpha, const Graphics::ResamplingQuality quality);
  29270. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29271. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29272. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29273. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29274. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29275. };
  29276. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29277. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29278. #endif
  29279. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29280. #endif
  29281. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29282. #endif
  29283. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29284. #endif
  29285. #ifndef __JUCE_LINE_JUCEHEADER__
  29286. #endif
  29287. #ifndef __JUCE_PATH_JUCEHEADER__
  29288. #endif
  29289. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29290. /********* Start of inlined file: juce_PathIterator.h *********/
  29291. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29292. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29293. /**
  29294. Flattens a Path object into a series of straight-line sections.
  29295. Use one of these to iterate through a Path object, and it will convert
  29296. all the curves into line sections so it's easy to render or perform
  29297. geometric operations on.
  29298. @see Path
  29299. */
  29300. class JUCE_API PathFlatteningIterator
  29301. {
  29302. public:
  29303. /** Creates a PathFlatteningIterator.
  29304. After creation, use the next() method to initialise the fields in the
  29305. object with the first line's position.
  29306. @param path the path to iterate along
  29307. @param transform a transform to apply to each point in the path being iterated
  29308. @param tolerence the amount by which the curves are allowed to deviate from the
  29309. lines into which they are being broken down - a higher tolerence
  29310. is a bit faster, but less smooth.
  29311. */
  29312. PathFlatteningIterator (const Path& path,
  29313. const AffineTransform& transform = AffineTransform::identity,
  29314. float tolerence = 9.0f) throw();
  29315. /** Destructor. */
  29316. ~PathFlatteningIterator() throw();
  29317. /** Fetches the next line segment from the path.
  29318. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29319. so that they describe the new line segment.
  29320. @returns false when there are no more lines to fetch.
  29321. */
  29322. bool next() throw();
  29323. /** The x position of the start of the current line segment. */
  29324. float x1;
  29325. /** The y position of the start of the current line segment. */
  29326. float y1;
  29327. /** The x position of the end of the current line segment. */
  29328. float x2;
  29329. /** The y position of the end of the current line segment. */
  29330. float y2;
  29331. /** Indicates whether the current line segment is closing a sub-path.
  29332. If the current line is the one that connects the end of a sub-path
  29333. back to the start again, this will be true.
  29334. */
  29335. bool closesSubPath;
  29336. /** The index of the current line within the current sub-path.
  29337. E.g. you can use this to see whether the line is the first one in the
  29338. subpath by seeing if it's 0.
  29339. */
  29340. int subPathIndex;
  29341. /** Returns true if the current segment is the last in the current sub-path. */
  29342. bool isLastInSubpath() const throw() { return stackPos == stackBase; }
  29343. juce_UseDebuggingNewOperator
  29344. private:
  29345. const Path& path;
  29346. const AffineTransform transform;
  29347. float* points;
  29348. float tolerence, subPathCloseX, subPathCloseY;
  29349. bool isIdentityTransform;
  29350. float* stackBase;
  29351. float* stackPos;
  29352. int index, stackSize;
  29353. PathFlatteningIterator (const PathFlatteningIterator&);
  29354. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29355. };
  29356. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29357. /********* End of inlined file: juce_PathIterator.h *********/
  29358. #endif
  29359. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29360. #endif
  29361. #ifndef __JUCE_POINT_JUCEHEADER__
  29362. #endif
  29363. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29364. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29365. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29366. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29367. /**
  29368. A rectangle whose co-ordinates can be defined in terms of absolute or
  29369. proportional distances.
  29370. Designed mainly for storing component positions, this gives you a lot of
  29371. control over how each co-ordinate is stored, either as an absolute position,
  29372. or as a proportion of the size of a parent rectangle.
  29373. It also allows you to define the anchor points by which the rectangle is
  29374. positioned, so for example you could specify that the top right of the
  29375. rectangle should be an absolute distance from its parent's bottom-right corner.
  29376. This object can be stored as a string, which takes the form "x y w h", including
  29377. symbols like '%' and letters to indicate the anchor point. See its toString()
  29378. method for more info.
  29379. Example usage:
  29380. @code
  29381. class MyComponent
  29382. {
  29383. void resized()
  29384. {
  29385. // this will set the child component's x to be 20% of our width, its y
  29386. // to be 30, its width to be 150, and its height to be 50% of our
  29387. // height..
  29388. const PositionedRectangle pos1 ("20% 30 150 50%");
  29389. pos1.applyToComponent (*myChildComponent1);
  29390. // this will inset the child component with a gap of 10 pixels
  29391. // around each of its edges..
  29392. const PositionedRectangle pos2 ("10 10 20M 20M");
  29393. pos2.applyToComponent (*myChildComponent2);
  29394. }
  29395. };
  29396. @endcode
  29397. */
  29398. class JUCE_API PositionedRectangle
  29399. {
  29400. public:
  29401. /** Creates an empty rectangle with all co-ordinates set to zero.
  29402. The default anchor point is top-left; the default
  29403. */
  29404. PositionedRectangle() throw();
  29405. /** Initialises a PositionedRectangle from a saved string version.
  29406. The string must be in the format generated by toString().
  29407. */
  29408. PositionedRectangle (const String& stringVersion) throw();
  29409. /** Creates a copy of another PositionedRectangle. */
  29410. PositionedRectangle (const PositionedRectangle& other) throw();
  29411. /** Copies another PositionedRectangle. */
  29412. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29413. /** Destructor. */
  29414. ~PositionedRectangle() throw();
  29415. /** Returns a string version of this position, from which it can later be
  29416. re-generated.
  29417. The format is four co-ordinates, "x y w h".
  29418. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29419. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29420. as a percentage, e.g. "80%".
  29421. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29422. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29423. the parent's right-hand edge.
  29424. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29425. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29426. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29427. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29428. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29429. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29430. has "c" appended to it. So "-50Rc" would mean that this component's
  29431. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29432. this component's centre should be placed 40% across the parent's width.
  29433. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29434. the number has "M" appended to it.
  29435. To reload a stored string, use the constructor that takes a string parameter.
  29436. */
  29437. const String toString() const throw();
  29438. /** Calculates the absolute position, given the size of the space that
  29439. it should go in.
  29440. This will work out any proportional distances and sizes relative to the
  29441. target rectangle, and will return the absolute position.
  29442. @see applyToComponent
  29443. */
  29444. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29445. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29446. */
  29447. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29448. double& x,
  29449. double& y,
  29450. double& width,
  29451. double& height) const throw();
  29452. /** This sets the bounds of the given component to this position.
  29453. This is equivalent to writing:
  29454. @code
  29455. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29456. @endcode
  29457. @see getRectangle, updateFromComponent
  29458. */
  29459. void applyToComponent (Component& comp) const throw();
  29460. /** Updates this object's co-ordinates to match the given rectangle.
  29461. This will set all co-ordinates based on the given rectangle, re-calculating
  29462. any proportional distances, and using the current anchor points.
  29463. So for example if the x co-ordinate mode is currently proportional, this will
  29464. re-calculate x based on the rectangle's relative position within the target
  29465. rectangle's width.
  29466. If the target rectangle's width or height are zero then it may not be possible
  29467. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29468. will not be changed.
  29469. */
  29470. void updateFrom (const Rectangle& newPosition,
  29471. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29472. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29473. */
  29474. void updateFromDouble (const double x, const double y,
  29475. const double width, const double height,
  29476. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29477. /** Updates this object's co-ordinates to match the bounds of this component.
  29478. This is equivalent to calling updateFrom() with the component's bounds and
  29479. it parent size.
  29480. If the component doesn't currently have a parent, then proportional co-ordinates
  29481. might not be updated because it would need to know the parent's size to do the
  29482. maths for this.
  29483. */
  29484. void updateFromComponent (const Component& comp) throw();
  29485. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29486. enum AnchorPoint
  29487. {
  29488. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29489. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29490. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29491. };
  29492. /** Specifies how an x or y co-ordinate should be interpreted. */
  29493. enum PositionMode
  29494. {
  29495. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29496. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29497. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29498. 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. */
  29499. };
  29500. /** Specifies how the width or height should be interpreted. */
  29501. enum SizeMode
  29502. {
  29503. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29504. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29505. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29506. };
  29507. /** Sets all options for all co-ordinates.
  29508. This requires a reference rectangle to be specified, because if you're changing any
  29509. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29510. the co-ordinates, and will need to know the parent size so it can calculate this.
  29511. */
  29512. void setModes (const AnchorPoint xAnchorMode,
  29513. const PositionMode xPositionMode,
  29514. const AnchorPoint yAnchorMode,
  29515. const PositionMode yPositionMode,
  29516. const SizeMode widthMode,
  29517. const SizeMode heightMode,
  29518. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29519. /** Returns the anchoring mode for the x co-ordinate.
  29520. To change any of the modes, use setModes().
  29521. */
  29522. AnchorPoint getAnchorPointX() const throw();
  29523. /** Returns the positioning mode for the x co-ordinate.
  29524. To change any of the modes, use setModes().
  29525. */
  29526. PositionMode getPositionModeX() const throw();
  29527. /** Returns the raw x co-ordinate.
  29528. If the x position mode is absolute, then this will be the absolute value. If it's
  29529. proportional, then this will be a fractional proportion, where 1.0 means the full
  29530. width of the parent space.
  29531. */
  29532. double getX() const throw() { return x; }
  29533. /** Sets the raw value of the x co-ordinate.
  29534. See getX() for the meaning of this value.
  29535. */
  29536. void setX (const double newX) throw() { x = newX; }
  29537. /** Returns the anchoring mode for the y co-ordinate.
  29538. To change any of the modes, use setModes().
  29539. */
  29540. AnchorPoint getAnchorPointY() const throw();
  29541. /** Returns the positioning mode for the y co-ordinate.
  29542. To change any of the modes, use setModes().
  29543. */
  29544. PositionMode getPositionModeY() const throw();
  29545. /** Returns the raw y co-ordinate.
  29546. If the y position mode is absolute, then this will be the absolute value. If it's
  29547. proportional, then this will be a fractional proportion, where 1.0 means the full
  29548. height of the parent space.
  29549. */
  29550. double getY() const throw() { return y; }
  29551. /** Sets the raw value of the y co-ordinate.
  29552. See getY() for the meaning of this value.
  29553. */
  29554. void setY (const double newY) throw() { y = newY; }
  29555. /** Returns the mode used to calculate the width.
  29556. To change any of the modes, use setModes().
  29557. */
  29558. SizeMode getWidthMode() const throw();
  29559. /** Returns the raw width value.
  29560. If the width mode is absolute, then this will be the absolute value. If the mode is
  29561. proportional, then this will be a fractional proportion, where 1.0 means the full
  29562. width of the parent space.
  29563. */
  29564. double getWidth() const throw() { return w; }
  29565. /** Sets the raw width value.
  29566. See getWidth() for the details about what this value means.
  29567. */
  29568. void setWidth (const double newWidth) throw() { w = newWidth; }
  29569. /** Returns the mode used to calculate the height.
  29570. To change any of the modes, use setModes().
  29571. */
  29572. SizeMode getHeightMode() const throw();
  29573. /** Returns the raw height value.
  29574. If the height mode is absolute, then this will be the absolute value. If the mode is
  29575. proportional, then this will be a fractional proportion, where 1.0 means the full
  29576. height of the parent space.
  29577. */
  29578. double getHeight() const throw() { return h; }
  29579. /** Sets the raw height value.
  29580. See getHeight() for the details about what this value means.
  29581. */
  29582. void setHeight (const double newHeight) throw() { h = newHeight; }
  29583. /** If the size and position are constance, and wouldn't be affected by changes
  29584. in the parent's size, then this will return true.
  29585. */
  29586. bool isPositionAbsolute() const throw();
  29587. /** Compares two objects. */
  29588. const bool operator== (const PositionedRectangle& other) const throw();
  29589. /** Compares two objects. */
  29590. const bool operator!= (const PositionedRectangle& other) const throw();
  29591. juce_UseDebuggingNewOperator
  29592. private:
  29593. double x, y, w, h;
  29594. uint8 xMode, yMode, wMode, hMode;
  29595. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  29596. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  29597. void decodePosString (const String& s, uint8& mode, double& value) throw();
  29598. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  29599. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  29600. const uint8 xMode, const uint8 wMode,
  29601. const int parentPos, const int parentSize) const throw();
  29602. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  29603. const uint8 xMode, const uint8 wMode,
  29604. const int parentPos, const int parentSize) const throw();
  29605. };
  29606. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29607. /********* End of inlined file: juce_PositionedRectangle.h *********/
  29608. #endif
  29609. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29610. #endif
  29611. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  29612. #endif
  29613. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29614. #endif
  29615. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29616. /********* Start of inlined file: juce_ImageCache.h *********/
  29617. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29618. #define __JUCE_IMAGECACHE_JUCEHEADER__
  29619. /**
  29620. A global cache of images that have been loaded from files or memory.
  29621. If you're loading an image and may need to use the image in more than one
  29622. place, this is used to allow the same image to be shared rather than loading
  29623. multiple copies into memory.
  29624. Another advantage is that after images are released, they will be kept in
  29625. memory for a few seconds before it is actually deleted, so if you're repeatedly
  29626. loading/deleting the same image, it'll reduce the chances of having to reload it
  29627. each time.
  29628. @see Image, ImageFileFormat
  29629. */
  29630. class JUCE_API ImageCache : private DeletedAtShutdown,
  29631. private Timer
  29632. {
  29633. public:
  29634. /** Loads an image from a file, (or just returns the image if it's already cached).
  29635. If the cache already contains an image that was loaded from this file,
  29636. that image will be returned. Otherwise, this method will try to load the
  29637. file, add it to the cache, and return it.
  29638. It's very important not to delete the image that is returned - instead use
  29639. the ImageCache::release() method.
  29640. Also, remember that the image returned is shared, so drawing into it might
  29641. affect other things that are using it!
  29642. @param file the file to try to load
  29643. @returns the image, or null if it there was an error loading it
  29644. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29645. */
  29646. static Image* getFromFile (const File& file);
  29647. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  29648. If the cache already contains an image that was loaded from this block of memory,
  29649. that image will be returned. Otherwise, this method will try to load the
  29650. file, add it to the cache, and return it.
  29651. It's very important not to delete the image that is returned - instead use
  29652. the ImageCache::release() method.
  29653. Also, remember that the image returned is shared, so drawing into it might
  29654. affect other things that are using it!
  29655. @param imageData the block of memory containing the image data
  29656. @param dataSize the data size in bytes
  29657. @returns the image, or null if it there was an error loading it
  29658. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29659. */
  29660. static Image* getFromMemory (const void* imageData,
  29661. const int dataSize);
  29662. /** Releases an image that was previously created by the ImageCache.
  29663. If an image has been returned by the getFromFile() or getFromMemory() methods,
  29664. it mustn't be deleted directly, but should be released with this method
  29665. instead.
  29666. @see getFromFile, getFromMemory
  29667. */
  29668. static void release (Image* const imageToRelease);
  29669. /** Checks whether an image is in the cache or not.
  29670. @returns true if the image is currently in the cache
  29671. */
  29672. static bool isImageInCache (Image* const imageToLookFor);
  29673. /** Increments the reference-count for a cached image.
  29674. If the image isn't in the cache, this method won't do anything.
  29675. */
  29676. static void incReferenceCount (Image* const image);
  29677. /** Checks the cache for an image with a particular hashcode.
  29678. If there's an image in the cache with this hashcode, it will be returned,
  29679. otherwise it will return zero.
  29680. If an image is returned, it must be released with the release() method
  29681. when no longer needed, to maintain the correct reference counts.
  29682. @param hashCode the hash code that would have been associated with the
  29683. image by addImageToCache()
  29684. @see addImageToCache
  29685. */
  29686. static Image* getFromHashCode (const int64 hashCode);
  29687. /** Adds an image to the cache with a user-defined hash-code.
  29688. After calling this, responsibilty for deleting the image will be taken
  29689. by the ImageCache.
  29690. The image will be initially be given a reference count of 1, so call
  29691. the release() method to delete it.
  29692. @param image the image to add
  29693. @param hashCode the hash-code to associate with it
  29694. @see getFromHashCode
  29695. */
  29696. static void addImageToCache (Image* const image,
  29697. const int64 hashCode);
  29698. /** Changes the amount of time before an unused image will be removed from the cache.
  29699. By default this is about 5 seconds.
  29700. */
  29701. static void setCacheTimeout (const int millisecs);
  29702. juce_UseDebuggingNewOperator
  29703. private:
  29704. CriticalSection lock;
  29705. VoidArray images;
  29706. ImageCache() throw();
  29707. ImageCache (const ImageCache&);
  29708. const ImageCache& operator= (const ImageCache&);
  29709. ~ImageCache();
  29710. void timerCallback();
  29711. };
  29712. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  29713. /********* End of inlined file: juce_ImageCache.h *********/
  29714. #endif
  29715. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29716. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  29717. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29718. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29719. /**
  29720. Represents a filter kernel to use in convoluting an image.
  29721. @see Image::applyConvolution
  29722. */
  29723. class JUCE_API ImageConvolutionKernel
  29724. {
  29725. public:
  29726. /** Creates an empty convulution kernel.
  29727. @param size the length of each dimension of the kernel, so e.g. if the size
  29728. is 5, it will create a 5x5 kernel
  29729. */
  29730. ImageConvolutionKernel (const int size) throw();
  29731. /** Destructor. */
  29732. ~ImageConvolutionKernel() throw();
  29733. /** Resets all values in the kernel to zero.
  29734. */
  29735. void clear() throw();
  29736. /** Sets the value of a specific cell in the kernel.
  29737. The x and y parameters must be in the range 0 < x < getKernelSize().
  29738. @see setOverallSum
  29739. */
  29740. void setKernelValue (const int x,
  29741. const int y,
  29742. const float value) throw();
  29743. /** Rescales all values in the kernel to make the total add up to a fixed value.
  29744. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  29745. */
  29746. void setOverallSum (const float desiredTotalSum) throw();
  29747. /** Multiplies all values in the kernel by a value. */
  29748. void rescaleAllValues (const float multiplier) throw();
  29749. /** Intialises the kernel for a gaussian blur.
  29750. @param blurRadius this may be larger or smaller than the kernel's actual
  29751. size but this will obviously be wasteful or clip at the
  29752. edges. Ideally the kernel should be just larger than
  29753. (blurRadius * 2).
  29754. */
  29755. void createGaussianBlur (const float blurRadius) throw();
  29756. /** Returns the size of the kernel.
  29757. E.g. if it's a 3x3 kernel, this returns 3.
  29758. */
  29759. int getKernelSize() const throw() { return size; }
  29760. /** Returns a 2-dimensional array of the kernel's values.
  29761. The size of each dimension of the array will be getKernelSize().
  29762. */
  29763. float** getValues() const throw() { return values; }
  29764. /** Applies the kernel to an image.
  29765. @param destImage the image that will receive the resultant convoluted pixels.
  29766. @param sourceImage an optional source image to read from - if this is 0, then the
  29767. destination image will be used as the source. If an image is
  29768. specified, it must be exactly the same size and type as the destination
  29769. image.
  29770. @param x the region of the image to apply the filter to
  29771. @param y the region of the image to apply the filter to
  29772. @param width the region of the image to apply the filter to
  29773. @param height the region of the image to apply the filter to
  29774. */
  29775. void applyToImage (Image& destImage,
  29776. const Image* sourceImage,
  29777. int x,
  29778. int y,
  29779. int width,
  29780. int height) const;
  29781. juce_UseDebuggingNewOperator
  29782. private:
  29783. float** values;
  29784. int size;
  29785. // no reason not to implement these one day..
  29786. ImageConvolutionKernel (const ImageConvolutionKernel&);
  29787. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  29788. };
  29789. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29790. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  29791. #endif
  29792. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29793. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  29794. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29795. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29796. /**
  29797. Base-class for codecs that can read and write image file formats such
  29798. as PNG, JPEG, etc.
  29799. This class also contains static methods to make it easy to load images
  29800. from files, streams or from memory.
  29801. @see Image, ImageCache
  29802. */
  29803. class JUCE_API ImageFileFormat
  29804. {
  29805. protected:
  29806. /** Creates an ImageFormat. */
  29807. ImageFileFormat() throw() {}
  29808. public:
  29809. /** Destructor. */
  29810. virtual ~ImageFileFormat() throw() {}
  29811. /** Returns a description of this file format.
  29812. E.g. "JPEG", "PNG"
  29813. */
  29814. virtual const String getFormatName() = 0;
  29815. /** Returns true if the given stream seems to contain data that this format
  29816. understands.
  29817. The format class should only read the first few bytes of the stream and sniff
  29818. for header bytes that it understands.
  29819. @see decodeImage
  29820. */
  29821. virtual bool canUnderstand (InputStream& input) = 0;
  29822. /** Tries to decode and return an image from the given stream.
  29823. This will be called for an image format after calling its canUnderStand() method
  29824. to see if it can handle the stream.
  29825. @param input the stream to read the data from. The stream will be positioned
  29826. at the start of the image data (but this may not necessarily
  29827. be position 0)
  29828. @returns the image that was decoded, or 0 if it fails. It's the
  29829. caller's responsibility to delete this image when no longer needed.
  29830. @see loadFrom
  29831. */
  29832. virtual Image* decodeImage (InputStream& input) = 0;
  29833. /** Attempts to write an image to a stream.
  29834. To specify extra information like encoding quality, there will be appropriate parameters
  29835. in the subclasses of the specific file types.
  29836. @returns true if it nothing went wrong.
  29837. */
  29838. virtual bool writeImageToStream (const Image& sourceImage,
  29839. OutputStream& destStream) = 0;
  29840. /** Tries the built-in decoders to see if it can find one to read this stream.
  29841. There are currently built-in decoders for PNG, JPEG and GIF formats.
  29842. The object that is returned should not be deleted by the caller.
  29843. @see canUnderstand, decodeImage, loadFrom
  29844. */
  29845. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  29846. /** Tries to load an image from a stream.
  29847. This will use the findImageFormatForStream() method to locate a suitable
  29848. codec, and use that to load the image.
  29849. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29850. caller's responsibility to delete this image when no longer needed.
  29851. */
  29852. static Image* loadFrom (InputStream& input);
  29853. /** Tries to load an image from a file.
  29854. This will use the findImageFormatForStream() method to locate a suitable
  29855. codec, and use that to load the image.
  29856. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29857. caller's responsibility to delete this image when no longer needed.
  29858. */
  29859. static Image* loadFrom (const File& file);
  29860. /** Tries to load an image from a block of raw image data.
  29861. This will use the findImageFormatForStream() method to locate a suitable
  29862. codec, and use that to load the image.
  29863. @returns the image that was decoded, or 0 if it fails to load one. It's the
  29864. caller's responsibility to delete this image when no longer needed.
  29865. */
  29866. static Image* loadFrom (const void* rawData,
  29867. const int numBytesOfData);
  29868. };
  29869. /**
  29870. A type of ImageFileFormat for reading and writing PNG files.
  29871. @see ImageFileFormat, JPEGImageFormat
  29872. */
  29873. class PNGImageFormat : public ImageFileFormat
  29874. {
  29875. public:
  29876. PNGImageFormat() throw();
  29877. ~PNGImageFormat() throw();
  29878. const String getFormatName();
  29879. bool canUnderstand (InputStream& input);
  29880. Image* decodeImage (InputStream& input);
  29881. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29882. };
  29883. /**
  29884. A type of ImageFileFormat for reading and writing JPEG files.
  29885. @see ImageFileFormat, PNGImageFormat
  29886. */
  29887. class JPEGImageFormat : public ImageFileFormat
  29888. {
  29889. public:
  29890. JPEGImageFormat() throw();
  29891. ~JPEGImageFormat() throw();
  29892. /** Specifies the quality to be used when writing a JPEG file.
  29893. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  29894. any negative value is "default" quality
  29895. */
  29896. void setQuality (const float newQuality);
  29897. const String getFormatName();
  29898. bool canUnderstand (InputStream& input);
  29899. Image* decodeImage (InputStream& input);
  29900. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  29901. private:
  29902. float quality;
  29903. };
  29904. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  29905. /********* End of inlined file: juce_ImageFileFormat.h *********/
  29906. #endif
  29907. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29908. /********* Start of inlined file: juce_Drawable.h *********/
  29909. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  29910. #define __JUCE_DRAWABLE_JUCEHEADER__
  29911. /**
  29912. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  29913. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29914. */
  29915. class JUCE_API Drawable
  29916. {
  29917. protected:
  29918. /** The base class can't be instantiated directly.
  29919. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  29920. */
  29921. Drawable();
  29922. public:
  29923. /** Destructor. */
  29924. virtual ~Drawable();
  29925. /** Creates a deep copy of this Drawable object.
  29926. Use this to create a new copy of this and any sub-objects in the tree.
  29927. */
  29928. virtual Drawable* createCopy() const = 0;
  29929. /** Renders this Drawable object.
  29930. This is the main rendering method you should call to render a Drawable.
  29931. @see drawWithin
  29932. */
  29933. virtual void draw (Graphics& g,
  29934. const AffineTransform& transform = AffineTransform::identity) const = 0;
  29935. /** Renders the Drawable at a given offset within the Graphics context.
  29936. The co-ordinates passed-in are used to translate the object relative to its own
  29937. origin before drawing it - this is basically a quick way of saying:
  29938. @code
  29939. draw (g, AffineTransform::translation (x, y)).
  29940. @endcode
  29941. */
  29942. void drawAt (Graphics& g,
  29943. const float x,
  29944. const float y) const;
  29945. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  29946. changing its aspect-ratio.
  29947. The object can placed arbitrarily within the rectangle based on a Justification type,
  29948. and can either be made as big as possible, or just reduced to fit.
  29949. @param g the graphics context to render onto
  29950. @param destX top-left of the target rectangle to fit it into
  29951. @param destY top-left of the target rectangle to fit it into
  29952. @param destWidth size of the target rectangle to fit the image into
  29953. @param destHeight size of the target rectangle to fit the image into
  29954. @param placement defines the alignment and rescaling to use to fit
  29955. this object within the target rectangle.
  29956. */
  29957. void drawWithin (Graphics& g,
  29958. const int destX,
  29959. const int destY,
  29960. const int destWidth,
  29961. const int destHeight,
  29962. const RectanglePlacement& placement) const;
  29963. /** Returns the smallest rectangle that can contain this Drawable object.
  29964. Co-ordinates are relative to the object's own origin.
  29965. */
  29966. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  29967. /** Returns true if the given point is somewhere inside this Drawable.
  29968. Co-ordinates are relative to the object's own origin.
  29969. */
  29970. virtual bool hitTest (float x, float y) const = 0;
  29971. /** Returns the name given to this drawable.
  29972. @see setName
  29973. */
  29974. const String& getName() const throw() { return name; }
  29975. /** Assigns a name to this drawable. */
  29976. void setName (const String& newName) throw() { name = newName; }
  29977. /** Tries to turn some kind of image file into a drawable.
  29978. The data could be an image that the ImageFileFormat class understands, or it
  29979. could be SVG.
  29980. */
  29981. static Drawable* createFromImageData (const void* data, const int numBytes);
  29982. /** Tries to turn a stream containing some kind of image data into a drawable.
  29983. The data could be an image that the ImageFileFormat class understands, or it
  29984. could be SVG.
  29985. */
  29986. static Drawable* createFromImageDataStream (InputStream& dataSource);
  29987. /** Tries to turn a file containing some kind of image data into a drawable.
  29988. The data could be an image that the ImageFileFormat class understands, or it
  29989. could be SVG.
  29990. */
  29991. static Drawable* createFromImageFile (const File& file);
  29992. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  29993. into a Drawable tree.
  29994. The object returned must be deleted by the caller. If something goes wrong
  29995. while parsing, it may return 0.
  29996. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  29997. implementation, but it can return the basic vector objects.
  29998. */
  29999. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30000. juce_UseDebuggingNewOperator
  30001. private:
  30002. Drawable (const Drawable&);
  30003. const Drawable& operator= (const Drawable&);
  30004. String name;
  30005. };
  30006. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30007. /********* End of inlined file: juce_Drawable.h *********/
  30008. #endif
  30009. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30010. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30011. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30012. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30013. /**
  30014. A drawable object which acts as a container for a set of other Drawables.
  30015. @see Drawable
  30016. */
  30017. class JUCE_API DrawableComposite : public Drawable
  30018. {
  30019. public:
  30020. /** Creates a composite Drawable.
  30021. */
  30022. DrawableComposite();
  30023. /** Destructor. */
  30024. virtual ~DrawableComposite();
  30025. /** Adds a new sub-drawable to this one.
  30026. This passes in a Drawable pointer for this object to look after. To add a copy
  30027. of a drawable, use the form of this method that takes a Drawable reference instead.
  30028. @param drawable the object to add - this will be deleted automatically
  30029. when no longer needed, so the caller mustn't keep any
  30030. pointers to it.
  30031. @param transform the transform to apply to this drawable when it's being
  30032. drawn
  30033. @param index where to insert it in the list of drawables. 0 is the back,
  30034. -1 is the front, or any value from 0 and getNumDrawables()
  30035. can be used
  30036. @see removeDrawable
  30037. */
  30038. void insertDrawable (Drawable* drawable,
  30039. const AffineTransform& transform = AffineTransform::identity,
  30040. const int index = -1);
  30041. /** Adds a new sub-drawable to this one.
  30042. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30043. for this object to look after, use the form of this method that takes a Drawable
  30044. pointer instead.
  30045. @param drawable the object to add - an internal copy will be made of this object
  30046. @param transform the transform to apply to this drawable when it's being
  30047. drawn
  30048. @param index where to insert it in the list of drawables. 0 is the back,
  30049. -1 is the front, or any value from 0 and getNumDrawables()
  30050. can be used
  30051. @see removeDrawable
  30052. */
  30053. void insertDrawable (const Drawable& drawable,
  30054. const AffineTransform& transform = AffineTransform::identity,
  30055. const int index = -1);
  30056. /** Deletes one of the Drawable objects.
  30057. @param index the index of the drawable to delete, between 0
  30058. and (getNumDrawables() - 1).
  30059. @see insertDrawable, getNumDrawables
  30060. */
  30061. void removeDrawable (const int index);
  30062. /** Returns the number of drawables contained inside this one.
  30063. @see getDrawable
  30064. */
  30065. int getNumDrawables() const throw() { return drawables.size(); }
  30066. /** Returns one of the drawables that are contained in this one.
  30067. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30068. to find it.
  30069. The pointer returned is managed by this object and will be deleted when no longer
  30070. needed, so be careful what you do with it.
  30071. @see getNumDrawables
  30072. */
  30073. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30074. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30075. The pointer returned is managed by this object and will be deleted when no longer
  30076. needed, so be careful what you do with it.
  30077. @see getNumDrawables
  30078. */
  30079. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30080. /** Brings one of the Drawables to the front.
  30081. @param index the index of the drawable to move, between 0
  30082. and (getNumDrawables() - 1).
  30083. @see insertDrawable, getNumDrawables
  30084. */
  30085. void bringToFront (const int index);
  30086. /** @internal */
  30087. void draw (Graphics& g, const AffineTransform& transform) const;
  30088. /** @internal */
  30089. void getBounds (float& x, float& y, float& width, float& height) const;
  30090. /** @internal */
  30091. bool hitTest (float x, float y) const;
  30092. /** @internal */
  30093. Drawable* createCopy() const;
  30094. juce_UseDebuggingNewOperator
  30095. private:
  30096. OwnedArray <Drawable> drawables;
  30097. OwnedArray <AffineTransform> transforms;
  30098. DrawableComposite (const DrawableComposite&);
  30099. const DrawableComposite& operator= (const DrawableComposite&);
  30100. };
  30101. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30102. /********* End of inlined file: juce_DrawableComposite.h *********/
  30103. #endif
  30104. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30105. /********* Start of inlined file: juce_DrawableImage.h *********/
  30106. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30107. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30108. /**
  30109. A drawable object which is a bitmap image.
  30110. @see Drawable
  30111. */
  30112. class JUCE_API DrawableImage : public Drawable
  30113. {
  30114. public:
  30115. DrawableImage();
  30116. /** Destructor. */
  30117. virtual ~DrawableImage();
  30118. /** Sets the image that this drawable will render.
  30119. An internal copy is made of the image passed-in. If you want to provide an
  30120. image that this object can take charge of without needing to create a copy,
  30121. use the other setImage() method.
  30122. */
  30123. void setImage (const Image& imageToCopy);
  30124. /** Sets the image that this drawable will render.
  30125. An internal copy of this will not be made, so the caller mustn't delete
  30126. the image while it's still being used by this object.
  30127. A good way to use this is with the ImageCache - if you create an image
  30128. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30129. it'll be released neatly with its reference count being decreased.
  30130. @param imageToUse the image to render
  30131. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30132. then the image will be deleted when this object no longer
  30133. needs it - unless the image was created by the ImageCache,
  30134. in which case it will be released with ImageCache::release().
  30135. */
  30136. void setImage (Image* imageToUse,
  30137. const bool releaseWhenNotNeeded);
  30138. /** Returns the current image. */
  30139. Image* getImage() const throw() { return image; }
  30140. /** Clears (and possibly deletes) the currently set image. */
  30141. void clearImage();
  30142. /** Sets the opacity to use when drawing the image. */
  30143. void setOpacity (const float newOpacity);
  30144. /** Returns the image's opacity. */
  30145. float getOpacity() const throw() { return opacity; }
  30146. /** Sets a colour to draw over the image's alpha channel.
  30147. By default this is transparent so isn't drawn, but if you set a non-transparent
  30148. colour here, then it will be overlaid on the image, using the image's alpha
  30149. channel as a mask.
  30150. This is handy for doing things like darkening or lightening an image by overlaying
  30151. it with semi-transparent black or white.
  30152. */
  30153. void setOverlayColour (const Colour& newOverlayColour);
  30154. /** Returns the overlay colour. */
  30155. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30156. /** @internal */
  30157. void draw (Graphics& g, const AffineTransform& transform) const;
  30158. /** @internal */
  30159. void getBounds (float& x, float& y, float& width, float& height) const;
  30160. /** @internal */
  30161. bool hitTest (float x, float y) const;
  30162. /** @internal */
  30163. Drawable* createCopy() const;
  30164. juce_UseDebuggingNewOperator
  30165. private:
  30166. Image* image;
  30167. bool canDeleteImage;
  30168. float opacity;
  30169. Colour overlayColour;
  30170. DrawableImage (const DrawableImage&);
  30171. const DrawableImage& operator= (const DrawableImage&);
  30172. };
  30173. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30174. /********* End of inlined file: juce_DrawableImage.h *********/
  30175. #endif
  30176. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30177. /********* Start of inlined file: juce_DrawablePath.h *********/
  30178. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30179. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30180. /**
  30181. A drawable object which renders a filled or outlined shape.
  30182. @see Drawable
  30183. */
  30184. class JUCE_API DrawablePath : public Drawable
  30185. {
  30186. public:
  30187. /** Creates a DrawablePath.
  30188. */
  30189. DrawablePath();
  30190. /** Destructor. */
  30191. virtual ~DrawablePath();
  30192. /** Changes the path that will be drawn.
  30193. @see setSolidFill, setOutline
  30194. */
  30195. void setPath (const Path& newPath);
  30196. /** Returns the current path. */
  30197. const Path& getPath() const throw() { return path; }
  30198. /** Sets a colour to fill the path with.
  30199. This colour is used to fill the path - if you don't want the path to be
  30200. filled (e.g. if you're just drawing an outline), set this colour to be
  30201. transparent.
  30202. @see setPath, setOutline
  30203. */
  30204. void setSolidFill (const Colour& newColour);
  30205. /** Sets a custom brush to use to fill the path.
  30206. @see setSolidFill
  30207. */
  30208. void setFillBrush (const Brush& newBrush);
  30209. /** Returns the brush currently being used to fill the shape. */
  30210. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30211. /** Changes the properties of the outline that will be drawn around the path.
  30212. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30213. colour passed-in here will be used for it.
  30214. @see setPath, setSolidFill
  30215. */
  30216. void setOutline (const float thickness,
  30217. const Colour& outlineColour);
  30218. /** Changes the properties of the outline that will be drawn around the path.
  30219. If the stroke type has 0 thickness, no outline will be drawn.
  30220. @see setPath, setSolidFill
  30221. */
  30222. void setOutline (const PathStrokeType& strokeType,
  30223. const Brush& strokeBrush);
  30224. /** Returns the current outline style. */
  30225. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30226. /** Returns the brush currently being used to draw the outline. */
  30227. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30228. /** @internal */
  30229. void draw (Graphics& g, const AffineTransform& transform) const;
  30230. /** @internal */
  30231. void getBounds (float& x, float& y, float& width, float& height) const;
  30232. /** @internal */
  30233. bool hitTest (float x, float y) const;
  30234. /** @internal */
  30235. Drawable* createCopy() const;
  30236. juce_UseDebuggingNewOperator
  30237. private:
  30238. Path path, outline;
  30239. Brush* fillBrush;
  30240. Brush* strokeBrush;
  30241. PathStrokeType strokeType;
  30242. void updateOutline();
  30243. DrawablePath (const DrawablePath&);
  30244. const DrawablePath& operator= (const DrawablePath&);
  30245. };
  30246. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30247. /********* End of inlined file: juce_DrawablePath.h *********/
  30248. #endif
  30249. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30250. /********* Start of inlined file: juce_DrawableText.h *********/
  30251. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30252. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30253. /**
  30254. A drawable object which renders a line of text.
  30255. @see Drawable
  30256. */
  30257. class JUCE_API DrawableText : public Drawable
  30258. {
  30259. public:
  30260. /** Creates a DrawableText object. */
  30261. DrawableText();
  30262. /** Destructor. */
  30263. virtual ~DrawableText();
  30264. /** Sets the block of text to render */
  30265. void setText (const GlyphArrangement& newText);
  30266. /** Sets a single line of text to render.
  30267. This is a convenient method of adding a single line - for
  30268. more complex text, use the setText() that takes a
  30269. GlyphArrangement instead.
  30270. */
  30271. void setText (const String& newText, const Font& fontToUse);
  30272. /** Returns the text arrangement that was set with setText(). */
  30273. const GlyphArrangement& getText() const throw() { return text; }
  30274. /** Sets the colour of the text. */
  30275. void setColour (const Colour& newColour);
  30276. /** Returns the current text colour. */
  30277. const Colour& getColour() const throw() { return colour; }
  30278. /** @internal */
  30279. void draw (Graphics& g, const AffineTransform& transform) const;
  30280. /** @internal */
  30281. void getBounds (float& x, float& y, float& width, float& height) const;
  30282. /** @internal */
  30283. bool hitTest (float x, float y) const;
  30284. /** @internal */
  30285. Drawable* createCopy() const;
  30286. juce_UseDebuggingNewOperator
  30287. private:
  30288. GlyphArrangement text;
  30289. Colour colour;
  30290. DrawableText (const DrawableText&);
  30291. const DrawableText& operator= (const DrawableText&);
  30292. };
  30293. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30294. /********* End of inlined file: juce_DrawableText.h *********/
  30295. #endif
  30296. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30297. #endif
  30298. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30299. #endif
  30300. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30301. #endif
  30302. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30303. #endif
  30304. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30305. /********* Start of inlined file: juce_ArrowButton.h *********/
  30306. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30307. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30308. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30309. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30310. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30311. /**
  30312. An effect filter that adds a drop-shadow behind the image's content.
  30313. (This will only work on images/components that aren't opaque, of course).
  30314. When added to a component, this effect will draw a soft-edged
  30315. shadow based on what gets drawn inside it. The shadow will also
  30316. be applied to the component's children.
  30317. For speed, this doesn't use a proper gaussian blur, but cheats by
  30318. using a simple bilinear filter. If you need a really high-quality
  30319. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30320. @see Component::setComponentEffect
  30321. */
  30322. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30323. {
  30324. public:
  30325. /** Creates a default drop-shadow effect.
  30326. To customise the shadow's appearance, use the setShadowProperties()
  30327. method.
  30328. */
  30329. DropShadowEffect();
  30330. /** Destructor. */
  30331. ~DropShadowEffect();
  30332. /** Sets up parameters affecting the shadow's appearance.
  30333. @param newRadius the (approximate) radius of the blur used
  30334. @param newOpacity the opacity with which the shadow is rendered
  30335. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30336. component's contents
  30337. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30338. component's contents
  30339. */
  30340. void setShadowProperties (const float newRadius,
  30341. const float newOpacity,
  30342. const int newShadowOffsetX,
  30343. const int newShadowOffsetY);
  30344. /** @internal */
  30345. void applyEffect (Image& sourceImage, Graphics& destContext);
  30346. juce_UseDebuggingNewOperator
  30347. private:
  30348. int offsetX, offsetY;
  30349. float radius, opacity;
  30350. };
  30351. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30352. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30353. /**
  30354. A button with an arrow in it.
  30355. @see Button
  30356. */
  30357. class JUCE_API ArrowButton : public Button
  30358. {
  30359. public:
  30360. /** Creates an ArrowButton.
  30361. @param buttonName the name to give the button
  30362. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30363. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30364. @param arrowColour the colour to use for the arrow
  30365. */
  30366. ArrowButton (const String& buttonName,
  30367. float arrowDirection,
  30368. const Colour& arrowColour);
  30369. /** Destructor. */
  30370. ~ArrowButton();
  30371. juce_UseDebuggingNewOperator
  30372. protected:
  30373. /** @internal */
  30374. void paintButton (Graphics& g,
  30375. bool isMouseOverButton,
  30376. bool isButtonDown);
  30377. /** @internal */
  30378. void buttonStateChanged();
  30379. private:
  30380. Colour colour;
  30381. DropShadowEffect shadow;
  30382. Path path;
  30383. int offset;
  30384. ArrowButton (const ArrowButton&);
  30385. const ArrowButton& operator= (const ArrowButton&);
  30386. };
  30387. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30388. /********* End of inlined file: juce_ArrowButton.h *********/
  30389. #endif
  30390. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30391. #endif
  30392. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30393. /********* Start of inlined file: juce_DrawableButton.h *********/
  30394. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30395. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30396. /**
  30397. A button that displays a Drawable.
  30398. Up to three Drawable objects can be given to this button, to represent the
  30399. 'normal', 'over' and 'down' states.
  30400. @see Button
  30401. */
  30402. class JUCE_API DrawableButton : public Button
  30403. {
  30404. public:
  30405. enum ButtonStyle
  30406. {
  30407. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30408. ImageRaw, /**< The button will just display the images in their normal size and position.
  30409. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30410. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30411. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30412. };
  30413. /** Creates a DrawableButton.
  30414. After creating one of these, use setImages() to specify the drawables to use.
  30415. @param buttonName the name to give the component
  30416. @param buttonStyle the layout to use
  30417. @see ButtonStyle, setButtonStyle, setImages
  30418. */
  30419. DrawableButton (const String& buttonName,
  30420. const ButtonStyle buttonStyle);
  30421. /** Destructor. */
  30422. ~DrawableButton();
  30423. /** Sets up the images to draw for the various button states.
  30424. The button will keep its own internal copies of these drawables.
  30425. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30426. will be made of the object passed-in if it is non-zero.
  30427. @param overImage the thing to draw for the button's 'over' state - if this is
  30428. zero, the button's normal image will be used when the mouse is
  30429. over it. An internal copy will be made of the object passed-in
  30430. if it is non-zero.
  30431. @param downImage the thing to draw for the button's 'down' state - if this is
  30432. zero, the 'over' image will be used instead (or the normal image
  30433. as a last resort). An internal copy will be made of the object
  30434. passed-in if it is non-zero.
  30435. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30436. the normal image will be drawn with a reduced opacity instead.
  30437. An internal copy will be made of the object passed-in if it is
  30438. non-zero.
  30439. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30440. state is 'on'. If this is 0, the normal image is used instead
  30441. @param overImageOn same as the overImage, but this is used when the button's toggle
  30442. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30443. @param downImageOn same as the downImage, but this is used when the button's toggle
  30444. state is 'on'. If this is 0, the overImageOn is drawn instead
  30445. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30446. state is 'on'. If this is 0, the normal image will be drawn instead
  30447. with a reduced opacity
  30448. */
  30449. void setImages (const Drawable* normalImage,
  30450. const Drawable* overImage = 0,
  30451. const Drawable* downImage = 0,
  30452. const Drawable* disabledImage = 0,
  30453. const Drawable* normalImageOn = 0,
  30454. const Drawable* overImageOn = 0,
  30455. const Drawable* downImageOn = 0,
  30456. const Drawable* disabledImageOn = 0);
  30457. /** Changes the button's style.
  30458. @see ButtonStyle
  30459. */
  30460. void setButtonStyle (const ButtonStyle newStyle);
  30461. /** Changes the button's background colours.
  30462. The toggledOffColour is the colour to use when the button's toggle state
  30463. is off, and toggledOnColour when it's on.
  30464. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30465. used to fill the background of the component.
  30466. For an ImageOnButtonBackground style, the colour is used to draw the
  30467. button's lozenge shape and exactly how the colour's used will depend
  30468. on the LookAndFeel.
  30469. */
  30470. void setBackgroundColours (const Colour& toggledOffColour,
  30471. const Colour& toggledOnColour);
  30472. /** Returns the current background colour being used.
  30473. @see setBackgroundColour
  30474. */
  30475. const Colour& getBackgroundColour() const throw();
  30476. /** Gives the button an optional amount of space around the edge of the drawable.
  30477. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30478. ones on a button background. If the button is too small for the given gap, a
  30479. smaller gap will be used.
  30480. By default there's a gap of about 3 pixels.
  30481. */
  30482. void setEdgeIndent (const int numPixelsIndent);
  30483. /** Returns the image that the button is currently displaying. */
  30484. const Drawable* getCurrentImage() const throw();
  30485. const Drawable* getNormalImage() const throw();
  30486. const Drawable* getOverImage() const throw();
  30487. const Drawable* getDownImage() const throw();
  30488. juce_UseDebuggingNewOperator
  30489. protected:
  30490. /** @internal */
  30491. void paintButton (Graphics& g,
  30492. bool isMouseOverButton,
  30493. bool isButtonDown);
  30494. private:
  30495. ButtonStyle style;
  30496. Drawable* normalImage;
  30497. Drawable* overImage;
  30498. Drawable* downImage;
  30499. Drawable* disabledImage;
  30500. Drawable* normalImageOn;
  30501. Drawable* overImageOn;
  30502. Drawable* downImageOn;
  30503. Drawable* disabledImageOn;
  30504. Colour backgroundOff, backgroundOn;
  30505. int edgeIndent;
  30506. void deleteImages();
  30507. DrawableButton (const DrawableButton&);
  30508. const DrawableButton& operator= (const DrawableButton&);
  30509. };
  30510. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30511. /********* End of inlined file: juce_DrawableButton.h *********/
  30512. #endif
  30513. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30514. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30515. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30516. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30517. /**
  30518. A button showing an underlined weblink, that will launch the link
  30519. when it's clicked.
  30520. @see Button
  30521. */
  30522. class JUCE_API HyperlinkButton : public Button
  30523. {
  30524. public:
  30525. /** Creates a HyperlinkButton.
  30526. @param linkText the text that will be displayed in the button - this is
  30527. also set as the Component's name, but the text can be
  30528. changed later with the Button::getButtonText() method
  30529. @param linkURL the URL to launch when the user clicks the button
  30530. */
  30531. HyperlinkButton (const String& linkText,
  30532. const URL& linkURL);
  30533. /** Destructor. */
  30534. ~HyperlinkButton();
  30535. /** Changes the font to use for the text.
  30536. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30537. to match the size of the component.
  30538. */
  30539. void setFont (const Font& newFont,
  30540. const bool resizeToMatchComponentHeight,
  30541. const Justification& justificationType = Justification::horizontallyCentred);
  30542. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30543. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30544. methods.
  30545. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30546. */
  30547. enum ColourIds
  30548. {
  30549. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30550. };
  30551. /** Changes the URL that the button will trigger. */
  30552. void setURL (const URL& newURL) throw();
  30553. /** Returns the URL that the button will trigger. */
  30554. const URL& getURL() const throw() { return url; }
  30555. /** Resizes the button horizontally to fit snugly around the text.
  30556. This won't affect the button's height.
  30557. */
  30558. void changeWidthToFitText();
  30559. juce_UseDebuggingNewOperator
  30560. protected:
  30561. /** @internal */
  30562. void clicked();
  30563. /** @internal */
  30564. void colourChanged();
  30565. /** @internal */
  30566. void paintButton (Graphics& g,
  30567. bool isMouseOverButton,
  30568. bool isButtonDown);
  30569. private:
  30570. URL url;
  30571. Font font;
  30572. bool resizeFont;
  30573. Justification justification;
  30574. const Font getFontToUse() const;
  30575. HyperlinkButton (const HyperlinkButton&);
  30576. const HyperlinkButton& operator= (const HyperlinkButton&);
  30577. };
  30578. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30579. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30580. #endif
  30581. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30582. /********* Start of inlined file: juce_ImageButton.h *********/
  30583. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30584. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30585. /**
  30586. As the title suggests, this is a button containing an image.
  30587. The colour and transparency of the image can be set to vary when the
  30588. button state changes.
  30589. @see Button, ShapeButton, TextButton
  30590. */
  30591. class JUCE_API ImageButton : public Button
  30592. {
  30593. public:
  30594. /** Creates an ImageButton.
  30595. Use setImage() to specify the image to use. The colours and opacities that
  30596. are specified here can be changed later using setDrawingOptions().
  30597. @param name the name to give the component
  30598. */
  30599. ImageButton (const String& name);
  30600. /** Destructor. */
  30601. ~ImageButton();
  30602. /** Sets up the images to draw in various states.
  30603. Important! Bear in mind that if you pass the same image in for more than one of
  30604. these parameters, this button will delete it (or release from the ImageCache)
  30605. multiple times!
  30606. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30607. resized to the same dimensions as the normal image
  30608. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30609. button when the button's size changes
  30610. @param preserveImageProportions if true then any rescaling of the image to fit
  30611. the button will keep the image's x and y proportions
  30612. correct - i.e. it won't distort its shape, although
  30613. this might create gaps around the edges
  30614. @param normalImage the image to use when the button is in its normal state. The
  30615. image passed in will be deleted (or released if it
  30616. was created by the ImageCache class) when the
  30617. button no longer needs it.
  30618. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30619. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30620. normal image - if this colour is transparent, no overlay
  30621. will be drawn. The overlay will be drawn over the top of the
  30622. image, so you can basically add a solid or semi-transparent
  30623. colour to the image to brighten or darken it
  30624. @param overImage the image to use when the mouse is over the button. If
  30625. you want to use the same image as was set in the normalImage
  30626. parameter, this value can be 0. As for normalImage, it
  30627. will be deleted or released by the button when no longer
  30628. needed
  30629. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30630. is over the button
  30631. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30632. image when the mouse is over - if this colour is transparent,
  30633. no overlay will be drawn
  30634. @param downImage an image to use when the button is pressed down. If set
  30635. to zero, the 'over' image will be drawn instead (or the
  30636. normal image if there isn't an 'over' image either). This
  30637. image will be deleted or released by the button when no
  30638. longer needed
  30639. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30640. is pressed
  30641. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30642. image when the button is pressed down - if this colour is
  30643. transparent, no overlay will be drawn
  30644. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30645. whenever it's inside the button's bounding rectangle. If
  30646. set to values higher than 0, the mouse will only be
  30647. considered to be over the image when the value of the
  30648. image's alpha channel at that position is greater than
  30649. this level.
  30650. */
  30651. void setImages (const bool resizeButtonNowToFitThisImage,
  30652. const bool rescaleImagesWhenButtonSizeChanges,
  30653. const bool preserveImageProportions,
  30654. Image* const normalImage,
  30655. const float imageOpacityWhenNormal,
  30656. const Colour& overlayColourWhenNormal,
  30657. Image* const overImage,
  30658. const float imageOpacityWhenOver,
  30659. const Colour& overlayColourWhenOver,
  30660. Image* const downImage,
  30661. const float imageOpacityWhenDown,
  30662. const Colour& overlayColourWhenDown,
  30663. const float hitTestAlphaThreshold = 0.0f);
  30664. /** Returns the currently set 'normal' image. */
  30665. Image* getNormalImage() const throw();
  30666. /** Returns the image that's drawn when the mouse is over the button.
  30667. If an 'over' image has been set, this will return it; otherwise it'll
  30668. just return the normal image.
  30669. */
  30670. Image* getOverImage() const throw();
  30671. /** Returns the image that's drawn when the button is held down.
  30672. If a 'down' image has been set, this will return it; otherwise it'll
  30673. return the 'over' image or normal image, depending on what's available.
  30674. */
  30675. Image* getDownImage() const throw();
  30676. juce_UseDebuggingNewOperator
  30677. protected:
  30678. /** @internal */
  30679. bool hitTest (int x, int y);
  30680. /** @internal */
  30681. void paintButton (Graphics& g,
  30682. bool isMouseOverButton,
  30683. bool isButtonDown);
  30684. private:
  30685. bool scaleImageToFit, preserveProportions;
  30686. unsigned char alphaThreshold;
  30687. int imageX, imageY, imageW, imageH;
  30688. Image* normalImage;
  30689. Image* overImage;
  30690. Image* downImage;
  30691. float normalOpacity, overOpacity, downOpacity;
  30692. Colour normalOverlay, overOverlay, downOverlay;
  30693. Image* getCurrentImage() const;
  30694. void deleteImages();
  30695. ImageButton (const ImageButton&);
  30696. const ImageButton& operator= (const ImageButton&);
  30697. };
  30698. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30699. /********* End of inlined file: juce_ImageButton.h *********/
  30700. #endif
  30701. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30702. /********* Start of inlined file: juce_ShapeButton.h *********/
  30703. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30704. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30705. /**
  30706. A button that contains a filled shape.
  30707. @see Button, ImageButton, TextButton, ArrowButton
  30708. */
  30709. class JUCE_API ShapeButton : public Button
  30710. {
  30711. public:
  30712. /** Creates a ShapeButton.
  30713. @param name a name to give the component - see Component::setName()
  30714. @param normalColour the colour to fill the shape with when the mouse isn't over
  30715. @param overColour the colour to use when the mouse is over the shape
  30716. @param downColour the colour to use when the button is in the pressed-down state
  30717. */
  30718. ShapeButton (const String& name,
  30719. const Colour& normalColour,
  30720. const Colour& overColour,
  30721. const Colour& downColour);
  30722. /** Destructor. */
  30723. ~ShapeButton();
  30724. /** Sets the shape to use.
  30725. @param newShape the shape to use
  30726. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30727. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30728. the button is resized
  30729. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30730. */
  30731. void setShape (const Path& newShape,
  30732. const bool resizeNowToFitThisShape,
  30733. const bool maintainShapeProportions,
  30734. const bool hasDropShadow);
  30735. /** Set the colours to use for drawing the shape.
  30736. @param normalColour the colour to fill the shape with when the mouse isn't over
  30737. @param overColour the colour to use when the mouse is over the shape
  30738. @param downColour the colour to use when the button is in the pressed-down state
  30739. */
  30740. void setColours (const Colour& normalColour,
  30741. const Colour& overColour,
  30742. const Colour& downColour);
  30743. /** Sets up an outline to draw around the shape.
  30744. @param outlineColour the colour to use
  30745. @param outlineStrokeWidth the thickness of line to draw
  30746. */
  30747. void setOutline (const Colour& outlineColour,
  30748. const float outlineStrokeWidth);
  30749. juce_UseDebuggingNewOperator
  30750. protected:
  30751. /** @internal */
  30752. void paintButton (Graphics& g,
  30753. bool isMouseOverButton,
  30754. bool isButtonDown);
  30755. private:
  30756. Colour normalColour, overColour, downColour, outlineColour;
  30757. DropShadowEffect shadow;
  30758. Path shape;
  30759. bool maintainShapeProportions;
  30760. float outlineWidth;
  30761. ShapeButton (const ShapeButton&);
  30762. const ShapeButton& operator= (const ShapeButton&);
  30763. };
  30764. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  30765. /********* End of inlined file: juce_ShapeButton.h *********/
  30766. #endif
  30767. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30768. #endif
  30769. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30770. /********* Start of inlined file: juce_ToggleButton.h *********/
  30771. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30772. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30773. /**
  30774. A button that can be toggled on/off.
  30775. All buttons can be toggle buttons, but this lets you create one of the
  30776. standard ones which has a tick-box and a text label next to it.
  30777. @see Button, DrawableButton, TextButton
  30778. */
  30779. class JUCE_API ToggleButton : public Button
  30780. {
  30781. public:
  30782. /** Creates a ToggleButton.
  30783. @param buttonText the text to put in the button (the component's name is also
  30784. initially set to this string, but these can be changed later
  30785. using the setName() and setButtonText() methods)
  30786. */
  30787. ToggleButton (const String& buttonText);
  30788. /** Destructor. */
  30789. ~ToggleButton();
  30790. /** Resizes the button to fit neatly around its current text.
  30791. The button's height won't be affected, only its width.
  30792. */
  30793. void changeWidthToFitText();
  30794. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30795. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30796. methods.
  30797. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30798. */
  30799. enum ColourIds
  30800. {
  30801. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  30802. };
  30803. juce_UseDebuggingNewOperator
  30804. protected:
  30805. /** @internal */
  30806. void paintButton (Graphics& g,
  30807. bool isMouseOverButton,
  30808. bool isButtonDown);
  30809. /** @internal */
  30810. void colourChanged();
  30811. private:
  30812. ToggleButton (const ToggleButton&);
  30813. const ToggleButton& operator= (const ToggleButton&);
  30814. };
  30815. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30816. /********* End of inlined file: juce_ToggleButton.h *********/
  30817. #endif
  30818. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30819. /********* Start of inlined file: juce_ToolbarButton.h *********/
  30820. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30821. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30822. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  30823. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30824. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30825. /********* Start of inlined file: juce_Toolbar.h *********/
  30826. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  30827. #define __JUCE_TOOLBAR_JUCEHEADER__
  30828. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  30829. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30830. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30831. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  30832. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30833. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30834. /**
  30835. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  30836. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  30837. derive your component from this class, and make sure that it is somewhere inside a
  30838. DragAndDropContainer component.
  30839. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30840. the operating system onto your component, you don't need any of these classes: instead
  30841. see the FileDragAndDropTarget class.
  30842. @see DragAndDropContainer, FileDragAndDropTarget
  30843. */
  30844. class JUCE_API DragAndDropTarget
  30845. {
  30846. public:
  30847. /** Destructor. */
  30848. virtual ~DragAndDropTarget() {}
  30849. /** Callback to check whether this target is interested in the type of object being
  30850. dragged.
  30851. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30852. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30853. @returns true if this component wants to receive the other callbacks regarging this
  30854. type of object; if it returns false, no other callbacks will be made.
  30855. */
  30856. virtual bool isInterestedInDragSource (const String& sourceDescription,
  30857. Component* sourceComponent) = 0;
  30858. /** Callback to indicate that something is being dragged over this component.
  30859. This gets called when the user moves the mouse into this component while dragging
  30860. something.
  30861. Use this callback as a trigger to make your component repaint itself to give the
  30862. user feedback about whether the item can be dropped here or not.
  30863. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30864. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30865. @param x the mouse x position, relative to this component
  30866. @param y the mouse y position, relative to this component
  30867. @see itemDragExit
  30868. */
  30869. virtual void itemDragEnter (const String& sourceDescription,
  30870. Component* sourceComponent,
  30871. int x,
  30872. int y);
  30873. /** Callback to indicate that the user is dragging something over this component.
  30874. This gets called when the user moves the mouse over this component while dragging
  30875. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  30876. this lets you know what happens in-between.
  30877. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30878. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30879. @param x the mouse x position, relative to this component
  30880. @param y the mouse y position, relative to this component
  30881. */
  30882. virtual void itemDragMove (const String& sourceDescription,
  30883. Component* sourceComponent,
  30884. int x,
  30885. int y);
  30886. /** Callback to indicate that something has been dragged off the edge of this component.
  30887. This gets called when the user moves the mouse out of this component while dragging
  30888. something.
  30889. If you've used itemDragEnter() to repaint your component and give feedback, use this
  30890. as a signal to repaint it in its normal state.
  30891. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30892. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30893. @see itemDragEnter
  30894. */
  30895. virtual void itemDragExit (const String& sourceDescription,
  30896. Component* sourceComponent);
  30897. /** Callback to indicate that the user has dropped something onto this component.
  30898. When the user drops an item this get called, and you can use the description to
  30899. work out whether your object wants to deal with it or not.
  30900. Note that after this is called, the itemDragExit method may not be called, so you should
  30901. clean up in here if there's anything you need to do when the drag finishes.
  30902. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30903. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30904. @param x the mouse x position, relative to this component
  30905. @param y the mouse y position, relative to this component
  30906. */
  30907. virtual void itemDropped (const String& sourceDescription,
  30908. Component* sourceComponent,
  30909. int x,
  30910. int y) = 0;
  30911. /** Overriding this allows the target to tell the drag container whether to
  30912. draw the drag image while the cursor is over it.
  30913. By default it returns true, but if you return false, then the normal drag
  30914. image will not be shown when the cursor is over this target.
  30915. */
  30916. virtual bool shouldDrawDragImageWhenOver();
  30917. };
  30918. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30919. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  30920. /**
  30921. Enables drag-and-drop behaviour for a component and all its sub-components.
  30922. For a component to be able to make or receive drag-and-drop events, one of its parent
  30923. components must derive from this class. It's probably best for the top-level
  30924. component to implement it.
  30925. Then to start a drag operation, any sub-component can just call the startDragging()
  30926. method, and this object will take over, tracking the mouse and sending appropriate
  30927. callbacks to any child components derived from DragAndDropTarget which the mouse
  30928. moves over.
  30929. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30930. the operating system onto your component, you don't need any of these classes: you can do this
  30931. simply by overriding Component::filesDropped().
  30932. @see DragAndDropTarget
  30933. */
  30934. class JUCE_API DragAndDropContainer
  30935. {
  30936. public:
  30937. /** Creates a DragAndDropContainer.
  30938. The object that derives from this class must also be a Component.
  30939. */
  30940. DragAndDropContainer();
  30941. /** Destructor. */
  30942. virtual ~DragAndDropContainer();
  30943. /** Begins a drag-and-drop operation.
  30944. This starts a drag-and-drop operation - call it when the user drags the
  30945. mouse in your drag-source component, and this object will track mouse
  30946. movements until the user lets go of the mouse button, and will send
  30947. appropriate messages to DragAndDropTarget objects that the mouse moves
  30948. over.
  30949. findParentDragContainerFor() is a handy method to call to find the
  30950. drag container to use for a component.
  30951. @param sourceDescription a string to use as the description of the thing being
  30952. dragged - this will be passed to the objects that might be
  30953. dropped-onto so they can decide if they want to handle it or
  30954. not
  30955. @param sourceComponent the component that is being dragged
  30956. @param dragImage the image to drag around underneath the mouse. If this is
  30957. zero, a snapshot of the sourceComponent will be used instead. An
  30958. image passed-in will be deleted by this object when no longer
  30959. needed.
  30960. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  30961. window, and can be dragged to DragAndDropTargets that are the
  30962. children of components other than this one.
  30963. */
  30964. void startDragging (const String& sourceDescription,
  30965. Component* sourceComponent,
  30966. Image* dragImage = 0,
  30967. const bool allowDraggingToOtherJuceWindows = false);
  30968. /** Returns true if something is currently being dragged. */
  30969. bool isDragAndDropActive() const;
  30970. /** Returns the description of the thing that's currently being dragged.
  30971. If nothing's being dragged, this will return an empty string, otherwise it's the
  30972. string that was passed into startDragging().
  30973. @see startDragging
  30974. */
  30975. const String getCurrentDragDescription() const;
  30976. /** Utility to find the DragAndDropContainer for a given Component.
  30977. This will search up this component's parent hierarchy looking for the first
  30978. parent component which is a DragAndDropContainer.
  30979. It's useful when a component wants to call startDragging but doesn't know
  30980. the DragAndDropContainer it should to use.
  30981. Obviously this may return 0 if it doesn't find a suitable component.
  30982. */
  30983. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  30984. /** This performs a synchronous drag-and-drop of a set of files to some external
  30985. application.
  30986. You can call this function in response to a mouseDrag callback, and it will
  30987. block, running its own internal message loop and tracking the mouse, while it
  30988. uses a native operating system drag-and-drop operation to move or copy some
  30989. files to another application.
  30990. @param files a list of filenames to drag
  30991. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  30992. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  30993. @returns true if the files were successfully dropped somewhere, or false if it
  30994. was interrupted
  30995. @see performExternalDragDropOfText
  30996. */
  30997. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  30998. /** This performs a synchronous drag-and-drop of a block of text to some external
  30999. application.
  31000. You can call this function in response to a mouseDrag callback, and it will
  31001. block, running its own internal message loop and tracking the mouse, while it
  31002. uses a native operating system drag-and-drop operation to move or copy some
  31003. text to another application.
  31004. @param text the text to copy
  31005. @returns true if the text was successfully dropped somewhere, or false if it
  31006. was interrupted
  31007. @see performExternalDragDropOfFiles
  31008. */
  31009. static bool performExternalDragDropOfText (const String& text);
  31010. juce_UseDebuggingNewOperator
  31011. protected:
  31012. /** Override this if you want to be able to perform an external drag a set of files
  31013. when the user drags outside of this container component.
  31014. This method will be called when a drag operation moves outside the Juce-based window,
  31015. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31016. to the array passed in, and return true.
  31017. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31018. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31019. @param files on return, the filenames you want to drag
  31020. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31021. it must make a copy of them (see the performExternalDragDropOfFiles()
  31022. method)
  31023. @see performExternalDragDropOfFiles
  31024. */
  31025. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31026. Component* dragSourceComponent,
  31027. StringArray& files,
  31028. bool& canMoveFiles);
  31029. private:
  31030. friend class DragImageComponent;
  31031. Component* dragImageComponent;
  31032. String currentDragDesc;
  31033. };
  31034. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31035. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31036. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31037. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31038. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31039. /**
  31040. Animates a set of components, moving it to a new position.
  31041. To use this, create a ComponentAnimator, and use its animateComponent() method
  31042. to tell it to move components to destination positions. Any number of
  31043. components can be animated by one ComponentAnimator object (if you've got a
  31044. lot of components to move, it's much more efficient to share a single animator
  31045. than to have many animators running at once).
  31046. You'll need to make sure the animator object isn't deleted before it finishes
  31047. moving the components.
  31048. */
  31049. class JUCE_API ComponentAnimator : private Timer
  31050. {
  31051. public:
  31052. /** Creates a ComponentAnimator. */
  31053. ComponentAnimator();
  31054. /** Destructor. */
  31055. ~ComponentAnimator();
  31056. /** Starts a component moving from its current position to a specified position.
  31057. If the component is already in the middle of an animation, that will be abandoned,
  31058. and a new animation will begin, moving the component from its current location.
  31059. The start and end speed parameters let you apply some acceleration to the component's
  31060. movement.
  31061. @param component the component to move
  31062. @param finalPosition the destination position and size to move it to
  31063. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31064. to arrive at its destination
  31065. @param startSpeed a value to indicate the relative start speed of the
  31066. animation. If this is 0, the component will start
  31067. by accelerating from rest; higher values mean that it
  31068. will have an initial speed greater than zero. If the
  31069. value if greater than 1, it will decelerate towards the
  31070. middle of its journey. To move the component at a constant
  31071. rate for its entire animation, set both the start and
  31072. end speeds to 1.0
  31073. @param endSpeed a relative speed at which the component should be moving
  31074. when the animation finishes. If this is 0, the component
  31075. will decelerate to a standstill at its final position; higher
  31076. values mean the component will still be moving when it stops.
  31077. To move the component at a constant rate for its entire
  31078. animation, set both the start and end speeds to 1.0
  31079. */
  31080. void animateComponent (Component* const component,
  31081. const Rectangle& finalPosition,
  31082. const int millisecondsToSpendMoving,
  31083. const double startSpeed = 1.0,
  31084. const double endSpeed = 1.0);
  31085. /** Stops a component if it's currently being animated.
  31086. If moveComponentToItsFinalPosition is true, then the component will
  31087. be immediately moved to its destination position and size. If false, it will be
  31088. left in whatever location it currently occupies.
  31089. */
  31090. void cancelAnimation (Component* const component,
  31091. const bool moveComponentToItsFinalPosition);
  31092. /** Clears all of the active animations.
  31093. If moveComponentsToTheirFinalPositions is true, all the components will
  31094. be immediately set to their final positions. If false, they will be
  31095. left in whatever locations they currently occupy.
  31096. */
  31097. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31098. /** Returns the destination position for a component.
  31099. If the component is being animated, this will return the target position that
  31100. was specified when animateComponent() was called.
  31101. If the specified component isn't currently being animated, this method will just
  31102. return its current position.
  31103. */
  31104. const Rectangle getComponentDestination (Component* const component);
  31105. juce_UseDebuggingNewOperator
  31106. private:
  31107. VoidArray tasks;
  31108. uint32 lastTime;
  31109. void* findTaskFor (Component* const component) const;
  31110. void timerCallback();
  31111. };
  31112. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31113. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31114. class ToolbarItemComponent;
  31115. class ToolbarItemFactory;
  31116. class MissingItemsComponent;
  31117. /**
  31118. A toolbar component.
  31119. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31120. and looks after their order and layout.
  31121. Items (icon buttons or other custom components) are added to a toolbar using a
  31122. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31123. toolbar might contain more than one instance of a particular item type.
  31124. Toolbars can be interactively customised, allowing the user to drag the items
  31125. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31126. component as a source of new items.
  31127. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31128. */
  31129. class JUCE_API Toolbar : public Component,
  31130. public DragAndDropContainer,
  31131. public DragAndDropTarget,
  31132. private ButtonListener
  31133. {
  31134. public:
  31135. /** Creates an empty toolbar component.
  31136. To add some icons or other components to your toolbar, you'll need to
  31137. create a ToolbarItemFactory class that can create a suitable set of
  31138. ToolbarItemComponents.
  31139. @see ToolbarItemFactory, ToolbarItemComponents
  31140. */
  31141. Toolbar();
  31142. /** Destructor.
  31143. Any items on the bar will be deleted when the toolbar is deleted.
  31144. */
  31145. ~Toolbar();
  31146. /** Changes the bar's orientation.
  31147. @see isVertical
  31148. */
  31149. void setVertical (const bool shouldBeVertical);
  31150. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31151. You can change the bar's orientation with setVertical().
  31152. */
  31153. bool isVertical() const throw() { return vertical; }
  31154. /** Returns the depth of the bar.
  31155. If the bar is horizontal, this will return its height; if it's vertical, it
  31156. will return its width.
  31157. @see getLength
  31158. */
  31159. int getThickness() const throw();
  31160. /** Returns the length of the bar.
  31161. If the bar is horizontal, this will return its width; if it's vertical, it
  31162. will return its height.
  31163. @see getThickness
  31164. */
  31165. int getLength() const throw();
  31166. /** Deletes all items from the bar.
  31167. */
  31168. void clear();
  31169. /** Adds an item to the toolbar.
  31170. The factory's ToolbarItemFactory::createItem() will be called by this method
  31171. to create the component that will actually be added to the bar.
  31172. The new item will be inserted at the specified index (if the index is -1, it
  31173. will be added to the right-hand or bottom end of the bar).
  31174. Once added, the component will be automatically deleted by this object when it
  31175. is no longer needed.
  31176. @see ToolbarItemFactory
  31177. */
  31178. void addItem (ToolbarItemFactory& factory,
  31179. const int itemId,
  31180. const int insertIndex = -1);
  31181. /** Deletes one of the items from the bar.
  31182. */
  31183. void removeToolbarItem (const int itemIndex);
  31184. /** Returns the number of items currently on the toolbar.
  31185. @see getItemId, getItemComponent
  31186. */
  31187. int getNumItems() const throw();
  31188. /** Returns the ID of the item with the given index.
  31189. If the index is less than zero or greater than the number of items,
  31190. this will return 0.
  31191. @see getNumItems
  31192. */
  31193. int getItemId (const int itemIndex) const throw();
  31194. /** Returns the component being used for the item with the given index.
  31195. If the index is less than zero or greater than the number of items,
  31196. this will return 0.
  31197. @see getNumItems
  31198. */
  31199. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31200. /** Clears this toolbar and adds to it the default set of items that the specified
  31201. factory creates.
  31202. @see ToolbarItemFactory::getDefaultItemSet
  31203. */
  31204. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31205. /** Options for the way items should be displayed.
  31206. @see setStyle, getStyle
  31207. */
  31208. enum ToolbarItemStyle
  31209. {
  31210. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31211. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31212. textOnly /**< Means that the toolbar only display text labels for each item. */
  31213. };
  31214. /** Returns the toolbar's current style.
  31215. @see ToolbarItemStyle, setStyle
  31216. */
  31217. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31218. /** Changes the toolbar's current style.
  31219. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31220. */
  31221. void setStyle (const ToolbarItemStyle& newStyle);
  31222. /** Flags used by the showCustomisationDialog() method. */
  31223. enum CustomisationFlags
  31224. {
  31225. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31226. show the "icons only" option on its choice of toolbar styles. */
  31227. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31228. show the "icons with text" option on its choice of toolbar styles. */
  31229. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31230. show the "text only" option on its choice of toolbar styles. */
  31231. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31232. show a button to reset the toolbar to its default set of items. */
  31233. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31234. };
  31235. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31236. The dialog contains a ToolbarItemPalette and various controls for editing other
  31237. aspects of the toolbar. This method will block and run the dialog box modally,
  31238. returning when the user closes it.
  31239. The factory is used to determine the set of items that will be shown on the
  31240. palette.
  31241. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31242. enum.
  31243. @see ToolbarItemPalette
  31244. */
  31245. void showCustomisationDialog (ToolbarItemFactory& factory,
  31246. const int optionFlags = allCustomisationOptionsEnabled);
  31247. /** Turns on or off the toolbar's editing mode, in which its items can be
  31248. rearranged by the user.
  31249. (In most cases it's easier just to use showCustomisationDialog() instead of
  31250. trying to enable editing directly).
  31251. @see ToolbarItemPalette
  31252. */
  31253. void setEditingActive (const bool editingEnabled);
  31254. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31255. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31256. methods.
  31257. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31258. */
  31259. enum ColourIds
  31260. {
  31261. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31262. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31263. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31264. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31265. over them. */
  31266. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31267. held down on them. */
  31268. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31269. when the style is set to iconsWithText or textOnly. */
  31270. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31271. the customisation dialog is active and the mouse moves over them. */
  31272. };
  31273. /** Returns a string that represents the toolbar's current set of items.
  31274. This lets you later restore the same item layout using restoreFromString().
  31275. @see restoreFromString
  31276. */
  31277. const String toString() const;
  31278. /** Restores a set of items that was previously stored in a string by the toString()
  31279. method.
  31280. The factory object is used to create any item components that are needed.
  31281. @see toString
  31282. */
  31283. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31284. const String& savedVersion);
  31285. /** @internal */
  31286. void paint (Graphics& g);
  31287. /** @internal */
  31288. void resized();
  31289. /** @internal */
  31290. void buttonClicked (Button*);
  31291. /** @internal */
  31292. void mouseDown (const MouseEvent&);
  31293. /** @internal */
  31294. bool isInterestedInDragSource (const String&, Component*);
  31295. /** @internal */
  31296. void itemDragMove (const String&, Component*, int, int);
  31297. /** @internal */
  31298. void itemDragExit (const String&, Component*);
  31299. /** @internal */
  31300. void itemDropped (const String&, Component*, int, int);
  31301. /** @internal */
  31302. void updateAllItemPositions (const bool animate);
  31303. /** @internal */
  31304. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31305. juce_UseDebuggingNewOperator
  31306. private:
  31307. Button* missingItemsButton;
  31308. bool vertical, isEditingActive;
  31309. ToolbarItemStyle toolbarStyle;
  31310. ComponentAnimator animator;
  31311. friend class MissingItemsComponent;
  31312. Array <ToolbarItemComponent*> items;
  31313. friend class ItemDragAndDropOverlayComponent;
  31314. static const tchar* const toolbarDragDescriptor;
  31315. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31316. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31317. Toolbar (const Toolbar&);
  31318. const Toolbar& operator= (const Toolbar&);
  31319. };
  31320. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31321. /********* End of inlined file: juce_Toolbar.h *********/
  31322. class ItemDragAndDropOverlayComponent;
  31323. /**
  31324. A component that can be used as one of the items in a Toolbar.
  31325. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31326. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31327. class for further info about creating them.
  31328. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31329. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31330. calling the constructor, and override contentAreaChanged(), in which you can position
  31331. any sub-components you need to add.
  31332. To add basic buttons without writing a special subclass, have a look at the
  31333. ToolbarButton class.
  31334. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31335. */
  31336. class JUCE_API ToolbarItemComponent : public Button
  31337. {
  31338. public:
  31339. /** Constructor.
  31340. @param itemId the ID of the type of toolbar item which this represents
  31341. @param labelText the text to display if the toolbar's style is set to
  31342. Toolbar::iconsWithText or Toolbar::textOnly
  31343. @param isBeingUsedAsAButton set this to false if you don't want the button
  31344. to draw itself with button over/down states when the mouse
  31345. moves over it or clicks
  31346. */
  31347. ToolbarItemComponent (const int itemId,
  31348. const String& labelText,
  31349. const bool isBeingUsedAsAButton);
  31350. /** Destructor. */
  31351. ~ToolbarItemComponent();
  31352. /** Returns the item type ID that this component represents.
  31353. This value is in the constructor.
  31354. */
  31355. int getItemId() const throw() { return itemId; }
  31356. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31357. inside one.
  31358. */
  31359. Toolbar* getToolbar() const;
  31360. /** Returns true if this component is currently inside a toolbar which is vertical.
  31361. @see Toolbar::isVertical
  31362. */
  31363. bool isToolbarVertical() const;
  31364. /** Returns the current style setting of this item.
  31365. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31366. @see setStyle, Toolbar::getStyle
  31367. */
  31368. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31369. /** Changes the current style setting of this item.
  31370. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31371. by the toolbar that holds this item.
  31372. @see setStyle, Toolbar::setStyle
  31373. */
  31374. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31375. /** Returns the area of the component that should be used to display the button image or
  31376. other contents of the item.
  31377. This content area may change when the item's style changes, and may leave a space around the
  31378. edge of the component where the text label can be shown.
  31379. @see contentAreaChanged
  31380. */
  31381. const Rectangle getContentArea() const throw() { return contentArea; }
  31382. /** This method must return the size criteria for this item, based on a given toolbar
  31383. size and orientation.
  31384. The preferredSize, minSize and maxSize values must all be set by your implementation
  31385. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31386. toolbar, they refer to the item's height.
  31387. The preferredSize is the size that the component would like to be, and this must be
  31388. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31389. the same value.
  31390. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31391. Toolbar::getThickness().
  31392. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31393. vertically.
  31394. */
  31395. virtual bool getToolbarItemSizes (int toolbarThickness,
  31396. bool isToolbarVertical,
  31397. int& preferredSize,
  31398. int& minSize,
  31399. int& maxSize) = 0;
  31400. /** Your subclass should use this method to draw its content area.
  31401. The graphics object that is passed-in will have been clipped and had its origin
  31402. moved to fit the content area as specified get getContentArea(). The width and height
  31403. parameters are the width and height of the content area.
  31404. If the component you're writing isn't a button, you can just do nothing in this method.
  31405. */
  31406. virtual void paintButtonArea (Graphics& g,
  31407. int width, int height,
  31408. bool isMouseOver, bool isMouseDown) = 0;
  31409. /** Callback to indicate that the content area of this item has changed.
  31410. This might be because the component was resized, or because the style changed and
  31411. the space needed for the text label is different.
  31412. See getContentArea() for a description of what the area is.
  31413. */
  31414. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31415. /** Editing modes.
  31416. These are used by setEditingMode(), but will be rarely needed in user code.
  31417. */
  31418. enum ToolbarEditingMode
  31419. {
  31420. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31421. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31422. customisation mode, and the items can be dragged around. */
  31423. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31424. dragged onto a toolbar to add it to that bar.*/
  31425. };
  31426. /** Changes the editing mode of this component.
  31427. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31428. and is unlikely to be of much use in end-user-code.
  31429. */
  31430. void setEditingMode (const ToolbarEditingMode newMode);
  31431. /** Returns the current editing mode of this component.
  31432. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31433. and is unlikely to be of much use in end-user-code.
  31434. */
  31435. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31436. /** @internal */
  31437. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31438. /** @internal */
  31439. void resized();
  31440. juce_UseDebuggingNewOperator
  31441. private:
  31442. friend class Toolbar;
  31443. friend class ItemDragAndDropOverlayComponent;
  31444. const int itemId;
  31445. ToolbarEditingMode mode;
  31446. Toolbar::ToolbarItemStyle toolbarStyle;
  31447. Component* overlayComp;
  31448. int dragOffsetX, dragOffsetY;
  31449. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31450. Rectangle contentArea;
  31451. ToolbarItemComponent (const ToolbarItemComponent&);
  31452. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31453. };
  31454. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31455. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31456. /**
  31457. A type of button designed to go on a toolbar.
  31458. This simple button can have two Drawable objects specified - one for normal
  31459. use and another one (optionally) for the button's "on" state if it's a
  31460. toggle button.
  31461. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31462. */
  31463. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31464. {
  31465. public:
  31466. /** Creates a ToolbarButton.
  31467. @param itemId the ID for this toolbar item type. This is passed through to the
  31468. ToolbarItemComponent constructor
  31469. @param labelText the text to display on the button (if the toolbar is using a style
  31470. that shows text labels). This is passed through to the
  31471. ToolbarItemComponent constructor
  31472. @param normalImage a drawable object that the button should use as its icon. The object
  31473. that is passed-in here will be kept by this object and will be
  31474. deleted when no longer needed or when this button is deleted.
  31475. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31476. is in a toggled-on state (see the Button::getToggleState() method). If
  31477. 0 is passed-in here, then the normal image will be used instead, regardless
  31478. of the toggle state. The object that is passed-in here will be kept by
  31479. this object and will be deleted when no longer needed or when this button
  31480. is deleted.
  31481. */
  31482. ToolbarButton (const int itemId,
  31483. const String& labelText,
  31484. Drawable* const normalImage,
  31485. Drawable* const toggledOnImage);
  31486. /** Destructor. */
  31487. ~ToolbarButton();
  31488. /** @internal */
  31489. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31490. int& minSize, int& maxSize);
  31491. /** @internal */
  31492. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31493. /** @internal */
  31494. void contentAreaChanged (const Rectangle& newBounds);
  31495. juce_UseDebuggingNewOperator
  31496. private:
  31497. Drawable* const normalImage;
  31498. Drawable* const toggledOnImage;
  31499. ToolbarButton (const ToolbarButton&);
  31500. const ToolbarButton& operator= (const ToolbarButton&);
  31501. };
  31502. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31503. /********* End of inlined file: juce_ToolbarButton.h *********/
  31504. #endif
  31505. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31506. #endif
  31507. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31508. /********* Start of inlined file: juce_GlowEffect.h *********/
  31509. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31510. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31511. /**
  31512. A component effect that adds a coloured blur around the component's contents.
  31513. (This will only work on non-opaque components).
  31514. @see Component::setComponentEffect, DropShadowEffect
  31515. */
  31516. class JUCE_API GlowEffect : public ImageEffectFilter
  31517. {
  31518. public:
  31519. /** Creates a default 'glow' effect.
  31520. To customise its appearance, use the setGlowProperties() method.
  31521. */
  31522. GlowEffect();
  31523. /** Destructor. */
  31524. ~GlowEffect();
  31525. /** Sets the glow's radius and colour.
  31526. The radius is how large the blur should be, and the colour is
  31527. used to render it (for a less intense glow, lower the colour's
  31528. opacity).
  31529. */
  31530. void setGlowProperties (const float newRadius,
  31531. const Colour& newColour);
  31532. /** @internal */
  31533. void applyEffect (Image& sourceImage, Graphics& destContext);
  31534. juce_UseDebuggingNewOperator
  31535. private:
  31536. float radius;
  31537. Colour colour;
  31538. };
  31539. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31540. /********* End of inlined file: juce_GlowEffect.h *********/
  31541. #endif
  31542. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31543. #endif
  31544. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31545. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31546. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31547. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31548. /**
  31549. An effect filter that reduces the image's opacity.
  31550. This can be used to make a component (and its child components) more
  31551. transparent.
  31552. @see Component::setComponentEffect
  31553. */
  31554. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31555. {
  31556. public:
  31557. /** Creates the effect object.
  31558. The opacity of the component to which the effect is applied will be
  31559. scaled by the given factor (in the range 0 to 1.0f).
  31560. */
  31561. ReduceOpacityEffect (const float opacity = 1.0f);
  31562. /** Destructor. */
  31563. ~ReduceOpacityEffect();
  31564. /** Sets how much to scale the component's opacity.
  31565. @param newOpacity should be between 0 and 1.0f
  31566. */
  31567. void setOpacity (const float newOpacity);
  31568. /** @internal */
  31569. void applyEffect (Image& sourceImage, Graphics& destContext);
  31570. juce_UseDebuggingNewOperator
  31571. private:
  31572. float opacity;
  31573. };
  31574. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31575. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31576. #endif
  31577. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31578. #endif
  31579. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31580. #endif
  31581. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31582. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31583. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31584. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31585. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31586. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31587. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31588. /**
  31589. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31590. command in a ApplicationCommandManager.
  31591. Normally, you won't actually create a KeyPressMappingSet directly, because
  31592. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  31593. you'd create yourself an ApplicationCommandManager, and call its
  31594. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  31595. KeyPressMappingSet.
  31596. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  31597. to the top-level component for which you want to handle keystrokes. So for example:
  31598. @code
  31599. class MyMainWindow : public Component
  31600. {
  31601. ApplicationCommandManager* myCommandManager;
  31602. public:
  31603. MyMainWindow()
  31604. {
  31605. myCommandManager = new ApplicationCommandManager();
  31606. // first, make sure the command manager has registered all the commands that its
  31607. // targets can perform..
  31608. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  31609. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  31610. // this will use the command manager to initialise the KeyPressMappingSet with
  31611. // the default keypresses that were specified when the targets added their commands
  31612. // to the manager.
  31613. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  31614. // having set up the default key-mappings, you might now want to load the last set
  31615. // of mappings that the user configured.
  31616. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  31617. // Now tell our top-level window to send any keypresses that arrive to the
  31618. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  31619. addKeyListener (myCommandManager->getKeyMappings());
  31620. }
  31621. ...
  31622. }
  31623. @endcode
  31624. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  31625. register to be told when a command or mapping is added, removed, etc.
  31626. There's also a UI component called KeyMappingEditorComponent that can be used
  31627. to easily edit the key mappings.
  31628. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  31629. */
  31630. class JUCE_API KeyPressMappingSet : public KeyListener,
  31631. public ChangeBroadcaster,
  31632. public FocusChangeListener
  31633. {
  31634. public:
  31635. /** Creates a KeyPressMappingSet for a given command manager.
  31636. Normally, you won't actually create a KeyPressMappingSet directly, because
  31637. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  31638. best thing to do is to create your ApplicationCommandManager, and use the
  31639. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  31640. When a suitable keypress happens, the manager's invoke() method will be
  31641. used to invoke the appropriate command.
  31642. @see ApplicationCommandManager
  31643. */
  31644. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  31645. /** Creates an copy of a KeyPressMappingSet. */
  31646. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  31647. /** Destructor. */
  31648. ~KeyPressMappingSet();
  31649. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  31650. /** Returns a list of keypresses that are assigned to a particular command.
  31651. @param commandID the command's ID
  31652. */
  31653. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  31654. /** Assigns a keypress to a command.
  31655. If the keypress is already assigned to a different command, it will first be
  31656. removed from that command, to avoid it triggering multiple functions.
  31657. @param commandID the ID of the command that you want to add a keypress to. If
  31658. this is 0, the keypress will be removed from anything that it
  31659. was previously assigned to, but not re-assigned
  31660. @param newKeyPress the new key-press
  31661. @param insertIndex if this is less than zero, the key will be appended to the
  31662. end of the list of keypresses; otherwise the new keypress will
  31663. be inserted into the existing list at this index
  31664. */
  31665. void addKeyPress (const CommandID commandID,
  31666. const KeyPress& newKeyPress,
  31667. int insertIndex = -1) throw();
  31668. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  31669. @see resetToDefaultMapping
  31670. */
  31671. void resetToDefaultMappings() throw();
  31672. /** Resets all key-mappings to the defaults for a particular command.
  31673. @see resetToDefaultMappings
  31674. */
  31675. void resetToDefaultMapping (const CommandID commandID) throw();
  31676. /** Removes all keypresses that are assigned to any commands. */
  31677. void clearAllKeyPresses() throw();
  31678. /** Removes all keypresses that are assigned to a particular command. */
  31679. void clearAllKeyPresses (const CommandID commandID) throw();
  31680. /** Removes one of the keypresses that are assigned to a command.
  31681. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  31682. which the keyPressIndex refers.
  31683. */
  31684. void removeKeyPress (const CommandID commandID,
  31685. const int keyPressIndex) throw();
  31686. /** Removes a keypress from any command that it may be assigned to.
  31687. */
  31688. void removeKeyPress (const KeyPress& keypress) throw();
  31689. /** Returns true if the given command is linked to this key. */
  31690. bool containsMapping (const CommandID commandID,
  31691. const KeyPress& keyPress) const throw();
  31692. /** Looks for a command that corresponds to a keypress.
  31693. @returns the UID of the command or 0 if none was found
  31694. */
  31695. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  31696. /** Tries to recreate the mappings from a previously stored state.
  31697. The XML passed in must have been created by the createXml() method.
  31698. If the stored state makes any reference to commands that aren't
  31699. currently available, these will be ignored.
  31700. If the set of mappings being loaded was a set of differences (using createXml (true)),
  31701. then this will call resetToDefaultMappings() and then merge the saved mappings
  31702. on top. If the saved set was created with createXml (false), then this method
  31703. will first clear all existing mappings and load the saved ones as a complete set.
  31704. @returns true if it manages to load the XML correctly
  31705. @see createXml
  31706. */
  31707. bool restoreFromXml (const XmlElement& xmlVersion);
  31708. /** Creates an XML representation of the current mappings.
  31709. This will produce a lump of XML that can be later reloaded using
  31710. restoreFromXml() to recreate the current mapping state.
  31711. The object that is returned must be deleted by the caller.
  31712. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  31713. will be saved into the XML. If it's true, then the XML will
  31714. only store the differences between the current mappings and
  31715. the default mappings you'd get from calling resetToDefaultMappings().
  31716. The advantage of saving a set of differences from the default is that
  31717. if you change the default mappings (in a new version of your app, for
  31718. example), then these will be merged into a user's saved preferences.
  31719. @see restoreFromXml
  31720. */
  31721. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  31722. /** @internal */
  31723. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31724. /** @internal */
  31725. bool keyStateChanged (Component* originatingComponent);
  31726. /** @internal */
  31727. void globalFocusChanged (Component* focusedComponent);
  31728. juce_UseDebuggingNewOperator
  31729. private:
  31730. ApplicationCommandManager* commandManager;
  31731. struct CommandMapping
  31732. {
  31733. CommandID commandID;
  31734. Array <KeyPress> keypresses;
  31735. bool wantsKeyUpDownCallbacks;
  31736. };
  31737. OwnedArray <CommandMapping> mappings;
  31738. struct KeyPressTime
  31739. {
  31740. KeyPress key;
  31741. uint32 timeWhenPressed;
  31742. };
  31743. OwnedArray <KeyPressTime> keysDown;
  31744. void handleMessage (const Message& message);
  31745. void invokeCommand (const CommandID commandID,
  31746. const KeyPress& keyPress,
  31747. const bool isKeyDown,
  31748. const int millisecsSinceKeyPressed,
  31749. Component* const originatingComponent) const;
  31750. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  31751. };
  31752. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31753. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  31754. /********* Start of inlined file: juce_TreeView.h *********/
  31755. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  31756. #define __JUCE_TREEVIEW_JUCEHEADER__
  31757. class TreeView;
  31758. /**
  31759. An item in a treeview.
  31760. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  31761. own sub-items.
  31762. To implement an item that contains sub-items, override the itemOpennessChanged()
  31763. method so that when it is opened, it adds the new sub-items to itself using the
  31764. addSubItem method. Depending on the nature of the item it might choose to only
  31765. do this the first time it's opened, or it might want to refresh itself each time.
  31766. It also has the option of deleting its sub-items when it is closed, or leaving them
  31767. in place.
  31768. */
  31769. class JUCE_API TreeViewItem
  31770. {
  31771. public:
  31772. /** Constructor. */
  31773. TreeViewItem();
  31774. /** Destructor. */
  31775. virtual ~TreeViewItem();
  31776. /** Returns the number of sub-items that have been added to this item.
  31777. Note that this doesn't mean much if the node isn't open.
  31778. @see getSubItem, mightContainSubItems, addSubItem
  31779. */
  31780. int getNumSubItems() const throw();
  31781. /** Returns one of the item's sub-items.
  31782. Remember that the object returned might get deleted at any time when its parent
  31783. item is closed or refreshed, depending on the nature of the items you're using.
  31784. @see getNumSubItems
  31785. */
  31786. TreeViewItem* getSubItem (const int index) const throw();
  31787. /** Removes any sub-items. */
  31788. void clearSubItems();
  31789. /** Adds a sub-item.
  31790. @param newItem the object to add to the item's sub-item list. Once added, these can be
  31791. found using getSubItem(). When the items are later removed with
  31792. removeSubItem() (or when this item is deleted), they will be deleted.
  31793. @param insertPosition the index which the new item should have when it's added. If this
  31794. value is less than 0, the item will be added to the end of the list.
  31795. */
  31796. void addSubItem (TreeViewItem* const newItem,
  31797. const int insertPosition = -1);
  31798. /** Removes one of the sub-items.
  31799. @param index the item to remove
  31800. @param deleteItem if true, the item that is removed will also be deleted.
  31801. */
  31802. void removeSubItem (const int index,
  31803. const bool deleteItem = true);
  31804. /** Returns the TreeView to which this item belongs. */
  31805. TreeView* getOwnerView() const throw() { return ownerView; }
  31806. /** Returns the item within which this item is contained. */
  31807. TreeViewItem* getParentItem() const throw() { return parentItem; }
  31808. /** True if this item is currently open in the treeview. */
  31809. bool isOpen() const throw();
  31810. /** Opens or closes the item.
  31811. When opened or closed, the item's itemOpennessChanged() method will be called,
  31812. and a subclass should use this callback to create and add any sub-items that
  31813. it needs to.
  31814. @see itemOpennessChanged, mightContainSubItems
  31815. */
  31816. void setOpen (const bool shouldBeOpen);
  31817. /** True if this item is currently selected.
  31818. Use this when painting the node, to decide whether to draw it as selected or not.
  31819. */
  31820. bool isSelected() const throw();
  31821. /** Selects or deselects the item.
  31822. This will cause a callback to itemSelectionChanged()
  31823. */
  31824. void setSelected (const bool shouldBeSelected,
  31825. const bool deselectOtherItemsFirst);
  31826. /** Returns the rectangle that this item occupies.
  31827. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  31828. top-left of the TreeView comp, so this will depend on the scroll-position of
  31829. the tree. If false, it is relative to the top-left of the topmost item in the
  31830. tree (so this would be unaffected by scrolling the view).
  31831. */
  31832. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  31833. /** Sends a signal to the treeview to make it refresh itself.
  31834. Call this if your items have changed and you want the tree to update to reflect
  31835. this.
  31836. */
  31837. void treeHasChanged() const throw();
  31838. /** Returns the row number of this item in the tree.
  31839. The row number of an item will change according to which items are open.
  31840. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  31841. */
  31842. int getRowNumberInTree() const throw();
  31843. /** Changes whether lines are drawn to connect any sub-items to this item.
  31844. By default, line-drawing is turned on.
  31845. */
  31846. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  31847. /** Tells the tree whether this item can potentially be opened.
  31848. If your item could contain sub-items, this should return true; if it returns
  31849. false then the tree will not try to open the item. This determines whether or
  31850. not the item will be drawn with a 'plus' button next to it.
  31851. */
  31852. virtual bool mightContainSubItems() = 0;
  31853. /** Returns a string to uniquely identify this item.
  31854. If you're planning on using the TreeView::getOpennessState() method, then
  31855. these strings will be used to identify which nodes are open. The string
  31856. should be unique amongst the item's sibling items, but it's ok for there
  31857. to be duplicates at other levels of the tree.
  31858. If you're not going to store the state, then it's ok not to bother implementing
  31859. this method.
  31860. */
  31861. virtual const String getUniqueName() const;
  31862. /** Called when an item is opened or closed.
  31863. When setOpen() is called and the item has specified that it might
  31864. have sub-items with the mightContainSubItems() method, this method
  31865. is called to let the item create or manage its sub-items.
  31866. So when this is called with isNowOpen set to true (i.e. when the item is being
  31867. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  31868. refresh its sub-item list.
  31869. When this is called with isNowOpen set to false, the subclass might want
  31870. to use clearSubItems() to save on space, or it might choose to leave them,
  31871. depending on the nature of the tree.
  31872. You could also use this callback as a trigger to start a background process
  31873. which asynchronously creates sub-items and adds them, if that's more
  31874. appropriate for the task in hand.
  31875. @see mightContainSubItems
  31876. */
  31877. virtual void itemOpennessChanged (bool isNowOpen);
  31878. /** Must return the width required by this item.
  31879. If your item needs to have a particular width in pixels, return that value; if
  31880. you'd rather have it just fill whatever space is available in the treeview,
  31881. return -1.
  31882. If all your items return -1, no horizontal scrollbar will be shown, but if any
  31883. items have fixed widths and extend beyond the width of the treeview, a
  31884. scrollbar will appear.
  31885. Each item can be a different width, but if they change width, you should call
  31886. treeHasChanged() to update the tree.
  31887. */
  31888. virtual int getItemWidth() const { return -1; }
  31889. /** Must return the height required by this item.
  31890. This is the height in pixels that the item will take up. Items in the tree
  31891. can be different heights, but if they change height, you should call
  31892. treeHasChanged() to update the tree.
  31893. */
  31894. virtual int getItemHeight() const { return 20; }
  31895. /** Creates a component that will be used to represent this item.
  31896. You don't have to implement this method - if it returns 0 then no component
  31897. will be used for the item, and you can just draw it using the paintItem()
  31898. callback. But if you do return a component, it will be positioned in the
  31899. treeview so that it can be used to represent this item.
  31900. The component returned will be managed by the treeview, so always return
  31901. a new component, and don't keep a reference to it, as the treeview will
  31902. delete it later when it goes off the screen or is no longer needed. Also
  31903. bear in mind that if the component keeps a reference to the item that
  31904. created it, that item could be deleted before the component. Its position
  31905. and size will be completely managed by the tree, so don't attempt to move it
  31906. around.
  31907. Something you may want to do with your component is to give it a pointer to
  31908. the TreeView that created it. This is perfectly safe, and there's no danger
  31909. of it becoming a dangling pointer because the TreeView will always delete
  31910. the component before it is itself deleted.
  31911. As long as you stick to these rules you can return whatever kind of
  31912. component you like. It's most useful if you're doing things like drag-and-drop
  31913. of items, or want to use a Label component to edit item names, etc.
  31914. */
  31915. virtual Component* createItemComponent() { return 0; }
  31916. /** Draws the item's contents.
  31917. You can choose to either implement this method and draw each item, or you
  31918. can use createItemComponent() to create a component that will represent the
  31919. item.
  31920. If all you need in your tree is to be able to draw the items and detect when
  31921. the user selects or double-clicks one of them, it's probably enough to
  31922. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  31923. complicated interactions, you may need to use createItemComponent() instead.
  31924. @param g the graphics context to draw into
  31925. @param width the width of the area available for drawing
  31926. @param height the height of the area available for drawing
  31927. */
  31928. virtual void paintItem (Graphics& g, int width, int height);
  31929. /** Called when the user clicks on this item.
  31930. If you're using createItemComponent() to create a custom component for the
  31931. item, the mouse-clicks might not make it through to the treeview, but this
  31932. is how you find out about clicks when just drawing each item individually.
  31933. The associated mouse-event details are passed in, so you can find out about
  31934. which button, where it was, etc.
  31935. @see itemDoubleClicked
  31936. */
  31937. virtual void itemClicked (const MouseEvent& e);
  31938. /** Called when the user double-clicks on this item.
  31939. If you're using createItemComponent() to create a custom component for the
  31940. item, the mouse-clicks might not make it through to the treeview, but this
  31941. is how you find out about clicks when just drawing each item individually.
  31942. The associated mouse-event details are passed in, so you can find out about
  31943. which button, where it was, etc.
  31944. If not overridden, the base class method here will open or close the item as
  31945. if the 'plus' button had been clicked.
  31946. @see itemClicked
  31947. */
  31948. virtual void itemDoubleClicked (const MouseEvent& e);
  31949. /** Called when the item is selected or deselected.
  31950. Use this if you want to do something special when the item's selectedness
  31951. changes. By default it'll get repainted when this happens.
  31952. */
  31953. virtual void itemSelectionChanged (bool isNowSelected);
  31954. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  31955. If this returns a non-empty name then when the user drags an item, the treeview will
  31956. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  31957. a drag-and-drop operation, using this string as the source description, with the treeview
  31958. itself as the source component.
  31959. If you need more complex drag-and-drop behaviour, you can use custom components for
  31960. the items, and use those to trigger the drag.
  31961. @see DragAndDropContainer::startDragging
  31962. */
  31963. virtual const String getDragSourceDescription();
  31964. juce_UseDebuggingNewOperator
  31965. private:
  31966. TreeView* ownerView;
  31967. TreeViewItem* parentItem;
  31968. OwnedArray <TreeViewItem> subItems;
  31969. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  31970. int uid;
  31971. bool selected : 1;
  31972. bool redrawNeeded : 1;
  31973. bool drawLinesInside : 1;
  31974. unsigned int openness : 2;
  31975. friend class TreeView;
  31976. friend class TreeViewContentComponent;
  31977. void updatePositions (int newY);
  31978. int getIndentX() const throw();
  31979. void setOwnerView (TreeView* const newOwner) throw();
  31980. void paintRecursively (Graphics& g, int width);
  31981. TreeViewItem* findItemRecursively (int y) throw();
  31982. TreeViewItem* getDeepestOpenParentItem() throw();
  31983. void restoreFromXml (const XmlElement& e);
  31984. XmlElement* createXmlOpenness() const;
  31985. bool isLastOfSiblings() const throw();
  31986. TreeViewItem* getTopLevelItem() throw();
  31987. int getNumRows() const throw();
  31988. TreeViewItem* getItemOnRow (int index) throw();
  31989. void deselectAllRecursively();
  31990. int countSelectedItemsRecursively() const throw();
  31991. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  31992. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  31993. TreeViewItem (const TreeViewItem&);
  31994. const TreeViewItem& operator= (const TreeViewItem&);
  31995. };
  31996. /**
  31997. A tree-view component.
  31998. Use one of these to hold and display a structure of TreeViewItem objects.
  31999. */
  32000. class JUCE_API TreeView : public Component,
  32001. public SettableTooltipClient,
  32002. private AsyncUpdater
  32003. {
  32004. public:
  32005. /** Creates an empty treeview.
  32006. Once you've got a treeview component, you'll need to give it something to
  32007. display, using the setRootItem() method.
  32008. */
  32009. TreeView (const String& componentName = String::empty);
  32010. /** Destructor. */
  32011. ~TreeView();
  32012. /** Sets the item that is displayed in the treeview.
  32013. A tree has a single root item which contains as many sub-items as it needs. If
  32014. you want the tree to contain a number of root items, you should still use a single
  32015. root item above these, but hide it using setRootItemVisible().
  32016. You can pass in 0 to this method to clear the tree and remove its current root item.
  32017. The object passed in will not be deleted by the treeview, it's up to the caller
  32018. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32019. this item until you've removed it from the tree, either by calling setRootItem (0),
  32020. or by deleting the tree first.
  32021. */
  32022. void setRootItem (TreeViewItem* const newRootItem);
  32023. /** Returns the tree's root item.
  32024. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32025. */
  32026. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32027. /** Changes whether the tree's root item is shown or not.
  32028. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32029. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32030. will also make sure the root item is open (otherwise the treeview would look empty).
  32031. */
  32032. void setRootItemVisible (const bool shouldBeVisible);
  32033. /** Returns true if the root item is visible.
  32034. @see setRootItemVisible
  32035. */
  32036. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32037. /** Sets whether items are open or closed by default.
  32038. Normally, items are closed until the user opens them, but you can use this
  32039. to make them default to being open until explicitly closed.
  32040. @see areItemsOpenByDefault
  32041. */
  32042. void setDefaultOpenness (const bool isOpenByDefault);
  32043. /** Returns true if the tree's items default to being open.
  32044. @see setDefaultOpenness
  32045. */
  32046. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32047. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32048. You can always select multiple items internally by calling the
  32049. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32050. is allowed to multi-select by clicking on the tree.
  32051. By default it is disabled.
  32052. @see isMultiSelectEnabled
  32053. */
  32054. void setMultiSelectEnabled (const bool canMultiSelect);
  32055. /** Returns whether multi-select has been enabled for the tree.
  32056. @see setMultiSelectEnabled
  32057. */
  32058. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32059. /** Deselects any items that are currently selected. */
  32060. void clearSelectedItems();
  32061. /** Returns the number of items that are currently selected.
  32062. @see getSelectedItem, clearSelectedItems
  32063. */
  32064. int getNumSelectedItems() const throw();
  32065. /** Returns one of the selected items in the tree.
  32066. @param index the index, 0 to (getNumSelectedItems() - 1)
  32067. */
  32068. TreeViewItem* getSelectedItem (const int index) const throw();
  32069. /** Returns the number of rows the tree is using.
  32070. This will depend on which items are open.
  32071. @see TreeViewItem::getRowNumberInTree()
  32072. */
  32073. int getNumRowsInTree() const;
  32074. /** Returns the item on a particular row of the tree.
  32075. If the index is out of range, this will return 0.
  32076. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  32077. */
  32078. TreeViewItem* getItemOnRow (int index) const;
  32079. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  32080. void scrollToKeepItemVisible (TreeViewItem* item);
  32081. /** Returns the treeview's Viewport object. */
  32082. Viewport* getViewport() const throw() { return viewport; }
  32083. /** Returns the number of pixels by which each nested level of the tree is indented.
  32084. @see setIndentSize
  32085. */
  32086. int getIndentSize() const throw() { return indentSize; }
  32087. /** Changes the distance by which each nested level of the tree is indented.
  32088. @see getIndentSize
  32089. */
  32090. void setIndentSize (const int newIndentSize);
  32091. /** Saves the current state of open/closed nodes so it can be restored later.
  32092. This takes a snapshot of which nodes have been explicitly opened or closed,
  32093. and records it as XML. To identify node objects it uses the
  32094. TreeViewItem::getUniqueName() method to create named paths. This
  32095. means that the same state of open/closed nodes can be restored to a
  32096. completely different instance of the tree, as long as it contains nodes
  32097. whose unique names are the same.
  32098. The caller is responsible for deleting the object that is returned.
  32099. @param alsoIncludeScrollPosition if this is true, the state will also
  32100. include information about where the
  32101. tree has been scrolled to vertically,
  32102. so this can also be restored
  32103. @see restoreOpennessState
  32104. */
  32105. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32106. /** Restores a previously saved arrangement of open/closed nodes.
  32107. This will try to restore a snapshot of the tree's state that was created by
  32108. the getOpennessState() method. If any of the nodes named in the original
  32109. XML aren't present in this tree, they will be ignored.
  32110. @see getOpennessState
  32111. */
  32112. void restoreOpennessState (const XmlElement& newState);
  32113. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32114. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32115. methods.
  32116. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32117. */
  32118. enum ColourIds
  32119. {
  32120. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32121. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32122. };
  32123. /** @internal */
  32124. void paint (Graphics& g);
  32125. /** @internal */
  32126. void resized();
  32127. /** @internal */
  32128. bool keyPressed (const KeyPress& key);
  32129. /** @internal */
  32130. void colourChanged();
  32131. juce_UseDebuggingNewOperator
  32132. private:
  32133. friend class TreeViewItem;
  32134. friend class TreeViewContentComponent;
  32135. Viewport* viewport;
  32136. CriticalSection nodeAlterationLock;
  32137. TreeViewItem* rootItem;
  32138. int indentSize;
  32139. bool defaultOpenness : 1;
  32140. bool needsRecalculating : 1;
  32141. bool rootItemVisible : 1;
  32142. bool multiSelectEnabled : 1;
  32143. void itemsChanged() throw();
  32144. void handleAsyncUpdate();
  32145. void moveSelectedRow (int delta);
  32146. TreeView (const TreeView&);
  32147. const TreeView& operator= (const TreeView&);
  32148. };
  32149. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32150. /********* End of inlined file: juce_TreeView.h *********/
  32151. /**
  32152. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32153. object.
  32154. @see KeyPressMappingSet
  32155. */
  32156. class JUCE_API KeyMappingEditorComponent : public Component,
  32157. public TreeViewItem,
  32158. public ChangeListener,
  32159. private ButtonListener
  32160. {
  32161. public:
  32162. /** Creates a KeyMappingEditorComponent.
  32163. @param mappingSet this is the set of mappings to display and
  32164. edit. Make sure the mappings object is not
  32165. deleted before this component!
  32166. @param showResetToDefaultButton if true, then at the bottom of the
  32167. list, the component will include a 'reset to
  32168. defaults' button.
  32169. */
  32170. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32171. const bool showResetToDefaultButton);
  32172. /** Destructor. */
  32173. virtual ~KeyMappingEditorComponent();
  32174. /** Sets up the colours to use for parts of the component.
  32175. @param mainBackground colour to use for most of the background
  32176. @param textColour colour to use for the text
  32177. */
  32178. void setColours (const Colour& mainBackground,
  32179. const Colour& textColour);
  32180. /** Returns the KeyPressMappingSet that this component is acting upon.
  32181. */
  32182. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32183. /** Can be overridden if some commands need to be excluded from the list.
  32184. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32185. method to decide what to return, but you can override it to handle special cases.
  32186. */
  32187. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32188. /** Can be overridden to indicate that some commands are shown as read-only.
  32189. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32190. method to decide what to return, but you can override it to handle special cases.
  32191. */
  32192. virtual bool isCommandReadOnly (const CommandID commandID);
  32193. /** This can be overridden to let you change the format of the string used
  32194. to describe a keypress.
  32195. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32196. keys that are triggered by something else externally. If you override the
  32197. method, be sure to let the base class's method handle keys you're not
  32198. interested in.
  32199. */
  32200. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32201. /** @internal */
  32202. void parentHierarchyChanged();
  32203. /** @internal */
  32204. void resized();
  32205. /** @internal */
  32206. void changeListenerCallback (void*);
  32207. /** @internal */
  32208. bool mightContainSubItems();
  32209. /** @internal */
  32210. const String getUniqueName() const;
  32211. /** @internal */
  32212. void buttonClicked (Button* button);
  32213. juce_UseDebuggingNewOperator
  32214. private:
  32215. KeyPressMappingSet* mappings;
  32216. TreeView* tree;
  32217. friend class KeyMappingTreeViewItem;
  32218. friend class KeyCategoryTreeViewItem;
  32219. friend class KeyMappingItemComponent;
  32220. friend class KeyMappingChangeButton;
  32221. Colour backgroundColour, textColour;
  32222. TextButton* resetButton;
  32223. void assignNewKey (const CommandID commandID, int index);
  32224. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32225. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32226. };
  32227. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32228. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32229. #endif
  32230. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32231. #endif
  32232. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32233. #endif
  32234. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32235. #endif
  32236. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32237. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32238. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32239. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32240. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32241. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32242. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32243. class MenuBarModel;
  32244. /**
  32245. A class to receive callbacks when a MenuBarModel changes.
  32246. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32247. */
  32248. class JUCE_API MenuBarModelListener
  32249. {
  32250. public:
  32251. /** Destructor. */
  32252. virtual ~MenuBarModelListener() {}
  32253. /** This callback is made when items are changed in the menu bar model.
  32254. */
  32255. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32256. /** This callback is made when an application command is invoked that
  32257. is represented by one of the items in the menu bar model.
  32258. */
  32259. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32260. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32261. };
  32262. /**
  32263. A class for controlling MenuBar components.
  32264. This class is used to tell a MenuBar what menus to show, and to respond
  32265. to a menu being selected.
  32266. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32267. */
  32268. class JUCE_API MenuBarModel : private AsyncUpdater,
  32269. private ApplicationCommandManagerListener
  32270. {
  32271. public:
  32272. MenuBarModel() throw();
  32273. /** Destructor. */
  32274. virtual ~MenuBarModel();
  32275. /** Call this when some of your menu items have changed.
  32276. This method will cause a callback to any MenuBarListener objects that
  32277. are registered with this model.
  32278. If this model is displaying items from an ApplicationCommandManager, you
  32279. can use the setApplicationCommandManagerToWatch() method to cause
  32280. change messages to be sent automatically when the ApplicationCommandManager
  32281. is changed.
  32282. @see addListener, removeListener, MenuBarListener
  32283. */
  32284. void menuItemsChanged();
  32285. /** Tells the menu bar to listen to the specified command manager, and to update
  32286. itself when the commands change.
  32287. This will also allow it to flash a menu name when a command from that menu
  32288. is invoked using a keystroke.
  32289. */
  32290. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32291. /** Registers a listener for callbacks when the menu items in this model change.
  32292. The listener object will get callbacks when this object's menuItemsChanged()
  32293. method is called.
  32294. @see removeListener
  32295. */
  32296. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32297. /** Removes a listener.
  32298. @see addListener
  32299. */
  32300. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32301. /** This method must return a list of the names of the menus. */
  32302. virtual const StringArray getMenuBarNames() = 0;
  32303. /** This should return the popup menu to display for a given top-level menu.
  32304. @param topLevelMenuIndex the index of the top-level menu to show
  32305. @param menuName the name of the top-level menu item to show
  32306. */
  32307. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32308. const String& menuName) = 0;
  32309. /** This is called when a menu item has been clicked on.
  32310. @param menuItemID the item ID of the PopupMenu item that was selected
  32311. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32312. chosen (just in case you've used duplicate ID numbers
  32313. on more than one of the popup menus)
  32314. */
  32315. virtual void menuItemSelected (int menuItemID,
  32316. int topLevelMenuIndex) = 0;
  32317. #if JUCE_MAC || DOXYGEN
  32318. /** MAC ONLY - Sets the model that is currently being shown as the main
  32319. menu bar at the top of the screen on the Mac.
  32320. You can pass 0 to stop the current model being displayed. Be careful
  32321. not to delete a model while it is being used.
  32322. An optional extra menu can be specified, containing items to add to the top of
  32323. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  32324. an apple, it's the one next to it, with your application's name at the top
  32325. and the services menu etc on it). When one of these items is selected, the
  32326. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  32327. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  32328. object then newMenuBarModel must be non-null.
  32329. */
  32330. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  32331. const PopupMenu* extraAppleMenuItems = 0) throw();
  32332. /** MAC ONLY - Returns the menu model that is currently being shown as
  32333. the main menu bar.
  32334. */
  32335. static MenuBarModel* getMacMainMenu() throw();
  32336. #endif
  32337. /** @internal */
  32338. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32339. /** @internal */
  32340. void applicationCommandListChanged();
  32341. /** @internal */
  32342. void handleAsyncUpdate();
  32343. juce_UseDebuggingNewOperator
  32344. private:
  32345. ApplicationCommandManager* manager;
  32346. SortedSet <void*> listeners;
  32347. MenuBarModel (const MenuBarModel&);
  32348. const MenuBarModel& operator= (const MenuBarModel&);
  32349. };
  32350. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32351. /********* End of inlined file: juce_MenuBarModel.h *********/
  32352. /**
  32353. A menu bar component.
  32354. @see MenuBarModel
  32355. */
  32356. class JUCE_API MenuBarComponent : public Component,
  32357. private MenuBarModelListener,
  32358. private Timer
  32359. {
  32360. public:
  32361. /** Creates a menu bar.
  32362. @param model the model object to use to control this bar. You can
  32363. pass 0 into this if you like, and set the model later
  32364. using the setModel() method
  32365. */
  32366. MenuBarComponent (MenuBarModel* const model);
  32367. /** Destructor. */
  32368. ~MenuBarComponent();
  32369. /** Changes the model object to use to control the bar.
  32370. This can be 0, in which case the bar will be empty. Don't delete the object
  32371. that is passed-in while it's still being used by this MenuBar.
  32372. */
  32373. void setModel (MenuBarModel* const newModel);
  32374. /** Pops up one of the menu items.
  32375. This lets you manually open one of the menus - it could be triggered by a
  32376. key shortcut, for example.
  32377. */
  32378. void showMenu (const int menuIndex);
  32379. /** @internal */
  32380. void paint (Graphics& g);
  32381. /** @internal */
  32382. void resized();
  32383. /** @internal */
  32384. void mouseEnter (const MouseEvent& e);
  32385. /** @internal */
  32386. void mouseExit (const MouseEvent& e);
  32387. /** @internal */
  32388. void mouseDown (const MouseEvent& e);
  32389. /** @internal */
  32390. void mouseDrag (const MouseEvent& e);
  32391. /** @internal */
  32392. void mouseUp (const MouseEvent& e);
  32393. /** @internal */
  32394. void mouseMove (const MouseEvent& e);
  32395. /** @internal */
  32396. void inputAttemptWhenModal();
  32397. /** @internal */
  32398. void handleCommandMessage (int commandId);
  32399. /** @internal */
  32400. bool keyPressed (const KeyPress& key);
  32401. /** @internal */
  32402. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32403. /** @internal */
  32404. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32405. const ApplicationCommandTarget::InvocationInfo& info);
  32406. juce_UseDebuggingNewOperator
  32407. private:
  32408. MenuBarModel* model;
  32409. StringArray menuNames;
  32410. Array <int> xPositions;
  32411. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32412. int lastMouseX, lastMouseY;
  32413. bool inModalState;
  32414. Component* currentPopup;
  32415. int getItemAt (int x, int y);
  32416. void updateItemUnderMouse (const int x, const int y);
  32417. void hideCurrentMenu();
  32418. void timerCallback();
  32419. void repaintMenuItem (int index);
  32420. MenuBarComponent (const MenuBarComponent&);
  32421. const MenuBarComponent& operator= (const MenuBarComponent&);
  32422. };
  32423. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32424. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32425. #endif
  32426. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32427. #endif
  32428. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32429. #endif
  32430. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32431. #endif
  32432. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32433. /********* Start of inlined file: juce_ComponentDragger.h *********/
  32434. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32435. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32436. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32437. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32438. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32439. /**
  32440. A class that imposes restrictions on a Component's size or position.
  32441. This is used by classes such as ResizableCornerComponent,
  32442. ResizableBorderComponent and ResizableWindow.
  32443. The base class can impose some basic size and position limits, but you can
  32444. also subclass this for custom uses.
  32445. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  32446. */
  32447. class JUCE_API ComponentBoundsConstrainer
  32448. {
  32449. public:
  32450. /** When first created, the object will not impose any restrictions on the components. */
  32451. ComponentBoundsConstrainer() throw();
  32452. /** Destructor. */
  32453. virtual ~ComponentBoundsConstrainer();
  32454. /** Imposes a minimum width limit. */
  32455. void setMinimumWidth (const int minimumWidth) throw();
  32456. /** Returns the current minimum width. */
  32457. int getMinimumWidth() const throw() { return minW; }
  32458. /** Imposes a maximum width limit. */
  32459. void setMaximumWidth (const int maximumWidth) throw();
  32460. /** Returns the current maximum width. */
  32461. int getMaximumWidth() const throw() { return maxW; }
  32462. /** Imposes a minimum height limit. */
  32463. void setMinimumHeight (const int minimumHeight) throw();
  32464. /** Returns the current minimum height. */
  32465. int getMinimumHeight() const throw() { return minH; }
  32466. /** Imposes a maximum height limit. */
  32467. void setMaximumHeight (const int maximumHeight) throw();
  32468. /** Returns the current maximum height. */
  32469. int getMaximumHeight() const throw() { return maxH; }
  32470. /** Imposes a minimum width and height limit. */
  32471. void setMinimumSize (const int minimumWidth,
  32472. const int minimumHeight) throw();
  32473. /** Imposes a maximum width and height limit. */
  32474. void setMaximumSize (const int maximumWidth,
  32475. const int maximumHeight) throw();
  32476. /** Set all the maximum and minimum dimensions. */
  32477. void setSizeLimits (const int minimumWidth,
  32478. const int minimumHeight,
  32479. const int maximumWidth,
  32480. const int maximumHeight) throw();
  32481. /** Sets the amount by which the component is allowed to go off-screen.
  32482. The values indicate how many pixels must remain on-screen when dragged off
  32483. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  32484. when the component goes off the top of the screen, its y-position will be
  32485. clipped so that there are always at least 10 pixels on-screen. In other words,
  32486. the lowest y-position it can take would be (10 - the component's height).
  32487. If you pass 0 or less for one of these amounts, the component is allowed
  32488. to move beyond that edge completely, with no restrictions at all.
  32489. If you pass a very large number (i.e. larger that the dimensions of the
  32490. component itself), then the component won't be allowed to overlap that
  32491. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  32492. the component will bump into the left side of the screen and go no further.
  32493. */
  32494. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  32495. const int minimumWhenOffTheLeft,
  32496. const int minimumWhenOffTheBottom,
  32497. const int minimumWhenOffTheRight) throw();
  32498. /** Specifies a width-to-height ratio that the resizer should always maintain.
  32499. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  32500. will always be maintained as this multiple of the height.
  32501. @see setResizeLimits
  32502. */
  32503. void setFixedAspectRatio (const double widthOverHeight) throw();
  32504. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  32505. If no aspect ratio is being enforced, this will return 0.
  32506. */
  32507. double getFixedAspectRatio() const throw();
  32508. /** This callback changes the given co-ordinates to impose whatever the current
  32509. constraints are set to be.
  32510. @param x the x position that should be examined and adjusted
  32511. @param y the y position that should be examined and adjusted
  32512. @param w the width that should be examined and adjusted
  32513. @param h the height that should be examined and adjusted
  32514. @param previousBounds the component's current size
  32515. @param limits the region in which the component can be positioned
  32516. @param isStretchingTop whether the top edge of the component is being resized
  32517. @param isStretchingLeft whether the left edge of the component is being resized
  32518. @param isStretchingBottom whether the bottom edge of the component is being resized
  32519. @param isStretchingRight whether the right edge of the component is being resized
  32520. */
  32521. virtual void checkBounds (int& x, int& y, int& w, int& h,
  32522. const Rectangle& previousBounds,
  32523. const Rectangle& limits,
  32524. const bool isStretchingTop,
  32525. const bool isStretchingLeft,
  32526. const bool isStretchingBottom,
  32527. const bool isStretchingRight);
  32528. /** This callback happens when the resizer is about to start dragging. */
  32529. virtual void resizeStart();
  32530. /** This callback happens when the resizer has finished dragging. */
  32531. virtual void resizeEnd();
  32532. /** Checks the given bounds, and then sets the component to the corrected size. */
  32533. void setBoundsForComponent (Component* const component,
  32534. int x, int y, int w, int h,
  32535. const bool isStretchingTop,
  32536. const bool isStretchingLeft,
  32537. const bool isStretchingBottom,
  32538. const bool isStretchingRight);
  32539. /** Called by setBoundsForComponent() to apply a new constrained size to a
  32540. component.
  32541. By default this just calls setBounds(), but it virtual in case it's needed for
  32542. extremely cunning purposes.
  32543. */
  32544. virtual void applyBoundsToComponent (Component* component,
  32545. int x, int y, int w, int h);
  32546. juce_UseDebuggingNewOperator
  32547. private:
  32548. int minW, maxW, minH, maxH;
  32549. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  32550. double aspectRatio;
  32551. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  32552. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  32553. };
  32554. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32555. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32556. /**
  32557. An object to take care of the logic for dragging components around with the mouse.
  32558. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  32559. then in your mouseDrag() callback, call dragComponent().
  32560. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  32561. to limit the component's position and keep it on-screen.
  32562. e.g. @code
  32563. class MyDraggableComp
  32564. {
  32565. ComponentDragger myDragger;
  32566. void mouseDown (const MouseEvent& e)
  32567. {
  32568. myDragger.startDraggingComponent (this, 0);
  32569. }
  32570. void mouseDrag (const MouseEvent& e)
  32571. {
  32572. myDragger.dragComponent (this, e);
  32573. }
  32574. };
  32575. @endcode
  32576. */
  32577. class JUCE_API ComponentDragger
  32578. {
  32579. public:
  32580. /** Creates a ComponentDragger. */
  32581. ComponentDragger();
  32582. /** Destructor. */
  32583. virtual ~ComponentDragger();
  32584. /** Call this from your component's mouseDown() method, to prepare for dragging.
  32585. @param componentToDrag the component that you want to drag
  32586. @param constrainer a constrainer object to use to keep the component
  32587. from going offscreen
  32588. @see dragComponent
  32589. */
  32590. void startDraggingComponent (Component* const componentToDrag,
  32591. ComponentBoundsConstrainer* constrainer);
  32592. /** Call this from your mouseDrag() callback to move the component.
  32593. This will move the component, but will first check the validity of the
  32594. component's new position using the checkPosition() method, which you
  32595. can override if you need to enforce special positioning limits on the
  32596. component.
  32597. @param componentToDrag the component that you want to drag
  32598. @param e the current mouse-drag event
  32599. @see dragComponent
  32600. */
  32601. void dragComponent (Component* const componentToDrag,
  32602. const MouseEvent& e);
  32603. juce_UseDebuggingNewOperator
  32604. private:
  32605. ComponentBoundsConstrainer* constrainer;
  32606. int originalX, originalY;
  32607. };
  32608. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32609. /********* End of inlined file: juce_ComponentDragger.h *********/
  32610. #endif
  32611. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32612. #endif
  32613. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32614. #endif
  32615. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32616. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32617. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32618. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32619. /**
  32620. Components derived from this class can have files dropped onto them by an external application.
  32621. @see DragAndDropContainer
  32622. */
  32623. class JUCE_API FileDragAndDropTarget
  32624. {
  32625. public:
  32626. /** Destructor. */
  32627. virtual ~FileDragAndDropTarget() {}
  32628. /** Callback to check whether this target is interested in the set of files being offered.
  32629. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32630. component, so don't do anything time-consuming in here, like opening the files to have a look
  32631. inside them!
  32632. @param files the set of (absolute) pathnames of the files that the user is dragging
  32633. @returns true if this component wants to receive the other callbacks regarging this
  32634. type of object; if it returns false, no other callbacks will be made.
  32635. */
  32636. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32637. /** Callback to indicate that some files are being dragged over this component.
  32638. This gets called when the user moves the mouse into this component while dragging.
  32639. Use this callback as a trigger to make your component repaint itself to give the
  32640. user feedback about whether the files can be dropped here or not.
  32641. @param files the set of (absolute) pathnames of the files that the user is dragging
  32642. @param x the mouse x position, relative to this component
  32643. @param y the mouse y position, relative to this component
  32644. */
  32645. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32646. /** Callback to indicate that the user is dragging some files over this component.
  32647. This gets called when the user moves the mouse over this component while dragging.
  32648. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32649. this lets you know what happens in-between.
  32650. @param files the set of (absolute) pathnames of the files that the user is dragging
  32651. @param x the mouse x position, relative to this component
  32652. @param y the mouse y position, relative to this component
  32653. */
  32654. virtual void fileDragMove (const StringArray& files, int x, int y);
  32655. /** Callback to indicate that the mouse has moved away from this component.
  32656. This gets called when the user moves the mouse out of this component while dragging
  32657. the files.
  32658. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32659. as a signal to repaint it in its normal state.
  32660. @param files the set of (absolute) pathnames of the files that the user is dragging
  32661. */
  32662. virtual void fileDragExit (const StringArray& files);
  32663. /** Callback to indicate that the user has dropped the files onto this component.
  32664. When the user drops the files, this get called, and you can use the files in whatever
  32665. way is appropriate.
  32666. Note that after this is called, the fileDragExit method may not be called, so you should
  32667. clean up in here if there's anything you need to do when the drag finishes.
  32668. @param files the set of (absolute) pathnames of the files that the user is dragging
  32669. @param x the mouse x position, relative to this component
  32670. @param y the mouse y position, relative to this component
  32671. */
  32672. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32673. };
  32674. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32675. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32676. #endif
  32677. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32678. /********* Start of inlined file: juce_LassoComponent.h *********/
  32679. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32680. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32681. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  32682. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32683. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32684. /** Manages a list of selectable items.
  32685. Use one of these to keep a track of things that the user has highlighted, like
  32686. icons or things in a list.
  32687. The class is templated so that you can use it to hold either a set of pointers
  32688. to objects, or a set of ID numbers or handles, for cases where each item may
  32689. not always have a corresponding object.
  32690. To be informed when items are selected/deselected, register a ChangeListener with
  32691. this object.
  32692. @see SelectableObject
  32693. */
  32694. template <class SelectableItemType>
  32695. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  32696. {
  32697. public:
  32698. /** Creates an empty set. */
  32699. SelectedItemSet()
  32700. {
  32701. }
  32702. /** Creates a set based on an array of items. */
  32703. SelectedItemSet (const Array <SelectableItemType>& items)
  32704. : selectedItems (items)
  32705. {
  32706. }
  32707. /** Creates a copy of another set. */
  32708. SelectedItemSet (const SelectedItemSet& other)
  32709. : selectedItems (other.selectedItems)
  32710. {
  32711. }
  32712. /** Creates a copy of another set. */
  32713. const SelectedItemSet& operator= (const SelectedItemSet& other)
  32714. {
  32715. if (selectedItems != other.selectedItems)
  32716. {
  32717. selectedItems = other.selectedItems;
  32718. changed();
  32719. }
  32720. return *this;
  32721. }
  32722. /** Destructor. */
  32723. ~SelectedItemSet()
  32724. {
  32725. }
  32726. /** Clears any other currently selected items, and selects this item.
  32727. If this item is already the only thing selected, no change notification
  32728. will be sent out.
  32729. @see addToSelection, addToSelectionBasedOnModifiers
  32730. */
  32731. void selectOnly (SelectableItemType item)
  32732. {
  32733. if (isSelected (item))
  32734. {
  32735. for (int i = selectedItems.size(); --i >= 0;)
  32736. {
  32737. if (selectedItems.getUnchecked(i) != item)
  32738. {
  32739. deselect (selectedItems.getUnchecked(i));
  32740. i = jmin (i, selectedItems.size());
  32741. }
  32742. }
  32743. }
  32744. else
  32745. {
  32746. deselectAll();
  32747. changed();
  32748. selectedItems.add (item);
  32749. itemSelected (item);
  32750. }
  32751. }
  32752. /** Selects an item.
  32753. If the item is already selected, no change notification will be sent out.
  32754. @see selectOnly, addToSelectionBasedOnModifiers
  32755. */
  32756. void addToSelection (SelectableItemType item)
  32757. {
  32758. if (! isSelected (item))
  32759. {
  32760. changed();
  32761. selectedItems.add (item);
  32762. itemSelected (item);
  32763. }
  32764. }
  32765. /** Selects or deselects an item.
  32766. This will use the modifier keys to decide whether to deselect other items
  32767. first.
  32768. So if the shift key is held down, the item will be added without deselecting
  32769. anything (same as calling addToSelection() )
  32770. If no modifiers are down, the current selection will be cleared first (same
  32771. as calling selectOnly() )
  32772. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  32773. so it'll be added to the set unless it's already there, in which case it'll be
  32774. deselected.
  32775. If the items that you're selecting can also be dragged, you may need to use the
  32776. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  32777. subtleties of this kind of usage.
  32778. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  32779. */
  32780. void addToSelectionBasedOnModifiers (SelectableItemType item,
  32781. const ModifierKeys& modifiers)
  32782. {
  32783. if (modifiers.isShiftDown())
  32784. {
  32785. addToSelection (item);
  32786. }
  32787. else if (modifiers.isCommandDown())
  32788. {
  32789. if (isSelected (item))
  32790. deselect (item);
  32791. else
  32792. addToSelection (item);
  32793. }
  32794. else
  32795. {
  32796. selectOnly (item);
  32797. }
  32798. }
  32799. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  32800. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  32801. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  32802. makes it easy to handle multiple-selection of sets of objects that can also
  32803. be dragged.
  32804. For example, if you have several items already selected, and you click on
  32805. one of them (without dragging), then you'd expect this to deselect the other, and
  32806. just select the item you clicked on. But if you had clicked on this item and
  32807. dragged it, you'd have expected them all to stay selected.
  32808. When you call this method, you'll need to store the boolean result, because the
  32809. addToSelectionOnMouseUp() method will need to be know this value.
  32810. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  32811. */
  32812. bool addToSelectionOnMouseDown (SelectableItemType item,
  32813. const ModifierKeys& modifiers)
  32814. {
  32815. if (isSelected (item))
  32816. {
  32817. return ! modifiers.isPopupMenu();
  32818. }
  32819. else
  32820. {
  32821. addToSelectionBasedOnModifiers (item, modifiers);
  32822. return false;
  32823. }
  32824. }
  32825. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  32826. Call this during a mouseUp callback, when you have previously called the
  32827. addToSelectionOnMouseDown() method during your mouseDown event.
  32828. See addToSelectionOnMouseDown() for more info
  32829. @param item the item to select (or deselect)
  32830. @param modifiers the modifiers from the mouse-up event
  32831. @param wasItemDragged true if your item was dragged during the mouse click
  32832. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  32833. back from the addToSelectionOnMouseDown() call that you
  32834. should have made during the matching mouseDown event
  32835. */
  32836. void addToSelectionOnMouseUp (SelectableItemType item,
  32837. const ModifierKeys& modifiers,
  32838. const bool wasItemDragged,
  32839. const bool resultOfMouseDownSelectMethod)
  32840. {
  32841. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  32842. addToSelectionBasedOnModifiers (item, modifiers);
  32843. }
  32844. /** Deselects an item. */
  32845. void deselect (SelectableItemType item)
  32846. {
  32847. const int i = selectedItems.indexOf (item);
  32848. if (i >= 0)
  32849. {
  32850. changed();
  32851. itemDeselected (selectedItems.remove (i));
  32852. }
  32853. }
  32854. /** Deselects all items. */
  32855. void deselectAll()
  32856. {
  32857. if (selectedItems.size() > 0)
  32858. {
  32859. changed();
  32860. for (int i = selectedItems.size(); --i >= 0;)
  32861. {
  32862. itemDeselected (selectedItems.remove (i));
  32863. i = jmin (i, selectedItems.size());
  32864. }
  32865. }
  32866. }
  32867. /** Returns the number of currently selected items.
  32868. @see getSelectedItem
  32869. */
  32870. int getNumSelected() const throw()
  32871. {
  32872. return selectedItems.size();
  32873. }
  32874. /** Returns one of the currently selected items.
  32875. Returns 0 if the index is out-of-range.
  32876. @see getNumSelected
  32877. */
  32878. SelectableItemType getSelectedItem (const int index) const throw()
  32879. {
  32880. return selectedItems [index];
  32881. }
  32882. /** True if this item is currently selected. */
  32883. bool isSelected (const SelectableItemType item) const throw()
  32884. {
  32885. return selectedItems.contains (item);
  32886. }
  32887. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  32888. /** Can be overridden to do special handling when an item is selected.
  32889. For example, if the item is an object, you might want to call it and tell
  32890. it that it's being selected.
  32891. */
  32892. virtual void itemSelected (SelectableItemType item) {}
  32893. /** Can be overridden to do special handling when an item is deselected.
  32894. For example, if the item is an object, you might want to call it and tell
  32895. it that it's being deselected.
  32896. */
  32897. virtual void itemDeselected (SelectableItemType item) {}
  32898. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  32899. */
  32900. void changed (const bool synchronous = false)
  32901. {
  32902. if (synchronous)
  32903. sendSynchronousChangeMessage (this);
  32904. else
  32905. sendChangeMessage (this);
  32906. }
  32907. juce_UseDebuggingNewOperator
  32908. private:
  32909. Array <SelectableItemType> selectedItems;
  32910. };
  32911. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32912. /********* End of inlined file: juce_SelectedItemSet.h *********/
  32913. /**
  32914. A class used by the LassoComponent to manage the things that it selects.
  32915. This allows the LassoComponent to find out which items are within the lasso,
  32916. and to change the list of selected items.
  32917. @see LassoComponent, SelectedItemSet
  32918. */
  32919. template <class SelectableItemType>
  32920. class LassoSource
  32921. {
  32922. public:
  32923. /** Destructor. */
  32924. virtual ~LassoSource() {}
  32925. /** Returns the set of items that lie within a given lassoable region.
  32926. Your implementation of this method must find all the relevent items that lie
  32927. within the given rectangle. and add them to the itemsFound array.
  32928. The co-ordinates are relative to the top-left of the lasso component's parent
  32929. component. (i.e. they are the same as the size and position of the lasso
  32930. component itself).
  32931. */
  32932. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  32933. int x, int y, int width, int height) = 0;
  32934. /** Returns the SelectedItemSet that the lasso should update.
  32935. This set will be continuously updated by the LassoComponent as it gets
  32936. dragged around, so make sure that you've got a ChangeListener attached to
  32937. the set so that your UI objects will know when the selection changes and
  32938. be able to update themselves appropriately.
  32939. */
  32940. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  32941. };
  32942. /**
  32943. A component that acts as a rectangular selection region, which you drag with
  32944. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  32945. To use one of these:
  32946. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  32947. component, and call its beginLasso() method, giving it a
  32948. suitable LassoSource object that it can use to find out which items are in
  32949. the active area.
  32950. - Each time your parent component gets a mouseDrag event, call dragLasso()
  32951. to update the lasso's position - it will use its LassoSource to calculate and
  32952. update the current selection.
  32953. - After the drag has finished and you get a mouseUp callback, you should call
  32954. endLasso() to clean up. This will make the lasso component invisible, and you
  32955. can remove it from the parent component, or delete it.
  32956. The class takes into account the modifier keys that are being held down while
  32957. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  32958. be added to the original selection; if ctrl or command is pressed, they will be
  32959. xor'ed with any previously selected items.
  32960. @see LassoSource, SelectedItemSet
  32961. */
  32962. template <class SelectableItemType>
  32963. class LassoComponent : public Component
  32964. {
  32965. public:
  32966. /** Creates a Lasso component.
  32967. The fill colour is used to fill the lasso'ed rectangle, and the outline
  32968. colour is used to draw a line around its edge.
  32969. */
  32970. LassoComponent (const int outlineThickness_ = 1)
  32971. : source (0),
  32972. outlineThickness (outlineThickness_)
  32973. {
  32974. }
  32975. /** Destructor. */
  32976. ~LassoComponent()
  32977. {
  32978. }
  32979. /** Call this in your mouseDown event, to initialise a drag.
  32980. Pass in a suitable LassoSource object which the lasso will use to find
  32981. the items and change the selection.
  32982. After using this method to initialise the lasso, repeatedly call dragLasso()
  32983. in your component's mouseDrag callback.
  32984. @see dragLasso, endLasso, LassoSource
  32985. */
  32986. void beginLasso (const MouseEvent& e,
  32987. LassoSource <SelectableItemType>* const lassoSource)
  32988. {
  32989. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  32990. jassert (lassoSource != 0); // the source can't be null!
  32991. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  32992. source = lassoSource;
  32993. if (lassoSource != 0)
  32994. originalSelection = lassoSource->getLassoSelection().getItemArray();
  32995. setSize (0, 0);
  32996. }
  32997. /** Call this in your mouseDrag event, to update the lasso's position.
  32998. This must be repeatedly calling when the mouse is dragged, after you've
  32999. first initialised the lasso with beginLasso().
  33000. This method takes into account the modifier keys that are being held down, so
  33001. if shift is pressed, then the lassoed items will be added to any that were
  33002. previously selected; if ctrl or command is pressed, then they will be xor'ed
  33003. with previously selected items.
  33004. @see beginLasso, endLasso
  33005. */
  33006. void dragLasso (const MouseEvent& e)
  33007. {
  33008. if (source != 0)
  33009. {
  33010. const int x1 = e.getMouseDownX();
  33011. const int y1 = e.getMouseDownY();
  33012. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  33013. setVisible (true);
  33014. Array <SelectableItemType> itemsInLasso;
  33015. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33016. if (e.mods.isShiftDown())
  33017. {
  33018. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33019. itemsInLasso.addArray (originalSelection);
  33020. }
  33021. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33022. {
  33023. Array <SelectableItemType> originalMinusNew (originalSelection);
  33024. originalMinusNew.removeValuesIn (itemsInLasso);
  33025. itemsInLasso.removeValuesIn (originalSelection);
  33026. itemsInLasso.addArray (originalMinusNew);
  33027. }
  33028. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33029. }
  33030. }
  33031. /** Call this in your mouseUp event, after the lasso has been dragged.
  33032. @see beginLasso, dragLasso
  33033. */
  33034. void endLasso()
  33035. {
  33036. source = 0;
  33037. originalSelection.clear();
  33038. setVisible (false);
  33039. }
  33040. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33041. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33042. methods.
  33043. Note that you can also use the constants from TextEditor::ColourIds to change the
  33044. colour of the text editor that is opened when a label is editable.
  33045. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33046. */
  33047. enum ColourIds
  33048. {
  33049. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  33050. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  33051. };
  33052. /** @internal */
  33053. void paint (Graphics& g)
  33054. {
  33055. g.fillAll (findColour (lassoFillColourId));
  33056. g.setColour (findColour (lassoOutlineColourId));
  33057. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33058. // this suggests that you've left a lasso comp lying around after the
  33059. // mouse drag has finished.. Be careful to call endLasso() when you get a
  33060. // mouse-up event.
  33061. jassert (isMouseButtonDownAnywhere());
  33062. }
  33063. /** @internal */
  33064. bool hitTest (int x, int y) { return false; }
  33065. juce_UseDebuggingNewOperator
  33066. private:
  33067. Array <SelectableItemType> originalSelection;
  33068. LassoSource <SelectableItemType>* source;
  33069. int outlineThickness;
  33070. };
  33071. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33072. /********* End of inlined file: juce_LassoComponent.h *********/
  33073. #endif
  33074. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  33075. #endif
  33076. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  33077. #endif
  33078. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33079. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  33080. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33081. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33082. /**
  33083. Monitors a component for mouse activity, and triggers a callback
  33084. when the mouse hovers in one place for a specified length of time.
  33085. To use a hover-detector, just create one and call its setHoverComponent()
  33086. method to start it watching a component. You can call setHoverComponent (0)
  33087. to make it inactive.
  33088. (Be careful not to delete a component that's being monitored without first
  33089. stopping or deleting the hover detector).
  33090. */
  33091. class JUCE_API MouseHoverDetector
  33092. {
  33093. public:
  33094. /** Creates a hover detector.
  33095. Initially the object is inactive, and you need to tell it which component
  33096. to monitor, using the setHoverComponent() method.
  33097. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  33098. needs to stay still before the mouseHovered() method
  33099. is invoked. You can change this setting later with
  33100. the setHoverTimeMillisecs() method
  33101. */
  33102. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  33103. /** Destructor. */
  33104. virtual ~MouseHoverDetector();
  33105. /** Changes the time for which the mouse has to stay still before it's considered
  33106. to be hovering.
  33107. */
  33108. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  33109. /** Changes the component that's being monitored for hovering.
  33110. Be careful not to delete a component that's being monitored without first
  33111. stopping or deleting the hover detector.
  33112. */
  33113. void setHoverComponent (Component* const newSourceComponent);
  33114. protected:
  33115. /** Called back when the mouse hovers.
  33116. After the mouse has stayed still over the component for the length of time
  33117. specified by setHoverTimeMillisecs(), this method will be invoked.
  33118. When the mouse is first moved after this callback has occurred, the
  33119. mouseMovedAfterHover() method will be called.
  33120. @param mouseX the mouse's X position relative to the component being monitored
  33121. @param mouseY the mouse's Y position relative to the component being monitored
  33122. */
  33123. virtual void mouseHovered (int mouseX,
  33124. int mouseY) = 0;
  33125. /** Called when the mouse is moved away after just having hovered. */
  33126. virtual void mouseMovedAfterHover() = 0;
  33127. private:
  33128. class JUCE_API HoverDetectorInternal : public MouseListener,
  33129. public Timer
  33130. {
  33131. public:
  33132. MouseHoverDetector* owner;
  33133. int lastX, lastY;
  33134. void timerCallback();
  33135. void mouseEnter (const MouseEvent&);
  33136. void mouseExit (const MouseEvent&);
  33137. void mouseDown (const MouseEvent&);
  33138. void mouseUp (const MouseEvent&);
  33139. void mouseMove (const MouseEvent&);
  33140. void mouseWheelMove (const MouseEvent&, float, float);
  33141. } internalTimer;
  33142. friend class HoverDetectorInternal;
  33143. Component* source;
  33144. int hoverTimeMillisecs;
  33145. bool hasJustHovered;
  33146. void hoverTimerCallback();
  33147. void checkJustHoveredCallback();
  33148. };
  33149. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33150. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33151. #endif
  33152. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33153. #endif
  33154. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33155. #endif
  33156. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33157. #endif
  33158. #ifndef __JUCE_LABEL_JUCEHEADER__
  33159. #endif
  33160. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33161. #endif
  33162. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33163. /********* Start of inlined file: juce_ProgressBar.h *********/
  33164. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33165. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33166. /**
  33167. A progress bar component.
  33168. To use this, just create one and make it visible. It'll run its own timer
  33169. to keep an eye on a variable that you give it, and will automatically
  33170. redraw itself when the variable changes.
  33171. For an easy way of running a background task with a dialog box showing its
  33172. progress, see the ThreadWithProgressWindow class.
  33173. @see ThreadWithProgressWindow
  33174. */
  33175. class JUCE_API ProgressBar : public Component,
  33176. public SettableTooltipClient,
  33177. private Timer
  33178. {
  33179. public:
  33180. /** Creates a ProgressBar.
  33181. @param progress pass in a reference to a double that you're going to
  33182. update with your task's progress. The ProgressBar will
  33183. monitor the value of this variable and will redraw itself
  33184. when the value changes. The range is from 0 to 1.0. Obviously
  33185. you'd better be careful not to delete this variable while the
  33186. ProgressBar still exists!
  33187. */
  33188. ProgressBar (double& progress);
  33189. /** Destructor. */
  33190. ~ProgressBar();
  33191. /** Turns the percentage display on or off.
  33192. By default this is on, and the progress bar will display a text string showing
  33193. its current percentage.
  33194. */
  33195. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33196. /** Gives the progress bar a string to display inside it.
  33197. If you call this, it will turn off the percentage display.
  33198. @see setPercentageDisplay
  33199. */
  33200. void setTextToDisplay (const String& text);
  33201. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33202. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33203. methods.
  33204. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33205. */
  33206. enum ColourIds
  33207. {
  33208. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33209. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33210. classes will probably use variations on this colour. */
  33211. };
  33212. juce_UseDebuggingNewOperator
  33213. protected:
  33214. /** @internal */
  33215. void paint (Graphics& g);
  33216. /** @internal */
  33217. void lookAndFeelChanged();
  33218. /** @internal */
  33219. void visibilityChanged();
  33220. /** @internal */
  33221. void colourChanged();
  33222. private:
  33223. double& progress;
  33224. double currentValue;
  33225. bool displayPercentage;
  33226. String displayedMessage, currentMessage;
  33227. void timerCallback();
  33228. ProgressBar (const ProgressBar&);
  33229. const ProgressBar& operator= (const ProgressBar&);
  33230. };
  33231. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33232. /********* End of inlined file: juce_ProgressBar.h *********/
  33233. #endif
  33234. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33235. /********* Start of inlined file: juce_Slider.h *********/
  33236. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33237. #define __JUCE_SLIDER_JUCEHEADER__
  33238. /********* Start of inlined file: juce_SliderListener.h *********/
  33239. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33240. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33241. class Slider;
  33242. /**
  33243. A class for receiving callbacks from a Slider.
  33244. To be told when a slider's value changes, you can register a SliderListener
  33245. object using Slider::addListener().
  33246. @see Slider::addListener, Slider::removeListener
  33247. */
  33248. class JUCE_API SliderListener
  33249. {
  33250. public:
  33251. /** Destructor. */
  33252. virtual ~SliderListener() {}
  33253. /** Called when the slider's value is changed.
  33254. This may be caused by dragging it, or by typing in its text entry box,
  33255. or by a call to Slider::setValue().
  33256. You can find out the new value using Slider::getValue().
  33257. @see Slider::valueChanged
  33258. */
  33259. virtual void sliderValueChanged (Slider* slider) = 0;
  33260. /** Called when the slider is about to be dragged.
  33261. This is called when a drag begins, then it's followed by multiple calls
  33262. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33263. user lets go.
  33264. @see sliderDragEnded, Slider::startedDragging
  33265. */
  33266. virtual void sliderDragStarted (Slider* slider);
  33267. /** Called after a drag operation has finished.
  33268. @see sliderDragStarted, Slider::stoppedDragging
  33269. */
  33270. virtual void sliderDragEnded (Slider* slider);
  33271. };
  33272. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33273. /********* End of inlined file: juce_SliderListener.h *********/
  33274. /**
  33275. A slider control for changing a value.
  33276. The slider can be horizontal, vertical, or rotary, and can optionally have
  33277. a text-box inside it to show an editable display of the current value.
  33278. To use it, create a Slider object and use the setSliderStyle() method
  33279. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33280. To define the values that it can be set to, see the setRange() and setValue() methods.
  33281. There are also lots of custom tweaks you can do by subclassing and overriding
  33282. some of the virtual methods, such as changing the scaling, changing the format of
  33283. the text display, custom ways of limiting the values, etc.
  33284. You can register SliderListeners with a slider, which will be informed when the value
  33285. changes, or a subclass can override valueChanged() to be informed synchronously.
  33286. @see SliderListener
  33287. */
  33288. class JUCE_API Slider : public Component,
  33289. public SettableTooltipClient,
  33290. private AsyncUpdater,
  33291. private ButtonListener,
  33292. private LabelListener
  33293. {
  33294. public:
  33295. /** Creates a slider.
  33296. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33297. setRange(), etc.
  33298. */
  33299. Slider (const String& componentName);
  33300. /** Destructor. */
  33301. ~Slider();
  33302. /** The types of slider available.
  33303. @see setSliderStyle, setRotaryParameters
  33304. */
  33305. enum SliderStyle
  33306. {
  33307. LinearHorizontal, /**< A traditional horizontal slider. */
  33308. LinearVertical, /**< A traditional vertical slider. */
  33309. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33310. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33311. @see setRotaryParameters */
  33312. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33313. @see setRotaryParameters */
  33314. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33315. @see setRotaryParameters */
  33316. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33317. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33318. @see setMinValue, setMaxValue */
  33319. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33320. @see setMinValue, setMaxValue */
  33321. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33322. value, with the current value being somewhere between them.
  33323. @see setMinValue, setMaxValue */
  33324. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33325. value, with the current value being somewhere between them.
  33326. @see setMinValue, setMaxValue */
  33327. };
  33328. /** Changes the type of slider interface being used.
  33329. @param newStyle the type of interface
  33330. @see setRotaryParameters, setVelocityBasedMode,
  33331. */
  33332. void setSliderStyle (const SliderStyle newStyle);
  33333. /** Returns the slider's current style.
  33334. @see setSliderStyle
  33335. */
  33336. SliderStyle getSliderStyle() const throw() { return style; }
  33337. /** Changes the properties of a rotary slider.
  33338. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33339. the slider's minimum value is represented
  33340. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33341. the slider's maximum value is represented. This must be
  33342. greater than startAngleRadians
  33343. @param stopAtEnd if true, then when the slider is dragged around past the
  33344. minimum or maximum, it'll stop there; if false, it'll wrap
  33345. back to the opposite value
  33346. */
  33347. void setRotaryParameters (const float startAngleRadians,
  33348. const float endAngleRadians,
  33349. const bool stopAtEnd);
  33350. /** Sets the distance the mouse has to move to drag the slider across
  33351. the full extent of its range.
  33352. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33353. relative mouse movements to adjust the slider.
  33354. */
  33355. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33356. /** Changes the way the the mouse is used when dragging the slider.
  33357. If true, this will turn on velocity-sensitive dragging, so that
  33358. the faster the mouse moves, the bigger the movement to the slider. This
  33359. helps when making accurate adjustments if the slider's range is quite large.
  33360. If false, the slider will just try to snap to wherever the mouse is.
  33361. */
  33362. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33363. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33364. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33365. or if you're holding down ctrl.
  33366. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33367. @param threshold the minimum number of pixels that the mouse needs to move for it
  33368. to be treated as a movement
  33369. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33370. the threshold is reached
  33371. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33372. key to toggle velocity-sensitive mode
  33373. */
  33374. void setVelocityModeParameters (const double sensitivity = 1.0,
  33375. const int threshold = 1,
  33376. const double offset = 0.0,
  33377. const bool userCanPressKeyToSwapMode = true) throw();
  33378. /** Sets up a skew factor to alter the way values are distributed.
  33379. You may want to use a range of values on the slider where more accuracy
  33380. is required towards one end of the range, so this will logarithmically
  33381. spread the values across the length of the slider.
  33382. If the factor is < 1.0, the lower end of the range will fill more of the
  33383. slider's length; if the factor is > 1.0, the upper end of the range
  33384. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33385. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33386. method instead.
  33387. @see getSkewFactor, setSkewFactorFromMidPoint
  33388. */
  33389. void setSkewFactor (const double factor) throw();
  33390. /** Sets up a skew factor to alter the way values are distributed.
  33391. This allows you to specify the slider value that should appear in the
  33392. centre of the slider's visible range.
  33393. @see setSkewFactor, getSkewFactor
  33394. */
  33395. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33396. /** Returns the current skew factor.
  33397. See setSkewFactor for more info.
  33398. @see setSkewFactor, setSkewFactorFromMidPoint
  33399. */
  33400. double getSkewFactor() const throw() { return skewFactor; }
  33401. /** Used by setIncDecButtonsMode().
  33402. */
  33403. enum IncDecButtonMode
  33404. {
  33405. incDecButtonsNotDraggable,
  33406. incDecButtonsDraggable_AutoDirection,
  33407. incDecButtonsDraggable_Horizontal,
  33408. incDecButtonsDraggable_Vertical
  33409. };
  33410. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33411. can be dragged on the buttons to drag the values.
  33412. By default this is turned off. When enabled, clicking on the buttons still works
  33413. them as normal, but by holding down the mouse on a button and dragging it a little
  33414. distance, it flips into a mode where the value can be dragged. The drag direction can
  33415. either be set explicitly to be vertical or horizontal, or can be set to
  33416. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33417. are side-by-side or above each other.
  33418. */
  33419. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33420. /** The position of the slider's text-entry box.
  33421. @see setTextBoxStyle
  33422. */
  33423. enum TextEntryBoxPosition
  33424. {
  33425. NoTextBox, /**< Doesn't display a text box. */
  33426. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33427. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33428. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33429. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33430. };
  33431. /** Changes the location and properties of the text-entry box.
  33432. @param newPosition where it should go (or NoTextBox to not have one at all)
  33433. @param isReadOnly if true, it's a read-only display
  33434. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33435. room for the slider as well!
  33436. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33437. room for the slider as well!
  33438. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33439. */
  33440. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33441. const bool isReadOnly,
  33442. const int textEntryBoxWidth,
  33443. const int textEntryBoxHeight);
  33444. /** Returns the status of the text-box.
  33445. @see setTextBoxStyle
  33446. */
  33447. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33448. /** Returns the width used for the text-box.
  33449. @see setTextBoxStyle
  33450. */
  33451. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33452. /** Returns the height used for the text-box.
  33453. @see setTextBoxStyle
  33454. */
  33455. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33456. /** Makes the text-box editable.
  33457. By default this is true, and the user can enter values into the textbox,
  33458. but it can be turned off if that's not suitable.
  33459. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33460. */
  33461. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33462. /** Returns true if the text-box is read-only.
  33463. @see setTextBoxStyle
  33464. */
  33465. bool isTextBoxEditable() const throw() { return editableText; }
  33466. /** If the text-box is editable, this will give it the focus so that the user can
  33467. type directly into it.
  33468. This is basically the effect as the user clicking on it.
  33469. */
  33470. void showTextBox();
  33471. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33472. focus away from it.
  33473. @param discardCurrentEditorContents if true, the slider's value will be left
  33474. unchanged; if false, the current contents of the
  33475. text editor will be used to set the slider position
  33476. before it is hidden.
  33477. */
  33478. void hideTextBox (const bool discardCurrentEditorContents);
  33479. /** Changes the slider's current value.
  33480. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33481. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33482. want to handle it.
  33483. @param newValue the new value to set - this will be restricted by the
  33484. minimum and maximum range, and will be snapped to the
  33485. nearest interval if one has been set
  33486. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33487. any SliderListeners or the valueChanged() method
  33488. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33489. synchronously; if false, it will be asynchronous
  33490. */
  33491. void setValue (double newValue,
  33492. const bool sendUpdateMessage = true,
  33493. const bool sendMessageSynchronously = false);
  33494. /** Returns the slider's current value. */
  33495. double getValue() const throw();
  33496. /** Sets the limits that the slider's value can take.
  33497. @param newMinimum the lowest value allowed
  33498. @param newMaximum the highest value allowed
  33499. @param newInterval the steps in which the value is allowed to increase - if this
  33500. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33501. */
  33502. void setRange (const double newMinimum,
  33503. const double newMaximum,
  33504. const double newInterval = 0);
  33505. /** Returns the current maximum value.
  33506. @see setRange
  33507. */
  33508. double getMaximum() const throw() { return maximum; }
  33509. /** Returns the current minimum value.
  33510. @see setRange
  33511. */
  33512. double getMinimum() const throw() { return minimum; }
  33513. /** Returns the current step-size for values.
  33514. @see setRange
  33515. */
  33516. double getInterval() const throw() { return interval; }
  33517. /** For a slider with two or three thumbs, this returns the lower of its values.
  33518. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33519. A slider with three values also uses the normal getValue() and setValue() methods to
  33520. control the middle value.
  33521. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33522. */
  33523. double getMinValue() const throw();
  33524. /** For a slider with two or three thumbs, this sets the lower of its values.
  33525. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33526. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33527. want to handle it.
  33528. @param newValue the new value to set - this will be restricted by the
  33529. minimum and maximum range, and the max value (in a two-value
  33530. slider) or the mid value (in a three-value slider), and
  33531. will be snapped to the nearest interval if one has been set.
  33532. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33533. any SliderListeners or the valueChanged() method
  33534. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33535. synchronously; if false, it will be asynchronous
  33536. @see getMinValue, setMaxValue, setValue
  33537. */
  33538. void setMinValue (double newValue,
  33539. const bool sendUpdateMessage = true,
  33540. const bool sendMessageSynchronously = false);
  33541. /** For a slider with two or three thumbs, this returns the higher of its values.
  33542. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33543. A slider with three values also uses the normal getValue() and setValue() methods to
  33544. control the middle value.
  33545. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33546. */
  33547. double getMaxValue() const throw();
  33548. /** For a slider with two or three thumbs, this sets the lower of its values.
  33549. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33550. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33551. want to handle it.
  33552. @param newValue the new value to set - this will be restricted by the
  33553. minimum and maximum range, and the max value (in a two-value
  33554. slider) or the mid value (in a three-value slider), and
  33555. will be snapped to the nearest interval if one has been set.
  33556. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33557. any SliderListeners or the valueChanged() method
  33558. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33559. synchronously; if false, it will be asynchronous
  33560. @see getMaxValue, setMinValue, setValue
  33561. */
  33562. void setMaxValue (double newValue,
  33563. const bool sendUpdateMessage = true,
  33564. const bool sendMessageSynchronously = false);
  33565. /** Adds a listener to be called when this slider's value changes. */
  33566. void addListener (SliderListener* const listener) throw();
  33567. /** Removes a previously-registered listener. */
  33568. void removeListener (SliderListener* const listener) throw();
  33569. /** This lets you choose whether double-clicking moves the slider to a given position.
  33570. By default this is turned off, but it's handy if you want a double-click to act
  33571. as a quick way of resetting a slider. Just pass in the value you want it to
  33572. go to when double-clicked.
  33573. @see getDoubleClickReturnValue
  33574. */
  33575. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  33576. const double valueToSetOnDoubleClick) throw();
  33577. /** Returns the values last set by setDoubleClickReturnValue() method.
  33578. Sets isEnabled to true if double-click is enabled, and returns the value
  33579. that was set.
  33580. @see setDoubleClickReturnValue
  33581. */
  33582. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  33583. /** Tells the slider whether to keep sending change messages while the user
  33584. is dragging the slider.
  33585. If set to true, a change message will only be sent when the user has
  33586. dragged the slider and let go. If set to false (the default), then messages
  33587. will be continuously sent as they drag it while the mouse button is still
  33588. held down.
  33589. */
  33590. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  33591. /** This lets you change whether the slider thumb jumps to the mouse position
  33592. when you click.
  33593. By default, this is true. If it's false, then the slider moves with relative
  33594. motion when you drag it.
  33595. This only applies to linear bars, and won't affect two- or three- value
  33596. sliders.
  33597. */
  33598. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  33599. /** If enabled, this gives the slider a pop-up bubble which appears while the
  33600. slider is being dragged.
  33601. This can be handy if your slider doesn't have a text-box, so that users can
  33602. see the value just when they're changing it.
  33603. If you pass a component as the parentComponentToUse parameter, the pop-up
  33604. bubble will be added as a child of that component when it's needed. If you
  33605. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  33606. transparent window, so if you're using an OS that can't do transparent windows
  33607. you'll have to add it to a parent component instead).
  33608. */
  33609. void setPopupDisplayEnabled (const bool isEnabled,
  33610. Component* const parentComponentToUse) throw();
  33611. /** If this is set to true, then right-clicking on the slider will pop-up
  33612. a menu to let the user change the way it works.
  33613. By default this is turned off, but when turned on, the menu will include
  33614. things like velocity sensitivity, and for rotary sliders, whether they
  33615. use a linear or rotary mouse-drag to move them.
  33616. */
  33617. void setPopupMenuEnabled (const bool menuEnabled) throw();
  33618. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  33619. By default it's enabled.
  33620. */
  33621. void setScrollWheelEnabled (const bool enabled) throw();
  33622. /** Returns a number to indicate which thumb is currently being dragged by the
  33623. mouse.
  33624. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  33625. the maximum-value thumb, or -1 if none is currently down.
  33626. */
  33627. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  33628. /** Callback to indicate that the user is about to start dragging the slider.
  33629. @see SliderListener::sliderDragStarted
  33630. */
  33631. virtual void startedDragging();
  33632. /** Callback to indicate that the user has just stopped dragging the slider.
  33633. @see SliderListener::sliderDragEnded
  33634. */
  33635. virtual void stoppedDragging();
  33636. /** Callback to indicate that the user has just moved the slider.
  33637. @see SliderListener::sliderValueChanged
  33638. */
  33639. virtual void valueChanged();
  33640. /** Callback to indicate that the user has just moved the slider.
  33641. Note - the valueChanged() method has changed its format and now no longer has
  33642. any parameters. Update your code to use the new version.
  33643. This version has been left here with an int as its return value to cause
  33644. a syntax error if you've got existing code that uses the old version.
  33645. */
  33646. virtual int valueChanged (double) { jassertfalse; return 0; }
  33647. /** Subclasses can override this to convert a text string to a value.
  33648. When the user enters something into the text-entry box, this method is
  33649. called to convert it to a value.
  33650. The default routine just tries to convert it to a double.
  33651. @see getTextFromValue
  33652. */
  33653. virtual double getValueFromText (const String& text);
  33654. /** Turns the slider's current value into a text string.
  33655. Subclasses can override this to customise the formatting of the text-entry box.
  33656. The default implementation just turns the value into a string, using
  33657. a number of decimal places based on the range interval. If a suffix string
  33658. has been set using setTextValueSuffix(), this will be appended to the text.
  33659. @see getValueFromText
  33660. */
  33661. virtual const String getTextFromValue (double value);
  33662. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  33663. a string.
  33664. This is used by the default implementation of getTextFromValue(), and is just
  33665. appended to the numeric value. For more advanced formatting, you can override
  33666. getTextFromValue() and do something else.
  33667. */
  33668. void setTextValueSuffix (const String& suffix);
  33669. /** Allows a user-defined mapping of distance along the slider to its value.
  33670. The default implementation for this performs the skewing operation that
  33671. can be set up in the setSkewFactor() method. Override it if you need
  33672. some kind of custom mapping instead, but make sure you also implement the
  33673. inverse function in valueToProportionOfLength().
  33674. @param proportion a value 0 to 1.0, indicating a distance along the slider
  33675. @returns the slider value that is represented by this position
  33676. @see valueToProportionOfLength
  33677. */
  33678. virtual double proportionOfLengthToValue (double proportion);
  33679. /** Allows a user-defined mapping of value to the position of the slider along its length.
  33680. The default implementation for this performs the skewing operation that
  33681. can be set up in the setSkewFactor() method. Override it if you need
  33682. some kind of custom mapping instead, but make sure you also implement the
  33683. inverse function in proportionOfLengthToValue().
  33684. @param value a valid slider value, between the range of values specified in
  33685. setRange()
  33686. @returns a value 0 to 1.0 indicating the distance along the slider that
  33687. represents this value
  33688. @see proportionOfLengthToValue
  33689. */
  33690. virtual double valueToProportionOfLength (double value);
  33691. /** Returns the X or Y coordinate of a value along the slider's length.
  33692. If the slider is horizontal, this will be the X coordinate of the given
  33693. value, relative to the left of the slider. If it's vertical, then this will
  33694. be the Y coordinate, relative to the top of the slider.
  33695. If the slider is rotary, this will throw an assertion and return 0. If the
  33696. value is out-of-range, it will be constrained to the length of the slider.
  33697. */
  33698. float getPositionOfValue (const double value);
  33699. /** This can be overridden to allow the slider to snap to user-definable values.
  33700. If overridden, it will be called when the user tries to move the slider to
  33701. a given position, and allows a subclass to sanity-check this value, possibly
  33702. returning a different value to use instead.
  33703. @param attemptedValue the value the user is trying to enter
  33704. @param userIsDragging true if the user is dragging with the mouse; false if
  33705. they are entering the value using the text box
  33706. @returns the value to use instead
  33707. */
  33708. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  33709. /** This can be called to force the text box to update its contents.
  33710. (Not normally needed, as this is done automatically).
  33711. */
  33712. void updateText();
  33713. /** True if the slider moves horizontally. */
  33714. bool isHorizontal() const throw();
  33715. /** True if the slider moves vertically. */
  33716. bool isVertical() const throw();
  33717. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  33718. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33719. methods.
  33720. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33721. */
  33722. enum ColourIds
  33723. {
  33724. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  33725. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  33726. and feel class how this is used. */
  33727. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  33728. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  33729. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  33730. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  33731. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  33732. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  33733. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  33734. };
  33735. juce_UseDebuggingNewOperator
  33736. protected:
  33737. /** @internal */
  33738. void labelTextChanged (Label*);
  33739. /** @internal */
  33740. void paint (Graphics& g);
  33741. /** @internal */
  33742. void resized();
  33743. /** @internal */
  33744. void mouseDown (const MouseEvent& e);
  33745. /** @internal */
  33746. void mouseUp (const MouseEvent& e);
  33747. /** @internal */
  33748. void mouseDrag (const MouseEvent& e);
  33749. /** @internal */
  33750. void mouseDoubleClick (const MouseEvent& e);
  33751. /** @internal */
  33752. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33753. /** @internal */
  33754. void modifierKeysChanged (const ModifierKeys& modifiers);
  33755. /** @internal */
  33756. void buttonClicked (Button* button);
  33757. /** @internal */
  33758. void lookAndFeelChanged();
  33759. /** @internal */
  33760. void enablementChanged();
  33761. /** @internal */
  33762. void focusOfChildComponentChanged (FocusChangeType cause);
  33763. /** @internal */
  33764. void handleAsyncUpdate();
  33765. /** @internal */
  33766. void colourChanged();
  33767. private:
  33768. SortedSet <void*> listeners;
  33769. double currentValue, valueMin, valueMax;
  33770. double minimum, maximum, interval, doubleClickReturnValue;
  33771. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  33772. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  33773. int velocityModeThreshold;
  33774. float rotaryStart, rotaryEnd;
  33775. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  33776. int sliderRegionStart, sliderRegionSize;
  33777. int sliderBeingDragged;
  33778. int pixelsForFullDragExtent;
  33779. Rectangle sliderRect;
  33780. String textSuffix;
  33781. SliderStyle style;
  33782. TextEntryBoxPosition textBoxPos;
  33783. int textBoxWidth, textBoxHeight;
  33784. IncDecButtonMode incDecButtonMode;
  33785. bool editableText : 1, doubleClickToValue : 1;
  33786. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  33787. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  33788. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  33789. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  33790. Font font;
  33791. Label* valueBox;
  33792. Button* incButton;
  33793. Button* decButton;
  33794. Component* popupDisplay;
  33795. Component* parentForPopupDisplay;
  33796. float getLinearSliderPos (const double value);
  33797. void restoreMouseIfHidden();
  33798. void sendDragStart();
  33799. void sendDragEnd();
  33800. double constrainedValue (double value) const throw();
  33801. void triggerChangeMessage (const bool synchronous);
  33802. bool incDecDragDirectionIsHorizontal() const throw();
  33803. Slider (const Slider&);
  33804. const Slider& operator= (const Slider&);
  33805. };
  33806. #endif // __JUCE_SLIDER_JUCEHEADER__
  33807. /********* End of inlined file: juce_Slider.h *********/
  33808. #endif
  33809. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33810. #endif
  33811. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33812. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  33813. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33814. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  33815. class TableHeaderComponent;
  33816. /**
  33817. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  33818. You can register one of these objects for table events using TableHeaderComponent::addListener()
  33819. and TableHeaderComponent::removeListener().
  33820. @see TableHeaderComponent
  33821. */
  33822. class JUCE_API TableHeaderListener
  33823. {
  33824. public:
  33825. TableHeaderListener() {}
  33826. /** Destructor. */
  33827. virtual ~TableHeaderListener() {}
  33828. /** This is called when some of the table's columns are added, removed, hidden,
  33829. or rearranged.
  33830. */
  33831. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  33832. /** This is called when one or more of the table's columns are resized.
  33833. */
  33834. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  33835. /** This is called when the column by which the table should be sorted is changed.
  33836. */
  33837. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  33838. /** This is called when the user begins or ends dragging one of the columns around.
  33839. When the user starts dragging a column, this is called with the ID of that
  33840. column. When they finish dragging, it is called again with 0 as the ID.
  33841. */
  33842. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  33843. int columnIdNowBeingDragged);
  33844. };
  33845. /**
  33846. A component that displays a strip of column headings for a table, and allows these
  33847. to be resized, dragged around, etc.
  33848. This is just the component that goes at the top of a table. You can use it
  33849. directly for custom components, or to create a simple table, use the
  33850. TableListBox class.
  33851. To use one of these, create it and use addColumn() to add all the columns that you need.
  33852. Each column must be given a unique ID number that's used to refer to it.
  33853. @see TableListBox, TableHeaderListener
  33854. */
  33855. class JUCE_API TableHeaderComponent : public Component,
  33856. private AsyncUpdater
  33857. {
  33858. public:
  33859. /** Creates an empty table header.
  33860. */
  33861. TableHeaderComponent();
  33862. /** Destructor. */
  33863. ~TableHeaderComponent();
  33864. /** A combination of these flags are passed into the addColumn() method to specify
  33865. the properties of a column.
  33866. */
  33867. enum ColumnPropertyFlags
  33868. {
  33869. 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. */
  33870. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  33871. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  33872. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  33873. 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. */
  33874. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  33875. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  33876. /** This set of default flags is used as the default parameter value in addColumn(). */
  33877. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  33878. /** A quick way of combining flags for a column that's not resizable. */
  33879. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  33880. /** A quick way of combining flags for a column that's not resizable or sortable. */
  33881. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  33882. /** A quick way of combining flags for a column that's not sortable. */
  33883. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  33884. };
  33885. /** Adds a column to the table.
  33886. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  33887. registered listeners.
  33888. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  33889. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  33890. a unique ID. This is used to identify the column later on, after the user may have
  33891. changed the order that they appear in
  33892. @param width the initial width of the column, in pixels
  33893. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  33894. if the 'resizable' flag is specified for this column
  33895. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  33896. if the 'resizable' flag is specified for this column
  33897. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  33898. properties of this column
  33899. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  33900. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  33901. all columns, not just the index amongst those that are currently visible
  33902. */
  33903. void addColumn (const String& columnName,
  33904. const int columnId,
  33905. const int width,
  33906. const int minimumWidth = 30,
  33907. const int maximumWidth = -1,
  33908. const int propertyFlags = defaultFlags,
  33909. const int insertIndex = -1);
  33910. /** Removes a column with the given ID.
  33911. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  33912. registered listeners.
  33913. */
  33914. void removeColumn (const int columnIdToRemove);
  33915. /** Deletes all columns from the table.
  33916. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  33917. registered listeners.
  33918. */
  33919. void removeAllColumns();
  33920. /** Returns the number of columns in the table.
  33921. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  33922. return the total number of columns, including hidden ones.
  33923. @see isColumnVisible
  33924. */
  33925. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  33926. /** Returns the name for a column.
  33927. @see setColumnName
  33928. */
  33929. const String getColumnName (const int columnId) const throw();
  33930. /** Changes the name of a column. */
  33931. void setColumnName (const int columnId, const String& newName);
  33932. /** Moves a column to a different index in the table.
  33933. @param columnId the column to move
  33934. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  33935. */
  33936. void moveColumn (const int columnId, int newVisibleIndex);
  33937. /** Changes the width of a column.
  33938. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  33939. */
  33940. void setColumnWidth (const int columnId, const int newWidth);
  33941. /** Shows or hides a column.
  33942. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  33943. @see isColumnVisible
  33944. */
  33945. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  33946. /** Returns true if this column is currently visible.
  33947. @see setColumnVisible
  33948. */
  33949. bool isColumnVisible (const int columnId) const;
  33950. /** Changes the column which is the sort column.
  33951. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  33952. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  33953. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  33954. @see getSortColumnId, isSortedForwards, reSortTable
  33955. */
  33956. void setSortColumnId (const int columnId, const bool sortForwards);
  33957. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  33958. @see setSortColumnId, isSortedForwards
  33959. */
  33960. int getSortColumnId() const throw();
  33961. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  33962. @see setSortColumnId
  33963. */
  33964. bool isSortedForwards() const throw();
  33965. /** Triggers a re-sort of the table according to the current sort-column.
  33966. If you modifiy the table's contents, you can call this to signal that the table needs
  33967. to be re-sorted.
  33968. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  33969. tableSortOrderChanged() method of any listeners).
  33970. */
  33971. void reSortTable();
  33972. /** Returns the total width of all the visible columns in the table.
  33973. */
  33974. int getTotalWidth() const throw();
  33975. /** Returns the index of a given column.
  33976. If there's no such column ID, this will return -1.
  33977. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  33978. otherwise it'll return the index amongst all the columns, including any hidden ones.
  33979. */
  33980. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  33981. /** Returns the ID of the column at a given index.
  33982. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  33983. otherwise it'll count it amongst all the columns, including any hidden ones.
  33984. If the index is out-of-range, it'll return 0.
  33985. */
  33986. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  33987. /** Returns the rectangle containing of one of the columns.
  33988. The index is an index from 0 to the number of columns that are currently visible (hidden
  33989. ones are not counted). It returns a rectangle showing the position of the column relative
  33990. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  33991. */
  33992. const Rectangle getColumnPosition (const int index) const throw();
  33993. /** Finds the column ID at a given x-position in the component.
  33994. If there is a column at this point this returns its ID, or if not, it will return 0.
  33995. */
  33996. int getColumnIdAtX (const int xToFind) const throw();
  33997. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  33998. entire width of the component.
  33999. By default this is disabled. Turning it on also means that when resizing a column, those
  34000. on the right will be squashed to fit.
  34001. */
  34002. void setStretchToFitActive (const bool shouldStretchToFit);
  34003. /** Returns true if stretch-to-fit has been enabled.
  34004. @see setStretchToFitActive
  34005. */
  34006. bool isStretchToFitActive() const throw();
  34007. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34008. specified width, keeping their relative proportions the same.
  34009. If the minimum widths of the columns are too wide to fit into this space, it may
  34010. actually end up wider.
  34011. */
  34012. void resizeAllColumnsToFit (int targetTotalWidth);
  34013. /** Enables or disables the pop-up menu.
  34014. The default menu allows the user to show or hide columns. You can add custom
  34015. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34016. By default the menu is enabled.
  34017. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34018. */
  34019. void setPopupMenuActive (const bool hasMenu);
  34020. /** Returns true if the pop-up menu is enabled.
  34021. @see setPopupMenuActive
  34022. */
  34023. bool isPopupMenuActive() const throw();
  34024. /** Returns a string that encapsulates the table's current layout.
  34025. This can be restored later using restoreFromString(). It saves the order of
  34026. the columns, the currently-sorted column, and the widths.
  34027. @see restoreFromString
  34028. */
  34029. const String toString() const;
  34030. /** Restores the state of the table, based on a string previously created with
  34031. toString().
  34032. @see toString
  34033. */
  34034. void restoreFromString (const String& storedVersion);
  34035. /** Adds a listener to be informed about things that happen to the header. */
  34036. void addListener (TableHeaderListener* const newListener) throw();
  34037. /** Removes a previously-registered listener. */
  34038. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34039. /** This can be overridden to handle a mouse-click on one of the column headers.
  34040. The default implementation will use this click to call getSortColumnId() and
  34041. change the sort order.
  34042. */
  34043. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34044. /** This can be overridden to add custom items to the pop-up menu.
  34045. If you override this, you should call the superclass's method to add its
  34046. column show/hide items, if you want them on the menu as well.
  34047. Then to handle the result, override reactToMenuItem().
  34048. @see reactToMenuItem
  34049. */
  34050. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  34051. /** Override this to handle any custom items that you have added to the
  34052. pop-up menu with an addMenuItems() override.
  34053. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34054. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34055. handle the items that it had added.
  34056. @see addMenuItems
  34057. */
  34058. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  34059. /** @internal */
  34060. void paint (Graphics& g);
  34061. /** @internal */
  34062. void resized();
  34063. /** @internal */
  34064. void mouseMove (const MouseEvent&);
  34065. /** @internal */
  34066. void mouseEnter (const MouseEvent&);
  34067. /** @internal */
  34068. void mouseExit (const MouseEvent&);
  34069. /** @internal */
  34070. void mouseDown (const MouseEvent&);
  34071. /** @internal */
  34072. void mouseDrag (const MouseEvent&);
  34073. /** @internal */
  34074. void mouseUp (const MouseEvent&);
  34075. /** @internal */
  34076. const MouseCursor getMouseCursor();
  34077. juce_UseDebuggingNewOperator
  34078. private:
  34079. struct ColumnInfo
  34080. {
  34081. String name;
  34082. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34083. double lastDeliberateWidth;
  34084. bool isVisible() const throw();
  34085. };
  34086. OwnedArray <ColumnInfo> columns;
  34087. Array <TableHeaderListener*> listeners;
  34088. Component* dragOverlayComp;
  34089. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34090. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34091. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34092. ColumnInfo* getInfoForId (const int columnId) const throw();
  34093. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  34094. void sendColumnsChanged();
  34095. void handleAsyncUpdate();
  34096. void beginDrag (const MouseEvent&);
  34097. void endDrag (const int finalIndex);
  34098. int getResizeDraggerAt (const int mouseX) const throw();
  34099. void updateColumnUnderMouse (int x, int y);
  34100. void showColumnChooserMenu (const int);
  34101. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34102. TableHeaderComponent (const TableHeaderComponent&);
  34103. const TableHeaderComponent operator= (const TableHeaderComponent&);
  34104. };
  34105. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34106. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  34107. #endif
  34108. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34109. /********* Start of inlined file: juce_TableListBox.h *********/
  34110. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34111. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34112. /**
  34113. One of these is used by a TableListBox as the data model for the table's contents.
  34114. The virtual methods that you override in this class take care of drawing the
  34115. table cells, and reacting to events.
  34116. @see TableListBox
  34117. */
  34118. class JUCE_API TableListBoxModel
  34119. {
  34120. public:
  34121. TableListBoxModel() {}
  34122. /** Destructor. */
  34123. virtual ~TableListBoxModel() {}
  34124. /** This must return the number of rows currently in the table.
  34125. If the number of rows changes, you must call TableListBox::updateContent() to
  34126. cause it to refresh the list.
  34127. */
  34128. virtual int getNumRows() = 0;
  34129. /** This must draw the background behind one of the rows in the table.
  34130. The graphics context has its origin at the row's top-left, and your method
  34131. should fill the area specified by the width and height parameters.
  34132. */
  34133. virtual void paintRowBackground (Graphics& g,
  34134. int rowNumber,
  34135. int width, int height,
  34136. bool rowIsSelected) = 0;
  34137. /** This must draw one of the cells.
  34138. The graphics context's origin will already be set to the top-left of the cell,
  34139. whose size is specified by (width, height).
  34140. */
  34141. virtual void paintCell (Graphics& g,
  34142. int rowNumber,
  34143. int columnId,
  34144. int width, int height,
  34145. bool rowIsSelected) = 0;
  34146. /** This is used to create or update a custom component to go in a cell.
  34147. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34148. and handle mouse clicks with cellClicked().
  34149. This method will be called whenever a custom component might need to be updated - e.g.
  34150. when the table is changed, or TableListBox::updateContent() is called.
  34151. If you don't need a custom component for the specified cell, then return 0.
  34152. If you do want a custom component, and the existingComponentToUpdate is null, then
  34153. this method must create a new component suitable for the cell, and return it.
  34154. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34155. by this method. In this case, the method must either update it to make sure it's correctly representing
  34156. the given cell (which may be different from the one that the component was created for), or it can
  34157. delete this component and return a new one.
  34158. */
  34159. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34160. Component* existingComponentToUpdate);
  34161. /** This callback is made when the user clicks on one of the cells in the table.
  34162. The mouse event's coordinates will be relative to the entire table row.
  34163. @see cellDoubleClicked, backgroundClicked
  34164. */
  34165. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34166. /** This callback is made when the user clicks on one of the cells in the table.
  34167. The mouse event's coordinates will be relative to the entire table row.
  34168. @see cellClicked, backgroundClicked
  34169. */
  34170. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34171. /** This can be overridden to react to the user double-clicking on a part of the list where
  34172. there are no rows.
  34173. @see cellClicked
  34174. */
  34175. virtual void backgroundClicked();
  34176. /** This callback is made when the table's sort order is changed.
  34177. This could be because the user has clicked a column header, or because the
  34178. TableHeaderComponent::setSortColumnId() method was called.
  34179. If you implement this, your method should re-sort the table using the given
  34180. column as the key.
  34181. */
  34182. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34183. /** Returns the best width for one of the columns.
  34184. If you implement this method, you should measure the width of all the items
  34185. in this column, and return the best size.
  34186. Returning 0 means that the column shouldn't be changed.
  34187. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34188. */
  34189. virtual int getColumnAutoSizeWidth (int columnId);
  34190. /** Override this to be informed when rows are selected or deselected.
  34191. @see ListBox::selectedRowsChanged()
  34192. */
  34193. virtual void selectedRowsChanged (int lastRowSelected);
  34194. /** Override this to be informed when the delete key is pressed.
  34195. @see ListBox::deleteKeyPressed()
  34196. */
  34197. virtual void deleteKeyPressed (int lastRowSelected);
  34198. /** Override this to be informed when the return key is pressed.
  34199. @see ListBox::returnKeyPressed()
  34200. */
  34201. virtual void returnKeyPressed (int lastRowSelected);
  34202. /** Override this to be informed when the list is scrolled.
  34203. This might be caused by the user moving the scrollbar, or by programmatic changes
  34204. to the list position.
  34205. */
  34206. virtual void listWasScrolled();
  34207. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34208. If this returns a non-empty name then when the user drags a row, the table will try to
  34209. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34210. drag-and-drop operation, using this string as the source description, and the listbox
  34211. itself as the source component.
  34212. @see DragAndDropContainer::startDragging
  34213. */
  34214. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34215. };
  34216. /**
  34217. A table of cells, using a TableHeaderComponent as its header.
  34218. This component makes it easy to create a table by providing a TableListBoxModel as
  34219. the data source.
  34220. @see TableListBoxModel, TableHeaderComponent
  34221. */
  34222. class JUCE_API TableListBox : public ListBox,
  34223. private ListBoxModel,
  34224. private TableHeaderListener
  34225. {
  34226. public:
  34227. /** Creates a TableListBox.
  34228. The model pointer passed-in can be null, in which case you can set it later
  34229. with setModel().
  34230. */
  34231. TableListBox (const String& componentName,
  34232. TableListBoxModel* const model);
  34233. /** Destructor. */
  34234. ~TableListBox();
  34235. /** Changes the TableListBoxModel that is being used for this table.
  34236. */
  34237. void setModel (TableListBoxModel* const newModel);
  34238. /** Returns the model currently in use. */
  34239. TableListBoxModel* getModel() const throw() { return model; }
  34240. /** Returns the header component being used in this table. */
  34241. TableHeaderComponent* getHeader() const throw() { return header; }
  34242. /** Changes the height of the table header component.
  34243. @see getHeaderHeight
  34244. */
  34245. void setHeaderHeight (const int newHeight);
  34246. /** Returns the height of the table header.
  34247. @see setHeaderHeight
  34248. */
  34249. int getHeaderHeight() const throw();
  34250. /** Resizes a column to fit its contents.
  34251. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34252. and applies that to the column.
  34253. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34254. */
  34255. void autoSizeColumn (const int columnId);
  34256. /** Calls autoSizeColumn() for all columns in the table. */
  34257. void autoSizeAllColumns();
  34258. /** Enables or disables the auto size options on the popup menu.
  34259. By default, these are enabled.
  34260. */
  34261. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34262. /** True if the auto-size options should be shown on the menu.
  34263. @see setAutoSizeMenuOptionsShown
  34264. */
  34265. bool isAutoSizeMenuOptionShown() const throw();
  34266. /** Returns the position of one of the cells in the table.
  34267. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34268. the table component's top-left. The row number isn't checked to see if it's
  34269. in-range, but the column ID must exist or this will return an empty rectangle.
  34270. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34271. top-left of the table's top-left cell.
  34272. */
  34273. const Rectangle getCellPosition (const int columnId,
  34274. const int rowNumber,
  34275. const bool relativeToComponentTopLeft) const;
  34276. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34277. @see ListBox::scrollToEnsureRowIsOnscreen
  34278. */
  34279. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34280. /** @internal */
  34281. int getNumRows();
  34282. /** @internal */
  34283. void paintListBoxItem (int, Graphics&, int, int, bool);
  34284. /** @internal */
  34285. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34286. /** @internal */
  34287. void selectedRowsChanged (int lastRowSelected);
  34288. /** @internal */
  34289. void deleteKeyPressed (int currentSelectedRow);
  34290. /** @internal */
  34291. void returnKeyPressed (int currentSelectedRow);
  34292. /** @internal */
  34293. void backgroundClicked();
  34294. /** @internal */
  34295. void listWasScrolled();
  34296. /** @internal */
  34297. void tableColumnsChanged (TableHeaderComponent*);
  34298. /** @internal */
  34299. void tableColumnsResized (TableHeaderComponent*);
  34300. /** @internal */
  34301. void tableSortOrderChanged (TableHeaderComponent*);
  34302. /** @internal */
  34303. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34304. /** @internal */
  34305. void resized();
  34306. juce_UseDebuggingNewOperator
  34307. private:
  34308. TableHeaderComponent* header;
  34309. TableListBoxModel* model;
  34310. int columnIdNowBeingDragged;
  34311. bool autoSizeOptionsShown;
  34312. void updateColumnComponents() const;
  34313. TableListBox (const TableListBox&);
  34314. const TableListBox& operator= (const TableListBox&);
  34315. };
  34316. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34317. /********* End of inlined file: juce_TableListBox.h *********/
  34318. #endif
  34319. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34320. #endif
  34321. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34322. #endif
  34323. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34324. #endif
  34325. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34326. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  34327. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34328. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34329. /**
  34330. A factory object which can create ToolbarItemComponent objects.
  34331. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34332. that it can create.
  34333. Each type of item is identified by a unique ID, and multiple instances of an
  34334. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34335. bars).
  34336. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34337. */
  34338. class JUCE_API ToolbarItemFactory
  34339. {
  34340. public:
  34341. ToolbarItemFactory();
  34342. /** Destructor. */
  34343. virtual ~ToolbarItemFactory();
  34344. /** A set of reserved item ID values, used for the built-in item types.
  34345. */
  34346. enum SpecialItemIds
  34347. {
  34348. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34349. can be placed between sets of items to break them into groups. */
  34350. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34351. items.*/
  34352. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34353. either side of it, filling any available space. */
  34354. };
  34355. /** Must return a list of the IDs for all the item types that this factory can create.
  34356. The ids should be added to the array that is passed-in.
  34357. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34358. and the predefined IDs in the SpecialItemIds enum.
  34359. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34360. to this list if you want your toolbar to be able to contain those items.
  34361. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34362. of available items, and their order on the palette will reflect the order in which
  34363. they appear on this list.
  34364. @see ToolbarItemPalette
  34365. */
  34366. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34367. /** Must return the set of items that should be added to a toolbar as its default set.
  34368. This method is used by Toolbar::addDefaultItems() to determine which items to
  34369. create.
  34370. The items that your method adds to the array that is passed-in will be added to the
  34371. toolbar in the same order. Items can appear in the list more than once.
  34372. */
  34373. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34374. /** Must create an instance of one of the items that the factory lists in its
  34375. getAllToolbarItemIds() method.
  34376. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34377. method, except for the built-in item types from the SpecialItemIds enum, which
  34378. are created internally by the toolbar code.
  34379. Try not to keep a pointer to the object that is returned, as it will be deleted
  34380. automatically by the toolbar, and remember that multiple instances of the same
  34381. item type are likely to exist at the same time.
  34382. */
  34383. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  34384. };
  34385. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34386. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  34387. #endif
  34388. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34389. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  34390. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34391. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34392. /**
  34393. A component containing a list of toolbar items, which the user can drag onto
  34394. a toolbar to add them.
  34395. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34396. which automatically shows one of these in a dialog box with lots of extra controls.
  34397. @see Toolbar
  34398. */
  34399. class JUCE_API ToolbarItemPalette : public Component,
  34400. public DragAndDropContainer
  34401. {
  34402. public:
  34403. /** Creates a palette of items for a given factory, with the aim of adding them
  34404. to the specified toolbar.
  34405. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34406. set of items that are shown in this palette.
  34407. The toolbar and factory must not be deleted while this object exists.
  34408. */
  34409. ToolbarItemPalette (ToolbarItemFactory& factory,
  34410. Toolbar* const toolbar);
  34411. /** Destructor. */
  34412. ~ToolbarItemPalette();
  34413. /** @internal */
  34414. void resized();
  34415. juce_UseDebuggingNewOperator
  34416. private:
  34417. ToolbarItemFactory& factory;
  34418. Toolbar* toolbar;
  34419. Viewport* viewport;
  34420. friend class Toolbar;
  34421. void replaceComponent (ToolbarItemComponent* const comp);
  34422. ToolbarItemPalette (const ToolbarItemPalette&);
  34423. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34424. };
  34425. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34426. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  34427. #endif
  34428. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34429. #endif
  34430. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34431. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34432. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34433. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34434. /**
  34435. A PropertyComponent that contains an on/off toggle button.
  34436. This type of property component can be used if you have a boolean value to
  34437. toggle on/off.
  34438. @see PropertyComponent
  34439. */
  34440. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  34441. private ButtonListener
  34442. {
  34443. public:
  34444. /** Creates a button component.
  34445. @param propertyName the property name to be passed to the PropertyComponent
  34446. @param buttonTextWhenTrue the text shown in the button when the value is true
  34447. @param buttonTextWhenFalse the text shown in the button when the value is false
  34448. */
  34449. BooleanPropertyComponent (const String& propertyName,
  34450. const String& buttonTextWhenTrue,
  34451. const String& buttonTextWhenFalse);
  34452. /** Destructor. */
  34453. ~BooleanPropertyComponent();
  34454. /** Called to change the state of the boolean value. */
  34455. virtual void setState (const bool newState) = 0;
  34456. /** Must return the current value of the property. */
  34457. virtual bool getState() const = 0;
  34458. /** @internal */
  34459. void paint (Graphics& g);
  34460. /** @internal */
  34461. void refresh();
  34462. /** @internal */
  34463. void buttonClicked (Button*);
  34464. juce_UseDebuggingNewOperator
  34465. private:
  34466. ToggleButton* button;
  34467. String onText, offText;
  34468. };
  34469. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34470. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  34471. #endif
  34472. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34473. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  34474. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34475. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34476. /**
  34477. A PropertyComponent that contains a button.
  34478. This type of property component can be used if you need a button to trigger some
  34479. kind of action.
  34480. @see PropertyComponent
  34481. */
  34482. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  34483. private ButtonListener
  34484. {
  34485. public:
  34486. /** Creates a button component.
  34487. @param propertyName the property name to be passed to the PropertyComponent
  34488. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  34489. */
  34490. ButtonPropertyComponent (const String& propertyName,
  34491. const bool triggerOnMouseDown);
  34492. /** Destructor. */
  34493. ~ButtonPropertyComponent();
  34494. /** Called when the user clicks the button.
  34495. */
  34496. virtual void buttonClicked() = 0;
  34497. /** Returns the string that should be displayed in the button.
  34498. If you need to change this string, call refresh() to update the component.
  34499. */
  34500. virtual const String getButtonText() const = 0;
  34501. /** @internal */
  34502. void refresh();
  34503. /** @internal */
  34504. void buttonClicked (Button*);
  34505. juce_UseDebuggingNewOperator
  34506. private:
  34507. TextButton* button;
  34508. };
  34509. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34510. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  34511. #endif
  34512. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34513. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  34514. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34515. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34516. /**
  34517. A PropertyComponent that shows its value as a combo box.
  34518. This type of property component contains a list of options and has a
  34519. combo box to choose one.
  34520. Your subclass's constructor must add some strings to the choices StringArray
  34521. and these are shown in the list.
  34522. The getIndex() method will be called to find out which option is the currently
  34523. selected one. If you call refresh() it will call getIndex() to check whether
  34524. the value has changed, and will update the combo box if needed.
  34525. If the user selects a different item from the list, setIndex() will be
  34526. called to let your class process this.
  34527. @see PropertyComponent, PropertyPanel
  34528. */
  34529. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  34530. private ComboBoxListener
  34531. {
  34532. public:
  34533. /** Creates the component.
  34534. Your subclass's constructor must add a list of options to the choices
  34535. member variable.
  34536. */
  34537. ChoicePropertyComponent (const String& propertyName);
  34538. /** Destructor. */
  34539. ~ChoicePropertyComponent();
  34540. /** Called when the user selects an item from the combo box.
  34541. Your subclass must use this callback to update the value that this component
  34542. represents. The index is the index of the chosen item in the choices
  34543. StringArray.
  34544. */
  34545. virtual void setIndex (const int newIndex) = 0;
  34546. /** Returns the index of the item that should currently be shown.
  34547. This is the index of the item in the choices StringArray that will be
  34548. shown.
  34549. */
  34550. virtual int getIndex() const = 0;
  34551. /** Returns the list of options. */
  34552. const StringArray& getChoices() const throw();
  34553. /** @internal */
  34554. void refresh();
  34555. /** @internal */
  34556. void comboBoxChanged (ComboBox*);
  34557. juce_UseDebuggingNewOperator
  34558. protected:
  34559. /** The list of options that will be shown in the combo box.
  34560. Your subclass must populate this array in its constructor. If any empty
  34561. strings are added, these will be replaced with horizontal separators (see
  34562. ComboBox::addSeparator() for more info).
  34563. */
  34564. StringArray choices;
  34565. private:
  34566. ComboBox* comboBox;
  34567. };
  34568. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34569. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  34570. #endif
  34571. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  34572. #endif
  34573. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  34574. #endif
  34575. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34576. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34577. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34578. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34579. /**
  34580. A PropertyComponent that shows its value as a slider.
  34581. @see PropertyComponent, Slider
  34582. */
  34583. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  34584. private SliderListener
  34585. {
  34586. public:
  34587. /** Creates the property component.
  34588. The ranges, interval and skew factor are passed to the Slider component.
  34589. If you need to customise the slider in other ways, your constructor can
  34590. access the slider member variable and change it directly.
  34591. */
  34592. SliderPropertyComponent (const String& propertyName,
  34593. const double rangeMin,
  34594. const double rangeMax,
  34595. const double interval,
  34596. const double skewFactor = 1.0);
  34597. /** Destructor. */
  34598. ~SliderPropertyComponent();
  34599. /** Called when the user moves the slider to change its value.
  34600. Your subclass must use this method to update whatever item this property
  34601. represents.
  34602. */
  34603. virtual void setValue (const double newValue) = 0;
  34604. /** Returns the value that the slider should show. */
  34605. virtual const double getValue() const = 0;
  34606. /** @internal */
  34607. void refresh();
  34608. /** @internal */
  34609. void changeListenerCallback (void*);
  34610. /** @internal */
  34611. void sliderValueChanged (Slider*);
  34612. juce_UseDebuggingNewOperator
  34613. protected:
  34614. /** The slider component being used in this component.
  34615. Your subclass has access to this in case it needs to customise it in some way.
  34616. */
  34617. Slider* slider;
  34618. };
  34619. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34620. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  34621. #endif
  34622. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34623. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  34624. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34625. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34626. /**
  34627. A PropertyComponent that shows its value as editable text.
  34628. @see PropertyComponent
  34629. */
  34630. class JUCE_API TextPropertyComponent : public PropertyComponent
  34631. {
  34632. public:
  34633. /** Creates a text property component.
  34634. The maxNumChars is used to set the length of string allowable, and isMultiLine
  34635. sets whether the text editor allows carriage returns.
  34636. @see TextEditor
  34637. */
  34638. TextPropertyComponent (const String& propertyName,
  34639. const int maxNumChars,
  34640. const bool isMultiLine);
  34641. /** Destructor. */
  34642. ~TextPropertyComponent();
  34643. /** Called when the user edits the text.
  34644. Your subclass must use this callback to change the value of whatever item
  34645. this property component represents.
  34646. */
  34647. virtual void setText (const String& newText) = 0;
  34648. /** Returns the text that should be shown in the text editor.
  34649. */
  34650. virtual const String getText() const = 0;
  34651. /** @internal */
  34652. void refresh();
  34653. /** @internal */
  34654. void textWasEdited();
  34655. juce_UseDebuggingNewOperator
  34656. private:
  34657. Label* textEditor;
  34658. };
  34659. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34660. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  34661. #endif
  34662. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  34663. #endif
  34664. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34665. #endif
  34666. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34667. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  34668. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34669. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34670. /** An object that watches for any movement of a component or any of its parent components.
  34671. This makes it easy to check when a component is moved relative to its top-level
  34672. peer window. The normal Component::moved() method is only called when a component
  34673. moves relative to its immediate parent, and sometimes you want to know if any of
  34674. components higher up the tree have moved (which of course will affect the overall
  34675. position of all their sub-components).
  34676. It also includes a callback that lets you know when the top-level peer is changed.
  34677. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  34678. because they need to keep their custom windows in the right place and respond to
  34679. changes in the peer.
  34680. */
  34681. class JUCE_API ComponentMovementWatcher : public ComponentListener
  34682. {
  34683. public:
  34684. /** Creates a ComponentMovementWatcher to watch a given target component. */
  34685. ComponentMovementWatcher (Component* const component);
  34686. /** Destructor. */
  34687. ~ComponentMovementWatcher();
  34688. /** This callback happens when the component that is being watched is moved
  34689. relative to its top-level peer window, or when it is resized.
  34690. */
  34691. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  34692. /** This callback happens when the component's top-level peer is changed.
  34693. */
  34694. virtual void componentPeerChanged() = 0;
  34695. juce_UseDebuggingNewOperator
  34696. /** @internal */
  34697. void componentParentHierarchyChanged (Component& component);
  34698. /** @internal */
  34699. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34700. private:
  34701. Component* const component;
  34702. ComponentPeer* lastPeer;
  34703. VoidArray registeredParentComps;
  34704. bool reentrant;
  34705. int lastX, lastY, lastWidth, lastHeight;
  34706. #ifdef JUCE_DEBUG
  34707. ComponentDeletionWatcher* deletionWatcher;
  34708. #endif
  34709. void unregister() throw();
  34710. void registerWithParentComps() throw();
  34711. ComponentMovementWatcher (const ComponentMovementWatcher&);
  34712. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  34713. };
  34714. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34715. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  34716. #endif
  34717. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34718. /********* Start of inlined file: juce_GroupComponent.h *********/
  34719. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34720. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34721. /**
  34722. A component that draws an outline around itself and has an optional title at
  34723. the top, for drawing an outline around a group of controls.
  34724. */
  34725. class JUCE_API GroupComponent : public Component
  34726. {
  34727. public:
  34728. /** Creates a GroupComponent.
  34729. @param componentName the name to give the component
  34730. @param labelText the text to show at the top of the outline
  34731. */
  34732. GroupComponent (const String& componentName,
  34733. const String& labelText);
  34734. /** Destructor. */
  34735. ~GroupComponent();
  34736. /** Changes the text that's shown at the top of the component. */
  34737. void setText (const String& newText) throw();
  34738. /** Returns the currently displayed text label. */
  34739. const String getText() const throw();
  34740. /** Sets the positioning of the text label.
  34741. (The default is Justification::left)
  34742. @see getTextLabelPosition
  34743. */
  34744. void setTextLabelPosition (const Justification& justification);
  34745. /** Returns the current text label position.
  34746. @see setTextLabelPosition
  34747. */
  34748. const Justification getTextLabelPosition() const throw() { return justification; }
  34749. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34750. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34751. methods.
  34752. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34753. */
  34754. enum ColourIds
  34755. {
  34756. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  34757. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  34758. };
  34759. /** @internal */
  34760. void paint (Graphics& g);
  34761. /** @internal */
  34762. void enablementChanged();
  34763. /** @internal */
  34764. void colourChanged();
  34765. private:
  34766. String text;
  34767. Justification justification;
  34768. GroupComponent (const GroupComponent&);
  34769. const GroupComponent& operator= (const GroupComponent&);
  34770. };
  34771. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34772. /********* End of inlined file: juce_GroupComponent.h *********/
  34773. #endif
  34774. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34775. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  34776. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34777. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  34778. /********* Start of inlined file: juce_TabbedComponent.h *********/
  34779. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34780. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  34781. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  34782. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34783. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34784. class TabbedButtonBar;
  34785. /** In a TabbedButtonBar, this component is used for each of the buttons.
  34786. If you want to create a TabbedButtonBar with custom tab components, derive
  34787. your component from this class, and override the TabbedButtonBar::createTabButton()
  34788. method to create it instead of the default one.
  34789. @see TabbedButtonBar
  34790. */
  34791. class JUCE_API TabBarButton : public Button
  34792. {
  34793. public:
  34794. /** Creates the tab button. */
  34795. TabBarButton (const String& name,
  34796. TabbedButtonBar* const ownerBar,
  34797. const int tabIndex);
  34798. /** Destructor. */
  34799. ~TabBarButton();
  34800. /** Chooses the best length for the tab, given the specified depth.
  34801. If the tab is horizontal, this should return its width, and the depth
  34802. specifies its height. If it's vertical, it should return the height, and
  34803. the depth is actually its width.
  34804. */
  34805. virtual int getBestTabLength (const int depth);
  34806. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  34807. void clicked (const ModifierKeys& mods);
  34808. bool hitTest (int x, int y);
  34809. juce_UseDebuggingNewOperator
  34810. protected:
  34811. friend class TabbedButtonBar;
  34812. TabbedButtonBar* const owner;
  34813. int tabIndex, overlapPixels;
  34814. DropShadowEffect shadow;
  34815. /** Returns an area of the component that's safe to draw in.
  34816. This deals with the orientation of the tabs, which affects which side is
  34817. touching the tabbed box's content component.
  34818. */
  34819. void getActiveArea (int& x, int& y, int& w, int& h);
  34820. private:
  34821. TabBarButton (const TabBarButton&);
  34822. const TabBarButton& operator= (const TabBarButton&);
  34823. };
  34824. /**
  34825. A vertical or horizontal bar containing tabs that you can select.
  34826. You can use one of these to generate things like a dialog box that has
  34827. tabbed pages you can flip between. Attach a ChangeListener to the
  34828. button bar to be told when the user changes the page.
  34829. An easier method than doing this is to use a TabbedComponent, which
  34830. contains its own TabbedButtonBar and which takes care of the layout
  34831. and other housekeeping.
  34832. @see TabbedComponent
  34833. */
  34834. class JUCE_API TabbedButtonBar : public Component,
  34835. public ChangeBroadcaster,
  34836. public ButtonListener
  34837. {
  34838. public:
  34839. /** The placement of the tab-bar
  34840. @see setOrientation, getOrientation
  34841. */
  34842. enum Orientation
  34843. {
  34844. TabsAtTop,
  34845. TabsAtBottom,
  34846. TabsAtLeft,
  34847. TabsAtRight
  34848. };
  34849. /** Creates a TabbedButtonBar with a given placement.
  34850. You can change the orientation later if you need to.
  34851. */
  34852. TabbedButtonBar (const Orientation orientation);
  34853. /** Destructor. */
  34854. ~TabbedButtonBar();
  34855. /** Changes the bar's orientation.
  34856. This won't change the bar's actual size - you'll need to do that yourself,
  34857. but this determines which direction the tabs go in, and which side they're
  34858. stuck to.
  34859. */
  34860. void setOrientation (const Orientation orientation);
  34861. /** Returns the current orientation.
  34862. @see setOrientation
  34863. */
  34864. Orientation getOrientation() const throw() { return orientation; }
  34865. /** Deletes all the tabs from the bar.
  34866. @see addTab
  34867. */
  34868. void clearTabs();
  34869. /** Adds a tab to the bar.
  34870. Tabs are added in left-to-right reading order.
  34871. If this is the first tab added, it'll also be automatically selected.
  34872. */
  34873. void addTab (const String& tabName,
  34874. const Colour& tabBackgroundColour,
  34875. int insertIndex = -1);
  34876. /** Changes the name of one of the tabs. */
  34877. void setTabName (const int tabIndex,
  34878. const String& newName);
  34879. /** Gets rid of one of the tabs. */
  34880. void removeTab (const int tabIndex);
  34881. /** Moves a tab to a new index in the list.
  34882. Pass -1 as the index to move it to the end of the list.
  34883. */
  34884. void moveTab (const int currentIndex,
  34885. const int newIndex);
  34886. /** Returns the number of tabs in the bar. */
  34887. int getNumTabs() const;
  34888. /** Returns a list of all the tab names in the bar. */
  34889. const StringArray getTabNames() const;
  34890. /** Changes the currently selected tab.
  34891. This will send a change message and cause a synchronous callback to
  34892. the currentTabChanged() method. (But if the given tab is already selected,
  34893. nothing will be done).
  34894. To deselect all the tabs, use an index of -1.
  34895. */
  34896. void setCurrentTabIndex (int newTabIndex);
  34897. /** Returns the name of the currently selected tab.
  34898. This could be an empty string if none are selected.
  34899. */
  34900. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  34901. /** Returns the index of the currently selected tab.
  34902. This could return -1 if none are selected.
  34903. */
  34904. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  34905. /** Callback method to indicate the selected tab has been changed.
  34906. @see setCurrentTabIndex
  34907. */
  34908. virtual void currentTabChanged (const int newCurrentTabIndex,
  34909. const String& newCurrentTabName);
  34910. /** Callback method to indicate that the user has right-clicked on a tab.
  34911. (Or ctrl-clicked on the Mac)
  34912. */
  34913. virtual void popupMenuClickOnTab (const int tabIndex,
  34914. const String& tabName);
  34915. /** Returns the colour of a tab.
  34916. This is the colour that was specified in addTab().
  34917. */
  34918. const Colour getTabBackgroundColour (const int tabIndex);
  34919. /** Changes the background colour of a tab.
  34920. @see addTab, getTabBackgroundColour
  34921. */
  34922. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  34923. /** @internal */
  34924. void resized();
  34925. /** @internal */
  34926. void buttonClicked (Button* button);
  34927. /** @internal */
  34928. void lookAndFeelChanged();
  34929. juce_UseDebuggingNewOperator
  34930. protected:
  34931. /** This creates one of the tabs.
  34932. If you need to use custom tab components, you can override this method and
  34933. return your own class instead of the default.
  34934. */
  34935. virtual TabBarButton* createTabButton (const String& tabName,
  34936. const int tabIndex);
  34937. private:
  34938. Orientation orientation;
  34939. StringArray tabs;
  34940. Array <Colour> tabColours;
  34941. int currentTabIndex;
  34942. Component* behindFrontTab;
  34943. Button* extraTabsButton;
  34944. TabBarButton* getTabButton (const int index) const;
  34945. TabbedButtonBar (const TabbedButtonBar&);
  34946. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  34947. };
  34948. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  34949. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  34950. /**
  34951. A component with a TabbedButtonBar along one of its sides.
  34952. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  34953. with addTab(), and this will take care of showing the pages for you when the
  34954. user clicks on a different tab.
  34955. @see TabbedButtonBar
  34956. */
  34957. class JUCE_API TabbedComponent : public Component
  34958. {
  34959. public:
  34960. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  34961. Once created, add some tabs with the addTab() method.
  34962. */
  34963. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  34964. /** Destructor. */
  34965. ~TabbedComponent();
  34966. /** Changes the placement of the tabs.
  34967. This will rearrange the layout to place the tabs along the appropriate
  34968. side of this component, and will shift the content component accordingly.
  34969. @see TabbedButtonBar::setOrientation
  34970. */
  34971. void setOrientation (const TabbedButtonBar::Orientation orientation);
  34972. /** Returns the current tab placement.
  34973. @see setOrientation, TabbedButtonBar::getOrientation
  34974. */
  34975. TabbedButtonBar::Orientation getOrientation() const throw();
  34976. /** Specifies how many pixels wide or high the tab-bar should be.
  34977. If the tabs are placed along the top or bottom, this specified the height
  34978. of the bar; if they're along the left or right edges, it'll be the width
  34979. of the bar.
  34980. */
  34981. void setTabBarDepth (const int newDepth);
  34982. /** Returns the current thickness of the tab bar.
  34983. @see setTabBarDepth
  34984. */
  34985. int getTabBarDepth() const throw() { return tabDepth; }
  34986. /** Specifies an outline that should be drawn around the entire content component.
  34987. If this thickness is > 0, a line of the specified colour will be drawn around
  34988. the three sides of the content component which don't touch the tab-bar, and
  34989. the content component will be inset by this amount.
  34990. */
  34991. void setOutline (const Colour& newOutlineColour,
  34992. const int newThickness);
  34993. /** Specifies a gap to leave around the edge of the content component.
  34994. Each edge of the content component will be indented by the given number of pixels.
  34995. */
  34996. void setIndent (const int indentThickness);
  34997. /** Removes all the tabs from the bar.
  34998. @see TabbedButtonBar::clearTabs
  34999. */
  35000. void clearTabs();
  35001. /** Adds a tab to the tab-bar.
  35002. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  35003. is true, it will be deleted when the tab is removed or when this object is
  35004. deleted.
  35005. @see TabbedButtonBar::addTab
  35006. */
  35007. void addTab (const String& tabName,
  35008. const Colour& tabBackgroundColour,
  35009. Component* const contentComponent,
  35010. const bool deleteComponentWhenNotNeeded,
  35011. const int insertIndex = -1);
  35012. /** Changes the name of one of the tabs. */
  35013. void setTabName (const int tabIndex,
  35014. const String& newName);
  35015. /** Gets rid of one of the tabs. */
  35016. void removeTab (const int tabIndex);
  35017. /** Returns the number of tabs in the bar. */
  35018. int getNumTabs() const;
  35019. /** Returns a list of all the tab names in the bar. */
  35020. const StringArray getTabNames() const;
  35021. /** Returns the content component that was added for the given index.
  35022. Be sure not to use or delete the components that are returned, as this may interfere
  35023. with the TabbedComponent's use of them.
  35024. */
  35025. Component* getTabContentComponent (const int tabIndex) const throw();
  35026. /** Returns the colour of one of the tabs. */
  35027. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  35028. /** Changes the background colour of one of the tabs. */
  35029. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35030. /** Changes the currently-selected tab.
  35031. To deselect all the tabs, pass -1 as the index.
  35032. @see TabbedButtonBar::setCurrentTabIndex
  35033. */
  35034. void setCurrentTabIndex (const int newTabIndex);
  35035. /** Returns the index of the currently selected tab.
  35036. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  35037. */
  35038. int getCurrentTabIndex() const;
  35039. /** Returns the name of the currently selected tab.
  35040. @see addTab, TabbedButtonBar::getCurrentTabName()
  35041. */
  35042. const String& getCurrentTabName() const;
  35043. /** Returns the current component that's filling the panel.
  35044. This will return 0 if there isn't one.
  35045. */
  35046. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  35047. /** Callback method to indicate the selected tab has been changed.
  35048. @see setCurrentTabIndex
  35049. */
  35050. virtual void currentTabChanged (const int newCurrentTabIndex,
  35051. const String& newCurrentTabName);
  35052. /** Callback method to indicate that the user has right-clicked on a tab.
  35053. (Or ctrl-clicked on the Mac)
  35054. */
  35055. virtual void popupMenuClickOnTab (const int tabIndex,
  35056. const String& tabName);
  35057. /** Returns the tab button bar component that is being used.
  35058. */
  35059. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  35060. /** @internal */
  35061. void paint (Graphics& g);
  35062. /** @internal */
  35063. void resized();
  35064. /** @internal */
  35065. void lookAndFeelChanged();
  35066. juce_UseDebuggingNewOperator
  35067. protected:
  35068. TabbedButtonBar* tabs;
  35069. /** This creates one of the tab buttons.
  35070. If you need to use custom tab components, you can override this method and
  35071. return your own class instead of the default.
  35072. */
  35073. virtual TabBarButton* createTabButton (const String& tabName,
  35074. const int tabIndex);
  35075. private:
  35076. Array <Component*> contentComponents;
  35077. Component* panelComponent;
  35078. int tabDepth;
  35079. Colour outlineColour;
  35080. int outlineThickness, edgeIndent;
  35081. friend class TabCompButtonBar;
  35082. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  35083. TabbedComponent (const TabbedComponent&);
  35084. const TabbedComponent& operator= (const TabbedComponent&);
  35085. };
  35086. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35087. /********* End of inlined file: juce_TabbedComponent.h *********/
  35088. /********* Start of inlined file: juce_DocumentWindow.h *********/
  35089. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35090. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35091. /********* Start of inlined file: juce_ResizableWindow.h *********/
  35092. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35093. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35094. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  35095. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35096. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35097. /********* Start of inlined file: juce_DropShadower.h *********/
  35098. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  35099. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  35100. /**
  35101. Adds a drop-shadow to a component.
  35102. This object creates and manages a set of components which sit around a
  35103. component, creating a gaussian shadow around it. The components will track
  35104. the position of the component and if it's brought to the front they'll also
  35105. follow this.
  35106. For desktop windows you don't need to use this class directly - just
  35107. set the Component::windowHasDropShadow flag when calling
  35108. Component::addToDesktop(), and the system will create one of these if it's
  35109. needed (which it obviously isn't on the Mac, for example).
  35110. */
  35111. class JUCE_API DropShadower : public ComponentListener
  35112. {
  35113. public:
  35114. /** Creates a DropShadower.
  35115. @param alpha the opacity of the shadows, from 0 to 1.0
  35116. @param xOffset the horizontal displacement of the shadow, in pixels
  35117. @param yOffset the vertical displacement of the shadow, in pixels
  35118. @param blurRadius the radius of the blur to use for creating the shadow
  35119. */
  35120. DropShadower (const float alpha = 0.5f,
  35121. const int xOffset = 1,
  35122. const int yOffset = 5,
  35123. const float blurRadius = 10.0f);
  35124. /** Destructor. */
  35125. virtual ~DropShadower();
  35126. /** Attaches the DropShadower to the component you want to shadow. */
  35127. void setOwner (Component* componentToFollow);
  35128. /** @internal */
  35129. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35130. /** @internal */
  35131. void componentBroughtToFront (Component& component);
  35132. /** @internal */
  35133. void componentChildrenChanged (Component& component);
  35134. /** @internal */
  35135. void componentParentHierarchyChanged (Component& component);
  35136. /** @internal */
  35137. void componentVisibilityChanged (Component& component);
  35138. juce_UseDebuggingNewOperator
  35139. private:
  35140. Component* owner;
  35141. int numShadows;
  35142. Component* shadowWindows[4];
  35143. Image* shadowImageSections[12];
  35144. const int shadowEdge, xOffset, yOffset;
  35145. const float alpha, blurRadius;
  35146. bool inDestructor, reentrant;
  35147. void updateShadows();
  35148. void setShadowImage (Image* const src,
  35149. const int num,
  35150. const int w, const int h,
  35151. const int sx, const int sy) throw();
  35152. void bringShadowWindowsToFront();
  35153. void deleteShadowWindows();
  35154. DropShadower (const DropShadower&);
  35155. const DropShadower& operator= (const DropShadower&);
  35156. };
  35157. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35158. /********* End of inlined file: juce_DropShadower.h *********/
  35159. /**
  35160. A base class for top-level windows.
  35161. This class is used for components that are considered a major part of your
  35162. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35163. etc. Things like menus that pop up briefly aren't derived from it.
  35164. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35165. could itself be the child of another component.
  35166. The class manages a list of all instances of top-level windows that are in use,
  35167. and each one is also given the concept of being "active". The active window is
  35168. one that is actively being used by the user. This isn't quite the same as the
  35169. component with the keyboard focus, because there may be a popup menu or other
  35170. temporary window which gets keyboard focus while the active top level window is
  35171. unchanged.
  35172. A top-level window also has an optional drop-shadow.
  35173. @see ResizableWindow, DocumentWindow, DialogWindow
  35174. */
  35175. class JUCE_API TopLevelWindow : public Component
  35176. {
  35177. public:
  35178. /** Creates a TopLevelWindow.
  35179. @param name the name to give the component
  35180. @param addToDesktop if true, the window will be automatically added to the
  35181. desktop; if false, you can use it as a child component
  35182. */
  35183. TopLevelWindow (const String& name,
  35184. const bool addToDesktop);
  35185. /** Destructor. */
  35186. ~TopLevelWindow();
  35187. /** True if this is currently the TopLevelWindow that is actively being used.
  35188. This isn't quite the same as having keyboard focus, because the focus may be
  35189. on a child component or a temporary pop-up menu, etc, while this window is
  35190. still considered to be active.
  35191. @see activeWindowStatusChanged
  35192. */
  35193. bool isActiveWindow() const throw() { return windowIsActive_; }
  35194. /** This will set the bounds of the window so that it's centred in front of another
  35195. window.
  35196. If your app has a few windows open and want to pop up a dialog box for one of
  35197. them, you can use this to show it in front of the relevent parent window, which
  35198. is a bit neater than just having it appear in the middle of the screen.
  35199. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35200. be used instead. If no window is focused, it'll just default to the middle of the
  35201. screen.
  35202. */
  35203. void centreAroundComponent (Component* componentToCentreAround,
  35204. const int width, const int height);
  35205. /** Turns the drop-shadow on and off. */
  35206. void setDropShadowEnabled (const bool useShadow);
  35207. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35208. @see isUsingNativeTitleBar
  35209. */
  35210. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35211. /** Returns true if the window is currently using an OS-native title bar.
  35212. @see setUsingNativeTitleBar
  35213. */
  35214. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35215. /** Returns the number of TopLevelWindow objects currently in use.
  35216. @see getTopLevelWindow
  35217. */
  35218. static int getNumTopLevelWindows() throw();
  35219. /** Returns one of the TopLevelWindow objects currently in use.
  35220. The index is 0 to (getNumTopLevelWindows() - 1).
  35221. */
  35222. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35223. /** Returns the currently-active top level window.
  35224. There might not be one, of course, so this can return 0.
  35225. */
  35226. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35227. juce_UseDebuggingNewOperator
  35228. /** @internal */
  35229. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35230. protected:
  35231. /** This callback happens when this window becomes active or inactive.
  35232. @see isActiveWindow
  35233. */
  35234. virtual void activeWindowStatusChanged();
  35235. /** @internal */
  35236. void focusOfChildComponentChanged (FocusChangeType cause);
  35237. /** @internal */
  35238. void parentHierarchyChanged();
  35239. /** @internal */
  35240. void visibilityChanged();
  35241. /** @internal */
  35242. virtual int getDesktopWindowStyleFlags() const;
  35243. /** @internal */
  35244. void recreateDesktopWindow();
  35245. private:
  35246. friend class TopLevelWindowManager;
  35247. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35248. DropShadower* shadower;
  35249. void setWindowActive (const bool isNowActive) throw();
  35250. TopLevelWindow (const TopLevelWindow&);
  35251. const TopLevelWindow& operator= (const TopLevelWindow&);
  35252. };
  35253. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35254. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35255. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35256. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35257. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35258. /**
  35259. A component that resizes its parent window when dragged.
  35260. This component forms a frame around the edge of a component, allowing it to
  35261. be dragged by the edges or corners to resize it - like the way windows are
  35262. resized in MSWindows or Linux.
  35263. To use it, just add it to your component, making it fill the entire parent component
  35264. (there's a mouse hit-test that only traps mouse-events which land around the
  35265. edge of the component, so it's even ok to put it on top of any other components
  35266. you're using). Make sure you rescale the resizer component to fill the parent
  35267. each time the parent's size changes.
  35268. @see ResizableCornerComponent
  35269. */
  35270. class JUCE_API ResizableBorderComponent : public Component
  35271. {
  35272. public:
  35273. /** Creates a resizer.
  35274. Pass in the target component which you want to be resized when this one is
  35275. dragged.
  35276. The target component will usually be a parent of the resizer component, but this
  35277. isn't mandatory.
  35278. Remember that when the target component is resized, it'll need to move and
  35279. resize this component to keep it in place, as this won't happen automatically.
  35280. If the constrainer parameter is non-zero, then this object will be used to enforce
  35281. limits on the size and position that the component can be stretched to. Make sure
  35282. that the constrainer isn't deleted while still in use by this object.
  35283. @see ComponentBoundsConstrainer
  35284. */
  35285. ResizableBorderComponent (Component* const componentToResize,
  35286. ComponentBoundsConstrainer* const constrainer);
  35287. /** Destructor. */
  35288. ~ResizableBorderComponent();
  35289. /** Specifies how many pixels wide the draggable edges of this component are.
  35290. @see getBorderThickness
  35291. */
  35292. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35293. /** Returns the number of pixels wide that the draggable edges of this component are.
  35294. @see setBorderThickness
  35295. */
  35296. const BorderSize getBorderThickness() const throw();
  35297. juce_UseDebuggingNewOperator
  35298. protected:
  35299. /** @internal */
  35300. void paint (Graphics& g);
  35301. /** @internal */
  35302. void mouseEnter (const MouseEvent& e);
  35303. /** @internal */
  35304. void mouseMove (const MouseEvent& e);
  35305. /** @internal */
  35306. void mouseDown (const MouseEvent& e);
  35307. /** @internal */
  35308. void mouseDrag (const MouseEvent& e);
  35309. /** @internal */
  35310. void mouseUp (const MouseEvent& e);
  35311. /** @internal */
  35312. bool hitTest (int x, int y);
  35313. private:
  35314. Component* const component;
  35315. ComponentBoundsConstrainer* constrainer;
  35316. BorderSize borderSize;
  35317. int originalX, originalY, originalW, originalH;
  35318. int mouseZone;
  35319. void updateMouseZone (const MouseEvent& e) throw();
  35320. ResizableBorderComponent (const ResizableBorderComponent&);
  35321. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35322. };
  35323. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35324. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35325. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35326. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35327. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35328. /** A component that resizes a parent window when dragged.
  35329. This is the small triangular stripey resizer component you get in the bottom-right
  35330. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35331. a larger component and it will automatically resize its parent when it gets dragged
  35332. around.
  35333. @see ResizableFrameComponent
  35334. */
  35335. class JUCE_API ResizableCornerComponent : public Component
  35336. {
  35337. public:
  35338. /** Creates a resizer.
  35339. Pass in the target component which you want to be resized when this one is
  35340. dragged.
  35341. The target component will usually be a parent of the resizer component, but this
  35342. isn't mandatory.
  35343. Remember that when the target component is resized, it'll need to move and
  35344. resize this component to keep it in place, as this won't happen automatically.
  35345. If the constrainer parameter is non-zero, then this object will be used to enforce
  35346. limits on the size and position that the component can be stretched to. Make sure
  35347. that the constrainer isn't deleted while still in use by this object. If you
  35348. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35349. @see ComponentBoundsConstrainer
  35350. */
  35351. ResizableCornerComponent (Component* const componentToResize,
  35352. ComponentBoundsConstrainer* const constrainer);
  35353. /** Destructor. */
  35354. ~ResizableCornerComponent();
  35355. juce_UseDebuggingNewOperator
  35356. protected:
  35357. /** @internal */
  35358. void paint (Graphics& g);
  35359. /** @internal */
  35360. void mouseDown (const MouseEvent& e);
  35361. /** @internal */
  35362. void mouseDrag (const MouseEvent& e);
  35363. /** @internal */
  35364. void mouseUp (const MouseEvent& e);
  35365. /** @internal */
  35366. bool hitTest (int x, int y);
  35367. private:
  35368. Component* const component;
  35369. ComponentBoundsConstrainer* constrainer;
  35370. int originalX, originalY, originalW, originalH;
  35371. ResizableCornerComponent (const ResizableCornerComponent&);
  35372. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35373. };
  35374. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35375. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35376. /**
  35377. A base class for top-level windows that can be dragged around and resized.
  35378. To add content to the window, use its setContentComponent() method to
  35379. give it a component that will remain positioned inside it (leaving a gap around
  35380. the edges for a border).
  35381. It's not advisable to add child components directly to a ResizableWindow: put them
  35382. inside your content component instead. And overriding methods like resized(), moved(), etc
  35383. is also not recommended - instead override these methods for your content component.
  35384. (If for some obscure reason you do need to override these methods, always remember to
  35385. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35386. decorations correctly).
  35387. By default resizing isn't enabled - use the setResizable() method to enable it and
  35388. to choose the style of resizing to use.
  35389. @see TopLevelWindow
  35390. */
  35391. class JUCE_API ResizableWindow : public TopLevelWindow
  35392. {
  35393. public:
  35394. /** Creates a ResizableWindow.
  35395. @param name the name to give the component
  35396. @param backgroundColour the colour to use for filling the window's background.
  35397. @param addToDesktop if true, the window will be automatically added to the
  35398. desktop; if false, you can use it as a child component
  35399. */
  35400. ResizableWindow (const String& name,
  35401. const Colour& backgroundColour,
  35402. const bool addToDesktop);
  35403. /** Destructor.
  35404. If a content component has been set with setContentComponent(), it
  35405. will be deleted.
  35406. */
  35407. ~ResizableWindow();
  35408. /** Returns the colour currently being used for the window's background.
  35409. As a convenience the window will fill itself with this colour, but you
  35410. can override the paint() method if you need more customised behaviour.
  35411. @see setBackgroundColour
  35412. */
  35413. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35414. /** Changes the colour currently being used for the window's background.
  35415. As a convenience the window will fill itself with this colour, but you
  35416. can override the paint() method if you need more customised behaviour.
  35417. Note that the opaque state of this window is altered by this call to reflect
  35418. the opacity of the colour passed-in. On window systems which can't support
  35419. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35420. be using this class as a base for a semi-transparent component anyway).
  35421. @see getBackgroundColour
  35422. */
  35423. void setBackgroundColour (const Colour& newColour);
  35424. /** Make the window resizable or fixed.
  35425. @param shouldBeResizable whether it's resizable at all
  35426. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35427. bottom-right; if false, it'll use a ResizableBorderComponent
  35428. around the edge
  35429. @see setResizeLimits, isResizable
  35430. */
  35431. void setResizable (const bool shouldBeResizable,
  35432. const bool useBottomRightCornerResizer);
  35433. /** True if resizing is enabled.
  35434. @see setResizable
  35435. */
  35436. bool isResizable() const throw();
  35437. /** This sets the maximum and minimum sizes for the window.
  35438. If the window's current size is outside these limits, it will be resized to
  35439. make sure it's within them.
  35440. Calling setBounds() on the component will bypass any size checking - it's only when
  35441. the window is being resized by the user that these values are enforced.
  35442. @see setResizable, setFixedAspectRatio
  35443. */
  35444. void setResizeLimits (const int newMinimumWidth,
  35445. const int newMinimumHeight,
  35446. const int newMaximumWidth,
  35447. const int newMaximumHeight) throw();
  35448. /** Returns the bounds constrainer object that this window is using.
  35449. You can access this to change its properties.
  35450. */
  35451. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35452. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35453. A pointer to the object you pass in will be kept, but it won't be deleted
  35454. by this object, so it's the caller's responsiblity to manage it.
  35455. If you pass 0, then no contraints will be placed on the positioning of the window.
  35456. */
  35457. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35458. /** Calls the window's setBounds method, after first checking these bounds
  35459. with the current constrainer.
  35460. @see setConstrainer
  35461. */
  35462. void setBoundsConstrained (int x, int y, int width, int height);
  35463. /** Returns true if the window is currently in full-screen mode.
  35464. @see setFullScreen
  35465. */
  35466. bool isFullScreen() const;
  35467. /** Puts the window into full-screen mode, or restores it to its normal size.
  35468. If true, the window will become full-screen; if false, it will return to the
  35469. last size it was before being made full-screen.
  35470. @see isFullScreen
  35471. */
  35472. void setFullScreen (const bool shouldBeFullScreen);
  35473. /** Returns true if the window is currently minimised.
  35474. @see setMinimised
  35475. */
  35476. bool isMinimised() const;
  35477. /** Minimises the window, or restores it to its previous position and size.
  35478. When being un-minimised, it'll return to the last position and size it
  35479. was in before being minimised.
  35480. @see isMinimised
  35481. */
  35482. void setMinimised (const bool shouldMinimise);
  35483. /** Returns a string which encodes the window's current size and position.
  35484. This string will encapsulate the window's size, position, and whether it's
  35485. in full-screen mode. It's intended for letting your application save and
  35486. restore a window's position.
  35487. Use the restoreWindowStateFromString() to restore from a saved state.
  35488. @see restoreWindowStateFromString
  35489. */
  35490. const String getWindowStateAsString();
  35491. /** Restores the window to a previously-saved size and position.
  35492. This restores the window's size, positon and full-screen status from an
  35493. string that was previously created with the getWindowStateAsString()
  35494. method.
  35495. @returns false if the string wasn't a valid window state
  35496. @see getWindowStateAsString
  35497. */
  35498. bool restoreWindowStateFromString (const String& previousState);
  35499. /** Returns the current content component.
  35500. This will be the component set by setContentComponent(), or 0 if none
  35501. has yet been specified.
  35502. @see setContentComponent
  35503. */
  35504. Component* getContentComponent() const throw() { return contentComponent; }
  35505. /** Changes the current content component.
  35506. This sets a component that will be placed in the centre of the ResizableWindow,
  35507. (leaving a space around the edge for the border).
  35508. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35509. with addChildComponent(). Instead, add them to the content component.
  35510. @param newContentComponent the new component to use (or null to not use one) - this
  35511. component will be deleted either when replaced by another call
  35512. to this method, or when the ResizableWindow is deleted.
  35513. To remove a content component without deleting it, use
  35514. setContentComponent (0, false).
  35515. @param deleteOldOne if true, the previous content component will be deleted; if
  35516. false, the previous component will just be removed without
  35517. deleting it.
  35518. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35519. it always fits around the size of the content component. If false, the
  35520. new content will be resized to fit the current space available.
  35521. */
  35522. void setContentComponent (Component* const newContentComponent,
  35523. const bool deleteOldOne = true,
  35524. const bool resizeToFit = false);
  35525. /** Changes the window so that the content component ends up with the specified size.
  35526. This is basically a setSize call on the window, but which adds on the borders,
  35527. so you can specify the content component's target size.
  35528. */
  35529. void setContentComponentSize (int width, int height);
  35530. juce_UseDebuggingNewOperator
  35531. protected:
  35532. /** @internal */
  35533. void paint (Graphics& g);
  35534. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35535. void moved();
  35536. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35537. void resized();
  35538. /** @internal */
  35539. void mouseDown (const MouseEvent& e);
  35540. /** @internal */
  35541. void mouseDrag (const MouseEvent& e);
  35542. /** @internal */
  35543. void lookAndFeelChanged();
  35544. /** @internal */
  35545. void childBoundsChanged (Component* child);
  35546. /** @internal */
  35547. void parentSizeChanged();
  35548. /** @internal */
  35549. void visibilityChanged();
  35550. /** @internal */
  35551. void activeWindowStatusChanged();
  35552. /** @internal */
  35553. int getDesktopWindowStyleFlags() const;
  35554. /** Returns the width of the border to use around the window.
  35555. @see getContentComponentBorder
  35556. */
  35557. virtual const BorderSize getBorderThickness();
  35558. /** Returns the insets to use when positioning the content component.
  35559. @see getBorderThickness
  35560. */
  35561. virtual const BorderSize getContentComponentBorder();
  35562. #ifdef JUCE_DEBUG
  35563. /** Overridden to warn people about adding components directly to this component
  35564. instead of using setContentComponent().
  35565. If you know what you're doing and are sure you really want to add a component, specify
  35566. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35567. */
  35568. void addChildComponent (Component* const child, int zOrder = -1);
  35569. /** Overridden to warn people about adding components directly to this component
  35570. instead of using setContentComponent().
  35571. If you know what you're doing and are sure you really want to add a component, specify
  35572. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35573. */
  35574. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35575. #endif
  35576. ResizableCornerComponent* resizableCorner;
  35577. ResizableBorderComponent* resizableBorder;
  35578. private:
  35579. Component* contentComponent;
  35580. bool resizeToFitContent, fullscreen;
  35581. Colour backgroundColour;
  35582. ComponentDragger dragger;
  35583. Rectangle lastNonFullScreenPos;
  35584. ComponentBoundsConstrainer defaultConstrainer;
  35585. ComponentBoundsConstrainer* constrainer;
  35586. #ifdef JUCE_DEBUG
  35587. bool hasBeenResized;
  35588. #endif
  35589. void updateLastPos();
  35590. ResizableWindow (const ResizableWindow&);
  35591. const ResizableWindow& operator= (const ResizableWindow&);
  35592. // (xxx remove these eventually)
  35593. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35594. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35595. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35596. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35597. };
  35598. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35599. /********* End of inlined file: juce_ResizableWindow.h *********/
  35600. /**
  35601. A resizable window with a title bar and maximise, minimise and close buttons.
  35602. This subclass of ResizableWindow creates a fairly standard type of window with
  35603. a title bar and various buttons. The name of the component is shown in the
  35604. title bar, and an icon can optionally be specified with setIcon().
  35605. All the methods available to a ResizableWindow are also available to this,
  35606. so it can easily be made resizable, minimised, maximised, etc.
  35607. It's not advisable to add child components directly to a DocumentWindow: put them
  35608. inside your content component instead. And overriding methods like resized(), moved(), etc
  35609. is also not recommended - instead override these methods for your content component.
  35610. (If for some obscure reason you do need to override these methods, always remember to
  35611. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35612. decorations correctly).
  35613. You can also automatically add a menu bar to the window, using the setMenuBar()
  35614. method.
  35615. @see ResizableWindow, DialogWindow
  35616. */
  35617. class JUCE_API DocumentWindow : public ResizableWindow
  35618. {
  35619. public:
  35620. /** The set of available button-types that can be put on the title bar.
  35621. @see setTitleBarButtonsRequired
  35622. */
  35623. enum TitleBarButtons
  35624. {
  35625. minimiseButton = 1,
  35626. maximiseButton = 2,
  35627. closeButton = 4,
  35628. /** A combination of all the buttons above. */
  35629. allButtons = 7
  35630. };
  35631. /** Creates a DocumentWindow.
  35632. @param name the name to give the component - this is also
  35633. the title shown at the top of the window. To change
  35634. this later, use setName()
  35635. @param backgroundColour the colour to use for filling the window's background.
  35636. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35637. should be shown on the title bar. This value is a bitwise
  35638. combination of values from the TitleBarButtons enum. Note
  35639. that it can be "allButtons" to get them all. You
  35640. can change this later with the setTitleBarButtonsRequired()
  35641. method, which can also specify where they are positioned.
  35642. @param addToDesktop if true, the window will be automatically added to the
  35643. desktop; if false, you can use it as a child component
  35644. @see TitleBarButtons
  35645. */
  35646. DocumentWindow (const String& name,
  35647. const Colour& backgroundColour,
  35648. const int requiredButtons,
  35649. const bool addToDesktop = true);
  35650. /** Destructor.
  35651. If a content component has been set with setContentComponent(), it
  35652. will be deleted.
  35653. */
  35654. ~DocumentWindow();
  35655. /** Changes the component's name.
  35656. (This is overridden from Component::setName() to cause a repaint, as
  35657. the name is what gets drawn across the window's title bar).
  35658. */
  35659. void setName (const String& newName);
  35660. /** Sets an icon to show in the title bar, next to the title.
  35661. A copy is made internally of the image, so the caller can delete the
  35662. image after calling this. If 0 is passed-in, any existing icon will be
  35663. removed.
  35664. */
  35665. void setIcon (const Image* imageToUse);
  35666. /** Changes the height of the title-bar. */
  35667. void setTitleBarHeight (const int newHeight);
  35668. /** Returns the current title bar height. */
  35669. int getTitleBarHeight() const;
  35670. /** Changes the set of title-bar buttons being shown.
  35671. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35672. should be shown on the title bar. This value is a bitwise
  35673. combination of values from the TitleBarButtons enum. Note
  35674. that it can be "allButtons" to get them all.
  35675. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  35676. left side of the bar; if false, they'll be placed at the right
  35677. */
  35678. void setTitleBarButtonsRequired (const int requiredButtons,
  35679. const bool positionTitleBarButtonsOnLeft);
  35680. /** Sets whether the title should be centred within the window.
  35681. If true, the title text is shown in the middle of the title-bar; if false,
  35682. it'll be shown at the left of the bar.
  35683. */
  35684. void setTitleBarTextCentred (const bool textShouldBeCentred);
  35685. /** Creates a menu inside this window.
  35686. @param menuBarModel this specifies a MenuBarModel that should be used to
  35687. generate the contents of a menu bar that will be placed
  35688. just below the title bar, and just above any content
  35689. component. If this value is zero, any existing menu bar
  35690. will be removed from the component; if non-zero, one will
  35691. be added if it's required.
  35692. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  35693. or less to use the look-and-feel's default size.
  35694. */
  35695. void setMenuBar (MenuBarModel* menuBarModel,
  35696. const int menuBarHeight = 0);
  35697. /** This method is called when the user tries to close the window.
  35698. This is triggered by the user clicking the close button, or using some other
  35699. OS-specific key shortcut or OS menu for getting rid of a window.
  35700. If the window is just a pop-up, you should override this closeButtonPressed()
  35701. method and make it delete the window in whatever way is appropriate for your
  35702. app. E.g. you might just want to call "delete this".
  35703. If your app is centred around this window such that the whole app should quit when
  35704. the window is closed, then you will probably want to use this method as an opportunity
  35705. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  35706. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  35707. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  35708. or closing it via the taskbar icon on Windows).
  35709. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  35710. redirects it to call this method, so any methods of closing the window that are
  35711. caught by userTriedToCloseWindow() will also end up here).
  35712. */
  35713. virtual void closeButtonPressed();
  35714. /** Callback that is triggered when the minimise button is pressed.
  35715. The default implementation of this calls ResizableWindow::setMinimised(), but
  35716. you can override it to do more customised behaviour.
  35717. */
  35718. virtual void minimiseButtonPressed();
  35719. /** Callback that is triggered when the maximise button is pressed, or when the
  35720. title-bar is double-clicked.
  35721. The default implementation of this calls ResizableWindow::setFullScreen(), but
  35722. you can override it to do more customised behaviour.
  35723. */
  35724. virtual void maximiseButtonPressed();
  35725. /** Returns the close button, (or 0 if there isn't one). */
  35726. Button* getCloseButton() const throw();
  35727. /** Returns the minimise button, (or 0 if there isn't one). */
  35728. Button* getMinimiseButton() const throw();
  35729. /** Returns the maximise button, (or 0 if there isn't one). */
  35730. Button* getMaximiseButton() const throw();
  35731. /** @internal */
  35732. void paint (Graphics& g);
  35733. /** @internal */
  35734. void resized();
  35735. /** @internal */
  35736. void lookAndFeelChanged();
  35737. /** @internal */
  35738. const BorderSize getBorderThickness();
  35739. /** @internal */
  35740. const BorderSize getContentComponentBorder();
  35741. /** @internal */
  35742. void mouseDoubleClick (const MouseEvent& e);
  35743. /** @internal */
  35744. void userTriedToCloseWindow();
  35745. /** @internal */
  35746. void activeWindowStatusChanged();
  35747. /** @internal */
  35748. int getDesktopWindowStyleFlags() const;
  35749. /** @internal */
  35750. void parentHierarchyChanged();
  35751. juce_UseDebuggingNewOperator
  35752. private:
  35753. int titleBarHeight, menuBarHeight, requiredButtons;
  35754. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  35755. Button* titleBarButtons [3];
  35756. Image* titleBarIcon;
  35757. MenuBarComponent* menuBar;
  35758. MenuBarModel* menuBarModel;
  35759. class ButtonListenerProxy : public ButtonListener
  35760. {
  35761. public:
  35762. ButtonListenerProxy();
  35763. void buttonClicked (Button* button);
  35764. DocumentWindow* owner;
  35765. } buttonListener;
  35766. int getBorderSize() const;
  35767. void repaintTitleBar();
  35768. DocumentWindow (const DocumentWindow&);
  35769. const DocumentWindow& operator= (const DocumentWindow&);
  35770. };
  35771. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35772. /********* End of inlined file: juce_DocumentWindow.h *********/
  35773. class MultiDocumentPanel;
  35774. class MDITabbedComponentInternal;
  35775. /**
  35776. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  35777. component.
  35778. It's like a normal DocumentWindow but has some extra functionality to make sure
  35779. everything works nicely inside a MultiDocumentPanel.
  35780. @see MultiDocumentPanel
  35781. */
  35782. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  35783. {
  35784. public:
  35785. /**
  35786. */
  35787. MultiDocumentPanelWindow (const Colour& backgroundColour);
  35788. /** Destructor. */
  35789. ~MultiDocumentPanelWindow();
  35790. /** @internal */
  35791. void maximiseButtonPressed();
  35792. /** @internal */
  35793. void closeButtonPressed();
  35794. /** @internal */
  35795. void activeWindowStatusChanged();
  35796. /** @internal */
  35797. void broughtToFront();
  35798. juce_UseDebuggingNewOperator
  35799. private:
  35800. void updateOrder();
  35801. MultiDocumentPanel* getOwner() const throw();
  35802. };
  35803. /**
  35804. A component that contains a set of other components either in floating windows
  35805. or tabs.
  35806. This acts as a panel that can be used to hold a set of open document windows, with
  35807. different layout modes.
  35808. Use addDocument() and closeDocument() to add or remove components from the
  35809. panel - never use any of the Component methods to access the panel's child
  35810. components directly, as these are managed internally.
  35811. */
  35812. class JUCE_API MultiDocumentPanel : public Component,
  35813. private ComponentListener
  35814. {
  35815. public:
  35816. /** Creates an empty panel.
  35817. Use addDocument() and closeDocument() to add or remove components from the
  35818. panel - never use any of the Component methods to access the panel's child
  35819. components directly, as these are managed internally.
  35820. */
  35821. MultiDocumentPanel();
  35822. /** Destructor.
  35823. When deleted, this will call closeAllDocuments (false) to make sure all its
  35824. components are deleted. If you need to make sure all documents are saved
  35825. before closing, then you should call closeAllDocuments (true) and check that
  35826. it returns true before deleting the panel.
  35827. */
  35828. ~MultiDocumentPanel();
  35829. /** Tries to close all the documents.
  35830. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35831. be called for each open document, and any of these calls fails, this method
  35832. will stop and return false, leaving some documents still open.
  35833. If checkItsOkToCloseFirst is false, then all documents will be closed
  35834. unconditionally.
  35835. @see closeDocument
  35836. */
  35837. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  35838. /** Adds a document component to the panel.
  35839. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  35840. this will fail and return false. (If it does fail, the component passed-in will not be
  35841. deleted, even if deleteWhenRemoved was set to true).
  35842. The MultiDocumentPanel will deal with creating a window border to go around your component,
  35843. so just pass in the bare content component here, no need to give it a ResizableWindow
  35844. or DocumentWindow.
  35845. @param component the component to add
  35846. @param backgroundColour the background colour to use to fill the component's
  35847. window or tab
  35848. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  35849. or closeAllDocuments(), then it will be deleted. If false, then
  35850. the caller must handle the component's deletion
  35851. */
  35852. bool addDocument (Component* const component,
  35853. const Colour& backgroundColour,
  35854. const bool deleteWhenRemoved);
  35855. /** Closes one of the documents.
  35856. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  35857. be called, and if it fails, this method will return false without closing the
  35858. document.
  35859. If checkItsOkToCloseFirst is false, then the documents will be closed
  35860. unconditionally.
  35861. The component will be deleted if the deleteWhenRemoved parameter was set to
  35862. true when it was added with addDocument.
  35863. @see addDocument, closeAllDocuments
  35864. */
  35865. bool closeDocument (Component* component,
  35866. const bool checkItsOkToCloseFirst);
  35867. /** Returns the number of open document windows.
  35868. @see getDocument
  35869. */
  35870. int getNumDocuments() const throw();
  35871. /** Returns one of the open documents.
  35872. The order of the documents in this array may change when they are added, removed
  35873. or moved around.
  35874. @see getNumDocuments
  35875. */
  35876. Component* getDocument (const int index) const throw();
  35877. /** Returns the document component that is currently focused or on top.
  35878. If currently using floating windows, then this will be the component in the currently
  35879. active window, or the top component if none are active.
  35880. If it's currently in tabbed mode, then it'll return the component in the active tab.
  35881. @see setActiveDocument
  35882. */
  35883. Component* getActiveDocument() const throw();
  35884. /** Makes one of the components active and brings it to the top.
  35885. @see getActiveDocument
  35886. */
  35887. void setActiveDocument (Component* component);
  35888. /** Callback which gets invoked when the currently-active document changes. */
  35889. virtual void activeDocumentChanged();
  35890. /** Sets a limit on how many windows can be open at once.
  35891. If this is zero or less there's no limit (the default). addDocument() will fail
  35892. if this number is exceeded.
  35893. */
  35894. void setMaximumNumDocuments (const int maximumNumDocuments);
  35895. /** Sets an option to make the document fullscreen if there's only one document open.
  35896. If set to true, then if there's only one document, it'll fill the whole of this
  35897. component without tabs or a window border. If false, then tabs or a window
  35898. will always be shown, even if there's only one document. If there's more than
  35899. one document open, then this option makes no difference.
  35900. */
  35901. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  35902. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  35903. */
  35904. bool isFullscreenWhenOneDocument() const throw();
  35905. /** The different layout modes available. */
  35906. enum LayoutMode
  35907. {
  35908. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  35909. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  35910. };
  35911. /** Changes the panel's mode.
  35912. @see LayoutMode, getLayoutMode
  35913. */
  35914. void setLayoutMode (const LayoutMode newLayoutMode);
  35915. /** Returns the current layout mode. */
  35916. LayoutMode getLayoutMode() const throw() { return mode; }
  35917. /** Sets the background colour for the whole panel.
  35918. Each document has its own background colour, but this is the one used to fill the areas
  35919. behind them.
  35920. */
  35921. void setBackgroundColour (const Colour& newBackgroundColour);
  35922. /** Returns the current background colour.
  35923. @see setBackgroundColour
  35924. */
  35925. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  35926. /** A subclass must override this to say whether its currently ok for a document
  35927. to be closed.
  35928. This method is called by closeDocument() and closeAllDocuments() to indicate that
  35929. a document should be saved if possible, ready for it to be closed.
  35930. If this method returns true, then it means the document is ok and can be closed.
  35931. If it returns false, then it means that the closeDocument() method should stop
  35932. and not close.
  35933. Normally, you'd use this method to ask the user if they want to save any changes,
  35934. then return true if the save operation went ok. If the user cancelled the save
  35935. operation you could return false here to abort the close operation.
  35936. If your component is based on the FileBasedDocument class, then you'd probably want
  35937. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  35938. FileBasedDocument::savedOk
  35939. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  35940. */
  35941. virtual bool tryToCloseDocument (Component* component) = 0;
  35942. /** Creates a new window to be used for a document.
  35943. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  35944. but you might want to override it to return a custom component.
  35945. */
  35946. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  35947. /** @internal */
  35948. void paint (Graphics& g);
  35949. /** @internal */
  35950. void resized();
  35951. /** @internal */
  35952. void componentNameChanged (Component&);
  35953. juce_UseDebuggingNewOperator
  35954. private:
  35955. LayoutMode mode;
  35956. Array <Component*> components;
  35957. TabbedComponent* tabComponent;
  35958. Colour backgroundColour;
  35959. int maximumNumDocuments, numDocsBeforeTabsUsed;
  35960. friend class MultiDocumentPanelWindow;
  35961. friend class MDITabbedComponentInternal;
  35962. Component* getContainerComp (Component* c) const;
  35963. void updateOrder();
  35964. void addWindow (Component* component);
  35965. };
  35966. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35967. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  35968. #endif
  35969. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35970. #endif
  35971. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35972. #endif
  35973. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  35974. #endif
  35975. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35976. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  35977. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35978. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  35979. /**
  35980. For laying out a set of components, where the components have preferred sizes
  35981. and size limits, but where they are allowed to stretch to fill the available
  35982. space.
  35983. For example, if you have a component containing several other components, and
  35984. each one should be given a share of the total size, you could use one of these
  35985. to resize the child components when the parent component is resized. Then
  35986. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  35987. A StretchableLayoutManager operates only in one dimension, so if you have a set
  35988. of components stacked vertically on top of each other, you'd use one to manage their
  35989. heights. To build up complex arrangements of components, e.g. for applications
  35990. with multiple nested panels, you would use more than one StretchableLayoutManager.
  35991. E.g. by using two (one vertical, one horizontal), you could create a resizable
  35992. spreadsheet-style table.
  35993. E.g.
  35994. @code
  35995. class MyComp : public Component
  35996. {
  35997. StretchableLayoutManager myLayout;
  35998. MyComp()
  35999. {
  36000. myLayout.setItemLayout (0, // for item 0
  36001. 50, 100, // must be between 50 and 100 pixels in size
  36002. -0.6); // and its preferred size is 60% of the total available space
  36003. myLayout.setItemLayout (1, // for item 1
  36004. -0.2, -0.6, // size must be between 20% and 60% of the available space
  36005. 50); // and its preferred size is 50 pixels
  36006. }
  36007. void resized()
  36008. {
  36009. // make a list of two of our child components that we want to reposition
  36010. Component* comps[] = { myComp1, myComp2 };
  36011. // this will position the 2 components, one above the other, to fit
  36012. // vertically into the rectangle provided.
  36013. myLayout.layOutComponents (comps, 2,
  36014. 0, 0, getWidth(), getHeight(),
  36015. true);
  36016. }
  36017. };
  36018. @endcode
  36019. @see StretchableLayoutResizerBar
  36020. */
  36021. class JUCE_API StretchableLayoutManager
  36022. {
  36023. public:
  36024. /** Creates an empty layout.
  36025. You'll need to add some item properties to the layout before it can be used
  36026. to resize things - see setItemLayout().
  36027. */
  36028. StretchableLayoutManager();
  36029. /** Destructor. */
  36030. ~StretchableLayoutManager();
  36031. /** For a numbered item, this sets its size limits and preferred size.
  36032. @param itemIndex the index of the item to change.
  36033. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36034. indicates an absolute size in pixels. A negative number indicates a
  36035. proportion of the available space (e.g -0.5 is 50%)
  36036. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36037. indicates an absolute size in pixels. A negative number indicates a
  36038. proportion of the available space
  36039. @param preferredSize the size that this item would like to be, if there's enough room. A
  36040. positive number indicates an absolute size in pixels. A negative number
  36041. indicates a proportion of the available space
  36042. @see getItemLayout
  36043. */
  36044. void setItemLayout (const int itemIndex,
  36045. const double minimumSize,
  36046. const double maximumSize,
  36047. const double preferredSize);
  36048. /** For a numbered item, this returns its size limits and preferred size.
  36049. @param itemIndex the index of the item.
  36050. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36051. indicates an absolute size in pixels. A negative number indicates a
  36052. proportion of the available space (e.g -0.5 is 50%)
  36053. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36054. indicates an absolute size in pixels. A negative number indicates a
  36055. proportion of the available space
  36056. @param preferredSize the size that this item would like to be, if there's enough room. A
  36057. positive number indicates an absolute size in pixels. A negative number
  36058. indicates a proportion of the available space
  36059. @returns false if the item's properties hadn't been set
  36060. @see setItemLayout
  36061. */
  36062. bool getItemLayout (const int itemIndex,
  36063. double& minimumSize,
  36064. double& maximumSize,
  36065. double& preferredSize) const;
  36066. /** Clears all the properties that have been set with setItemLayout() and resets
  36067. this object to its initial state.
  36068. */
  36069. void clearAllItems();
  36070. /** Takes a set of components that correspond to the layout's items, and positions
  36071. them to fill a space.
  36072. This will try to give each item its preferred size, whether that's a relative size
  36073. or an absolute one.
  36074. @param components an array of components that correspond to each of the
  36075. numbered items that the StretchableLayoutManager object
  36076. has been told about with setItemLayout()
  36077. @param numComponents the number of components in the array that is passed-in. This
  36078. should be the same as the number of items this object has been
  36079. told about.
  36080. @param x the left of the rectangle in which the components should
  36081. be laid out
  36082. @param y the top of the rectangle in which the components should
  36083. be laid out
  36084. @param width the width of the rectangle in which the components should
  36085. be laid out
  36086. @param height the height of the rectangle in which the components should
  36087. be laid out
  36088. @param vertically if true, the components will be positioned in a vertical stack,
  36089. so that they fill the height of the rectangle. If false, they
  36090. will be placed side-by-side in a horizontal line, filling the
  36091. available width
  36092. @param resizeOtherDimension if true, this means that the components will have their
  36093. other dimension resized to fit the space - i.e. if the 'vertically'
  36094. parameter is true, their x-positions and widths are adjusted to fit
  36095. the x and width parameters; if 'vertically' is false, their y-positions
  36096. and heights are adjusted to fit the y and height parameters.
  36097. */
  36098. void layOutComponents (Component** const components,
  36099. int numComponents,
  36100. int x, int y, int width, int height,
  36101. const bool vertically,
  36102. const bool resizeOtherDimension);
  36103. /** Returns the current position of one of the items.
  36104. This is only a valid call after layOutComponents() has been called, as it
  36105. returns the last position that this item was placed at. If the layout was
  36106. vertical, the value returned will be the y position of the top of the item,
  36107. relative to the top of the rectangle in which the items were placed (so for
  36108. example, item 0 will always have position of 0, even in the rectangle passed
  36109. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  36110. the position returned is the item's left-hand position, again relative to the
  36111. x position of the rectangle used.
  36112. @see getItemCurrentSize, setItemPosition
  36113. */
  36114. int getItemCurrentPosition (const int itemIndex) const;
  36115. /** Returns the current size of one of the items.
  36116. This is only meaningful after layOutComponents() has been called, as it
  36117. returns the last size that this item was given. If the layout was done
  36118. vertically, it'll return the item's height in pixels; if it was horizontal,
  36119. it'll return its width.
  36120. @see getItemCurrentRelativeSize
  36121. */
  36122. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36123. /** Returns the current size of one of the items.
  36124. This is only meaningful after layOutComponents() has been called, as it
  36125. returns the last size that this item was given. If the layout was done
  36126. vertically, it'll return a negative value representing the item's height relative
  36127. to the last size used for laying the components out; if the layout was done
  36128. horizontally it'll be the proportion of its width.
  36129. @see getItemCurrentAbsoluteSize
  36130. */
  36131. double getItemCurrentRelativeSize (const int itemIndex) const;
  36132. /** Moves one of the items, shifting along any other items as necessary in
  36133. order to get it to the desired position.
  36134. Calling this method will also update the preferred sizes of the items it
  36135. shuffles along, so that they reflect their new positions.
  36136. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36137. about when it's dragged).
  36138. @param itemIndex the item to move
  36139. @param newPosition the absolute position that you'd like this item to move
  36140. to. The item might not be able to always reach exactly this position,
  36141. because other items may have minimum sizes that constrain how
  36142. far it can go
  36143. */
  36144. void setItemPosition (const int itemIndex,
  36145. int newPosition);
  36146. juce_UseDebuggingNewOperator
  36147. private:
  36148. struct ItemLayoutProperties
  36149. {
  36150. int itemIndex;
  36151. int currentSize;
  36152. double minSize, maxSize, preferredSize;
  36153. };
  36154. OwnedArray <ItemLayoutProperties> items;
  36155. int totalSize;
  36156. static int sizeToRealSize (double size, int totalSpace);
  36157. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36158. void setTotalSize (const int newTotalSize);
  36159. int fitComponentsIntoSpace (const int startIndex,
  36160. const int endIndex,
  36161. const int availableSpace,
  36162. int startPos);
  36163. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36164. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36165. void updatePrefSizesToMatchCurrentPositions();
  36166. StretchableLayoutManager (const StretchableLayoutManager&);
  36167. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36168. };
  36169. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36170. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36171. #endif
  36172. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36173. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36174. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36175. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36176. /**
  36177. A component that acts as one of the vertical or horizontal bars you see being
  36178. used to resize panels in a window.
  36179. One of these acts with a StretchableLayoutManager to resize the other components.
  36180. @see StretchableLayoutManager
  36181. */
  36182. class JUCE_API StretchableLayoutResizerBar : public Component
  36183. {
  36184. public:
  36185. /** Creates a resizer bar for use on a specified layout.
  36186. @param layoutToUse the layout that will be affected when this bar
  36187. is dragged
  36188. @param itemIndexInLayout the item index in the layout that corresponds to
  36189. this bar component. You'll need to set up the item
  36190. properties in a suitable way for a divider bar, e.g.
  36191. for an 8-pixel wide bar which, you could call
  36192. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36193. @param isBarVertical true if it's an upright bar that you drag left and
  36194. right; false for a horizontal one that you drag up and
  36195. down
  36196. */
  36197. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36198. const int itemIndexInLayout,
  36199. const bool isBarVertical);
  36200. /** Destructor. */
  36201. ~StretchableLayoutResizerBar();
  36202. /** This is called when the bar is dragged.
  36203. This method must update the positions of any components whose position is
  36204. determined by the StretchableLayoutManager, because they might have just
  36205. moved.
  36206. The default implementation calls the resized() method of this component's
  36207. parent component, because that's often where you're likely to apply the
  36208. layout, but it can be overridden for more specific needs.
  36209. */
  36210. virtual void hasBeenMoved();
  36211. /** @internal */
  36212. void paint (Graphics& g);
  36213. /** @internal */
  36214. void mouseDown (const MouseEvent& e);
  36215. /** @internal */
  36216. void mouseDrag (const MouseEvent& e);
  36217. juce_UseDebuggingNewOperator
  36218. private:
  36219. StretchableLayoutManager* layout;
  36220. int itemIndex, mouseDownPos;
  36221. bool isVertical;
  36222. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36223. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36224. };
  36225. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36226. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36227. #endif
  36228. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36229. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36230. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36231. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36232. /**
  36233. A utility class for fitting a set of objects whose sizes can vary between
  36234. a minimum and maximum size, into a space.
  36235. This is a trickier algorithm than it would first seem, so I've put it in this
  36236. class to allow it to be shared by various bits of code.
  36237. To use it, create one of these objects, call addItem() to add the list of items
  36238. you need, then call resizeToFit(), which will change all their sizes. You can
  36239. then retrieve the new sizes with getItemSize() and getNumItems().
  36240. It's currently used by the TableHeaderComponent for stretching out the table
  36241. headings to fill the table's width.
  36242. */
  36243. class StretchableObjectResizer
  36244. {
  36245. public:
  36246. /** Creates an empty object resizer. */
  36247. StretchableObjectResizer();
  36248. /** Destructor. */
  36249. ~StretchableObjectResizer();
  36250. /** Adds an item to the list.
  36251. The order parameter lets you specify groups of items that are resized first when some
  36252. space needs to be found. Those items with an order of 0 will be the first ones to be
  36253. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36254. will then try resizing the items with an order of 1, then 2, and so on.
  36255. */
  36256. void addItem (const double currentSize,
  36257. const double minSize,
  36258. const double maxSize,
  36259. const int order = 0);
  36260. /** Resizes all the items to fit this amount of space.
  36261. This will attempt to fit them in without exceeding each item's miniumum and
  36262. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36263. further, the final size may be greater or less than the size passed in.
  36264. After calling this method, you can retrieve the new sizes with the getItemSize()
  36265. method.
  36266. */
  36267. void resizeToFit (const double targetSize);
  36268. /** Returns the number of items that have been added. */
  36269. int getNumItems() const throw() { return items.size(); }
  36270. /** Returns the size of one of the items. */
  36271. double getItemSize (const int index) const throw();
  36272. juce_UseDebuggingNewOperator
  36273. private:
  36274. struct Item
  36275. {
  36276. double size;
  36277. double minSize;
  36278. double maxSize;
  36279. int order;
  36280. };
  36281. OwnedArray <Item> items;
  36282. StretchableObjectResizer (const StretchableObjectResizer&);
  36283. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36284. };
  36285. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36286. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36287. #endif
  36288. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36289. #endif
  36290. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36291. #endif
  36292. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36293. #endif
  36294. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36295. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36296. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36297. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36298. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  36299. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36300. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36301. /********* Start of inlined file: juce_FileFilter.h *********/
  36302. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36303. #define __JUCE_FILEFILTER_JUCEHEADER__
  36304. /**
  36305. Interface for deciding which files are suitable for something.
  36306. For example, this is used by DirectoryContentsList to select which files
  36307. go into the list.
  36308. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36309. */
  36310. class JUCE_API FileFilter
  36311. {
  36312. public:
  36313. /** Creates a filter with the given description.
  36314. The description can be returned later with the getDescription() method.
  36315. */
  36316. FileFilter (const String& filterDescription);
  36317. /** Destructor. */
  36318. virtual ~FileFilter();
  36319. /** Returns the description that the filter was created with. */
  36320. const String& getDescription() const throw();
  36321. /** Should return true if this file is suitable for inclusion in whatever context
  36322. the object is being used.
  36323. */
  36324. virtual bool isFileSuitable (const File& file) const = 0;
  36325. /** Should return true if this directory is suitable for inclusion in whatever context
  36326. the object is being used.
  36327. */
  36328. virtual bool isDirectorySuitable (const File& file) const = 0;
  36329. protected:
  36330. String description;
  36331. };
  36332. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36333. /********* End of inlined file: juce_FileFilter.h *********/
  36334. /**
  36335. A class to asynchronously scan for details about the files in a directory.
  36336. This keeps a list of files and some information about them, using a background
  36337. thread to scan for more files. As files are found, it broadcasts change messages
  36338. to tell any listeners.
  36339. @see FileListComponent, FileBrowserComponent
  36340. */
  36341. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36342. public TimeSliceClient
  36343. {
  36344. public:
  36345. /** Creates a directory list.
  36346. To set the directory it should point to, use setDirectory(), which will
  36347. also start it scanning for files on the background thread.
  36348. When the background thread finds and adds new files to this list, the
  36349. ChangeBroadcaster class will send a change message, so you can register
  36350. listeners and update them when the list changes.
  36351. @param fileFilter an optional filter to select which files are
  36352. included in the list. If this is 0, then all files
  36353. and directories are included. Make sure that the
  36354. filter doesn't get deleted during the lifetime of this
  36355. object
  36356. @param threadToUse a thread object that this list can use
  36357. to scan for files as a background task. Make sure
  36358. that the thread you give it has been started, or you
  36359. won't get any files!
  36360. */
  36361. DirectoryContentsList (const FileFilter* const fileFilter,
  36362. TimeSliceThread& threadToUse);
  36363. /** Destructor. */
  36364. ~DirectoryContentsList();
  36365. /** Sets the directory to look in for files.
  36366. If the directory that's passed in is different to the current one, this will
  36367. also start the background thread scanning it for files.
  36368. */
  36369. void setDirectory (const File& directory,
  36370. const bool includeDirectories,
  36371. const bool includeFiles);
  36372. /** Returns the directory that's currently being used. */
  36373. const File& getDirectory() const throw();
  36374. /** Clears the list, and stops the thread scanning for files. */
  36375. void clear();
  36376. /** Clears the list and restarts scanning the directory for files. */
  36377. void refresh();
  36378. /** True if the background thread hasn't yet finished scanning for files. */
  36379. bool isStillLoading() const;
  36380. /** Tells the list whether or not to ignore hidden files.
  36381. By default these are ignored.
  36382. */
  36383. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  36384. /** Contains cached information about one of the files in a DirectoryContentsList.
  36385. */
  36386. struct FileInfo
  36387. {
  36388. /** The filename.
  36389. This isn't a full pathname, it's just the last part of the path, same as you'd
  36390. get from File::getFileName().
  36391. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36392. */
  36393. String filename;
  36394. /** File size in bytes. */
  36395. int64 fileSize;
  36396. /** File modification time.
  36397. As supplied by File::getLastModificationTime().
  36398. */
  36399. Time modificationTime;
  36400. /** File creation time.
  36401. As supplied by File::getCreationTime().
  36402. */
  36403. Time creationTime;
  36404. /** True if the file is a directory. */
  36405. bool isDirectory;
  36406. /** True if the file is read-only. */
  36407. bool isReadOnly;
  36408. };
  36409. /** Returns the number of files currently available in the list.
  36410. The info about one of these files can be retrieved with getFileInfo() or
  36411. getFile().
  36412. Obviously as the background thread runs and scans the directory for files, this
  36413. number will change.
  36414. @see getFileInfo, getFile
  36415. */
  36416. int getNumFiles() const;
  36417. /** Returns the cached information about one of the files in the list.
  36418. If the index is in-range, this will return true and will copy the file's details
  36419. to the structure that is passed-in.
  36420. If it returns false, then the index wasn't in range, and the structure won't
  36421. be affected.
  36422. @see getNumFiles, getFile
  36423. */
  36424. bool getFileInfo (const int index,
  36425. FileInfo& resultInfo) const;
  36426. /** Returns one of the files in the list.
  36427. @param index should be less than getNumFiles(). If this is out-of-range, the
  36428. return value will be File::nonexistent
  36429. @see getNumFiles, getFileInfo
  36430. */
  36431. const File getFile (const int index) const;
  36432. /** Returns the file filter being used.
  36433. The filter is specified in the constructor.
  36434. */
  36435. const FileFilter* getFilter() const throw() { return fileFilter; }
  36436. /** @internal */
  36437. bool useTimeSlice();
  36438. /** @internal */
  36439. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  36440. /** @internal */
  36441. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  36442. const DirectoryContentsList::FileInfo* const second) throw();
  36443. juce_UseDebuggingNewOperator
  36444. private:
  36445. File root;
  36446. const FileFilter* fileFilter;
  36447. TimeSliceThread& thread;
  36448. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  36449. CriticalSection fileListLock;
  36450. OwnedArray <FileInfo> files;
  36451. void* volatile fileFindHandle;
  36452. bool volatile shouldStop;
  36453. void changed();
  36454. bool checkNextFile (bool& hasChanged);
  36455. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  36456. const int64 fileSize, const Time& modTime,
  36457. const Time& creationTime, const bool isReadOnly);
  36458. DirectoryContentsList (const DirectoryContentsList&);
  36459. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  36460. };
  36461. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36462. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  36463. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  36464. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36465. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36466. /**
  36467. A listener for user selection events in a file browser.
  36468. This is used by a FileBrowserComponent or FileListComponent.
  36469. */
  36470. class JUCE_API FileBrowserListener
  36471. {
  36472. public:
  36473. /** Destructor. */
  36474. virtual ~FileBrowserListener();
  36475. /** Callback when the user selects a different file in the browser. */
  36476. virtual void selectionChanged() = 0;
  36477. /** Callback when the user clicks on a file in the browser. */
  36478. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36479. /** Callback when the user double-clicks on a file in the browser. */
  36480. virtual void fileDoubleClicked (const File& file) = 0;
  36481. };
  36482. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36483. /********* End of inlined file: juce_FileBrowserListener.h *********/
  36484. /**
  36485. A base class for components that display a list of the files in a directory.
  36486. @see DirectoryContentsList
  36487. */
  36488. class JUCE_API DirectoryContentsDisplayComponent
  36489. {
  36490. public:
  36491. /**
  36492. */
  36493. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36494. /** Destructor. */
  36495. virtual ~DirectoryContentsDisplayComponent();
  36496. /** Returns the file that the user has currently selected.
  36497. Returns File::nonexistent if none is selected.
  36498. */
  36499. virtual const File getSelectedFile() const = 0;
  36500. /** Scrolls this view to the top. */
  36501. virtual void scrollToTop() = 0;
  36502. /** Adds a listener to be told when files are selected or clicked.
  36503. @see removeListener
  36504. */
  36505. void addListener (FileBrowserListener* const listener) throw();
  36506. /** Removes a listener.
  36507. @see addListener
  36508. */
  36509. void removeListener (FileBrowserListener* const listener) throw();
  36510. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36511. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36512. methods.
  36513. Note that you can also use the constants from TextEditor::ColourIds to change the
  36514. colour of the text editor that is opened when a label is editable.
  36515. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36516. */
  36517. enum ColourIds
  36518. {
  36519. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36520. textColourId = 0x1000541, /**< The colour for the text. */
  36521. };
  36522. /** @internal */
  36523. void sendSelectionChangeMessage();
  36524. /** @internal */
  36525. void sendDoubleClickMessage (const File& file);
  36526. /** @internal */
  36527. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36528. juce_UseDebuggingNewOperator
  36529. protected:
  36530. DirectoryContentsList& fileList;
  36531. SortedSet <void*> listeners;
  36532. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36533. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36534. };
  36535. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36536. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36537. #endif
  36538. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36539. #endif
  36540. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36541. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  36542. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36543. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36544. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  36545. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36546. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36547. /**
  36548. Base class for components that live inside a file chooser dialog box and
  36549. show previews of the files that get selected.
  36550. One of these allows special extra information to be displayed for files
  36551. in a dialog box as the user selects them. Each time the current file or
  36552. directory is changed, the selectedFileChanged() method will be called
  36553. to allow it to update itself appropriately.
  36554. @see FileChooser, ImagePreviewComponent
  36555. */
  36556. class JUCE_API FilePreviewComponent : public Component
  36557. {
  36558. public:
  36559. /** Creates a FilePreviewComponent. */
  36560. FilePreviewComponent();
  36561. /** Destructor. */
  36562. ~FilePreviewComponent();
  36563. /** Called to indicate that the user's currently selected file has changed.
  36564. @param newSelectedFile the newly selected file or directory, which may be
  36565. File::nonexistent if none is selected.
  36566. */
  36567. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36568. juce_UseDebuggingNewOperator
  36569. private:
  36570. FilePreviewComponent (const FilePreviewComponent&);
  36571. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  36572. };
  36573. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36574. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  36575. /**
  36576. A component for browsing and selecting a file or directory to open or save.
  36577. This contains a FileListComponent and adds various boxes and controls for
  36578. navigating and selecting a file. It can work in different modes so that it can
  36579. be used for loading or saving a file, or for choosing a directory.
  36580. @see FileChooserDialogBox, FileChooser, FileListComponent
  36581. */
  36582. class JUCE_API FileBrowserComponent : public Component,
  36583. public ChangeBroadcaster,
  36584. private FileBrowserListener,
  36585. private TextEditorListener,
  36586. private ButtonListener,
  36587. private ComboBoxListener
  36588. {
  36589. public:
  36590. /** Various modes that the browser can be used in.
  36591. One of these is passed into the constructor.
  36592. */
  36593. enum FileChooserMode
  36594. {
  36595. loadFileMode, /**< the component should allow the user to choose an existing
  36596. file with the intention of opening it. */
  36597. saveFileMode, /**< the component should allow the user to specify the name of
  36598. a file that will be used to save something. */
  36599. chooseDirectoryMode /**< the component should allow the user to select an existing
  36600. directory. */
  36601. };
  36602. /** Creates a FileBrowserComponent.
  36603. @param browserMode The intended purpose for the browser - see the
  36604. FileChooserMode enum for the various options
  36605. @param initialFileOrDirectory The file or directory that should be selected when
  36606. the component begins. If this is File::nonexistent,
  36607. a default directory will be chosen.
  36608. @param fileFilter an optional filter to use to determine which files
  36609. are shown. If this is 0 then all files are displayed. Note
  36610. that a pointer is kept internally to this object, so
  36611. make sure that it is not deleted before the browser object
  36612. is deleted.
  36613. @param previewComp an optional preview component that will be used to
  36614. show previews of files that the user selects
  36615. @param useTreeView if this is false, the files are shown in a list; if true,
  36616. they are shown in a treeview
  36617. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  36618. text into the filename box.
  36619. */
  36620. FileBrowserComponent (FileChooserMode browserMode,
  36621. const File& initialFileOrDirectory,
  36622. const FileFilter* fileFilter,
  36623. FilePreviewComponent* previewComp,
  36624. const bool useTreeView = false,
  36625. const bool filenameTextBoxIsReadOnly = false);
  36626. /** Destructor. */
  36627. ~FileBrowserComponent();
  36628. /**
  36629. */
  36630. const File getCurrentFile() const throw();
  36631. /** Returns true if the current file is usable.
  36632. This can be used to decide whether the user can press "ok" for the
  36633. current file. What it does depends on the mode, so for example in an "open"
  36634. mode, the current file is only valid if one has been selected and if the file
  36635. exists. In a "save" mode, a non-existent file would also be valid.
  36636. */
  36637. bool currentFileIsValid() const;
  36638. /** Returns the directory whose contents are currently being shown in the listbox. */
  36639. const File getRoot() const;
  36640. /** Changes the directory that's being shown in the listbox. */
  36641. void setRoot (const File& newRootDirectory);
  36642. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36643. void goUp();
  36644. /** Refreshes the directory that's currently being listed. */
  36645. void refresh();
  36646. /** Returns the browser's current mode. */
  36647. FileChooserMode getMode() const throw() { return mode; }
  36648. /** Returns a verb to describe what should happen when the file is accepted.
  36649. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36650. mode, it'll be "Save", etc.
  36651. */
  36652. virtual const String getActionVerb() const;
  36653. /** Adds a listener to be told when the user selects and clicks on files.
  36654. @see removeListener
  36655. */
  36656. void addListener (FileBrowserListener* const listener) throw();
  36657. /** Removes a listener.
  36658. @see addListener
  36659. */
  36660. void removeListener (FileBrowserListener* const listener) throw();
  36661. /** @internal */
  36662. void resized();
  36663. /** @internal */
  36664. void buttonClicked (Button* b);
  36665. /** @internal */
  36666. void comboBoxChanged (ComboBox*);
  36667. /** @internal */
  36668. void textEditorTextChanged (TextEditor& editor);
  36669. /** @internal */
  36670. void textEditorReturnKeyPressed (TextEditor& editor);
  36671. /** @internal */
  36672. void textEditorEscapeKeyPressed (TextEditor& editor);
  36673. /** @internal */
  36674. void textEditorFocusLost (TextEditor& editor);
  36675. /** @internal */
  36676. void selectionChanged();
  36677. /** @internal */
  36678. void fileClicked (const File& f, const MouseEvent& e);
  36679. /** @internal */
  36680. void fileDoubleClicked (const File& f);
  36681. /** @internal */
  36682. FilePreviewComponent* getPreviewComponent() const throw();
  36683. juce_UseDebuggingNewOperator
  36684. protected:
  36685. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  36686. private:
  36687. DirectoryContentsList* fileList;
  36688. FileFilter* directoriesOnlyFilter;
  36689. FileChooserMode mode;
  36690. File currentRoot;
  36691. SortedSet <void*> listeners;
  36692. DirectoryContentsDisplayComponent* fileListComponent;
  36693. FilePreviewComponent* previewComp;
  36694. ComboBox* currentPathBox;
  36695. TextEditor* filenameBox;
  36696. Button* goUpButton;
  36697. TimeSliceThread thread;
  36698. void sendListenerChangeMessage();
  36699. FileBrowserComponent (const FileBrowserComponent&);
  36700. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  36701. };
  36702. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36703. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  36704. #endif
  36705. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36706. #endif
  36707. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36708. /********* Start of inlined file: juce_FileChooser.h *********/
  36709. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36710. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36711. /**
  36712. Creates a dialog box to choose a file or directory to load or save.
  36713. To use a FileChooser:
  36714. - create one (as a local stack variable is the neatest way)
  36715. - call one of its browseFor.. methods
  36716. - if this returns true, the user has selected a file, so you can retrieve it
  36717. with the getResult() method.
  36718. e.g. @code
  36719. void loadMooseFile()
  36720. {
  36721. FileChooser myChooser ("Please select the moose you want to load...",
  36722. File::getSpecialLocation (File::userHomeDirectory),
  36723. "*.moose");
  36724. if (myChooser.browseForFileToOpen())
  36725. {
  36726. File mooseFile (myChooser.getResult());
  36727. loadMoose (mooseFile);
  36728. }
  36729. }
  36730. @endcode
  36731. */
  36732. class JUCE_API FileChooser
  36733. {
  36734. public:
  36735. /** Creates a FileChooser.
  36736. After creating one of these, use one of the browseFor... methods to display it.
  36737. @param dialogBoxTitle a text string to display in the dialog box to
  36738. tell the user what's going on
  36739. @param initialFileOrDirectory the file or directory that should be selected when
  36740. the dialog box opens. If this parameter is set to
  36741. File::nonexistent, a sensible default directory
  36742. will be used instead.
  36743. @param filePatternsAllowed a set of file patterns to specify which files can be
  36744. selected - each pattern should be separated by a
  36745. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36746. empty string means that all files are allowed
  36747. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36748. possible; if false, then a Juce-based browser dialog
  36749. box will always be used
  36750. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36751. */
  36752. FileChooser (const String& dialogBoxTitle,
  36753. const File& initialFileOrDirectory = File::nonexistent,
  36754. const String& filePatternsAllowed = String::empty,
  36755. const bool useOSNativeDialogBox = true);
  36756. /** Destructor. */
  36757. ~FileChooser();
  36758. /** Shows a dialog box to choose a file to open.
  36759. This will display the dialog box modally, using an "open file" mode, so that
  36760. it won't allow non-existent files or directories to be chosen.
  36761. @param previewComponent an optional component to display inside the dialog
  36762. box to show special info about the files that the user
  36763. is browsing. The component will not be deleted by this
  36764. object, so the caller must take care of it.
  36765. @returns true if the user selected a file, in which case, use the getResult()
  36766. method to find out what it was. Returns false if they cancelled instead.
  36767. @see browseForFileToSave, browseForDirectory
  36768. */
  36769. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36770. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36771. The files that are returned can be obtained by calling getResults(). See
  36772. browseForFileToOpen() for more info about the behaviour of this method.
  36773. */
  36774. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36775. /** Shows a dialog box to choose a file to save.
  36776. This will display the dialog box modally, using an "save file" mode, so it
  36777. will allow non-existent files to be chosen, but not directories.
  36778. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36779. the user if they're sure they want to overwrite a file that already
  36780. exists
  36781. @returns true if the user chose a file and pressed 'ok', in which case, use
  36782. the getResult() method to find out what the file was. Returns false
  36783. if they cancelled instead.
  36784. @see browseForFileToOpen, browseForDirectory
  36785. */
  36786. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  36787. /** Shows a dialog box to choose a directory.
  36788. This will display the dialog box modally, using an "open directory" mode, so it
  36789. will only allow directories to be returned, not files.
  36790. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36791. the getResult() method to find out what they chose. Returns false
  36792. if they cancelled instead.
  36793. @see browseForFileToOpen, browseForFileToSave
  36794. */
  36795. bool browseForDirectory();
  36796. /** Returns the last file that was chosen by one of the browseFor methods.
  36797. After calling the appropriate browseFor... method, this method lets you
  36798. find out what file or directory they chose.
  36799. Note that the file returned is only valid if the browse method returned true (i.e.
  36800. if the user pressed 'ok' rather than cancelling).
  36801. If you're using a multiple-file select, then use the getResults() method instead,
  36802. to obtain the list of all files chosen.
  36803. @see getResults
  36804. */
  36805. const File getResult() const;
  36806. /** Returns a list of all the files that were chosen during the last call to a
  36807. browse method.
  36808. This array may be empty if no files were chosen, or can contain multiple entries
  36809. if multiple files were chosen.
  36810. @see getResult
  36811. */
  36812. const OwnedArray <File>& getResults() const;
  36813. juce_UseDebuggingNewOperator
  36814. private:
  36815. String title, filters;
  36816. File startingFile;
  36817. OwnedArray <File> results;
  36818. bool useNativeDialogBox;
  36819. bool showDialog (const bool isDirectory,
  36820. const bool isSave,
  36821. const bool warnAboutOverwritingExistingFiles,
  36822. const bool selectMultipleFiles,
  36823. FilePreviewComponent* const previewComponent);
  36824. static void showPlatformDialog (OwnedArray<File>& results,
  36825. const String& title,
  36826. const File& file,
  36827. const String& filters,
  36828. bool isDirectory,
  36829. bool isSave,
  36830. bool warnAboutOverwritingExistingFiles,
  36831. bool selectMultipleFiles,
  36832. FilePreviewComponent* previewComponent);
  36833. };
  36834. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36835. /********* End of inlined file: juce_FileChooser.h *********/
  36836. #endif
  36837. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36838. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  36839. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36840. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36841. /**
  36842. A file open/save dialog box.
  36843. This is a Juce-based file dialog box; to use a native file chooser, see the
  36844. FileChooser class.
  36845. To use one of these, create it and call its show() method. e.g.
  36846. @code
  36847. {
  36848. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  36849. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  36850. File::nonexistent,
  36851. &wildcardFilter,
  36852. 0);
  36853. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  36854. T("Please choose some kind of file that you want to open..."),
  36855. browser,
  36856. getLookAndFeel().alertWindowBackground);
  36857. if (dialogBox.show())
  36858. {
  36859. File selectedFile = browser.getCurrentFile();
  36860. ...
  36861. }
  36862. }
  36863. @endcode
  36864. @see FileChooser
  36865. */
  36866. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  36867. public ButtonListener,
  36868. public FileBrowserListener
  36869. {
  36870. public:
  36871. /** Creates a file chooser box.
  36872. @param title the main title to show at the top of the box
  36873. @param instructions an optional longer piece of text to show below the title in
  36874. a smaller font, describing in more detail what's required.
  36875. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  36876. box. Make sure you delete this after (but not before!) the
  36877. dialog box has been deleted.
  36878. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  36879. if they try to select a file that already exists. (This
  36880. flag is only used when saving files)
  36881. @param backgroundColour the background colour for the top level window
  36882. @see FileBrowserComponent, FilePreviewComponent
  36883. */
  36884. FileChooserDialogBox (const String& title,
  36885. const String& instructions,
  36886. FileBrowserComponent& browserComponent,
  36887. const bool warnAboutOverwritingExistingFiles,
  36888. const Colour& backgroundColour);
  36889. /** Destructor. */
  36890. ~FileChooserDialogBox();
  36891. /** Displays and runs the dialog box modally.
  36892. This will show the box with the specified size, returning true if the user
  36893. pressed 'ok', or false if they cancelled.
  36894. Leave the width or height as 0 to use the default size
  36895. */
  36896. bool show (int width = 0,int height = 0);
  36897. /** @internal */
  36898. void buttonClicked (Button* button);
  36899. /** @internal */
  36900. void closeButtonPressed();
  36901. /** @internal */
  36902. void selectionChanged();
  36903. /** @internal */
  36904. void fileClicked (const File& file, const MouseEvent& e);
  36905. /** @internal */
  36906. void fileDoubleClicked (const File& file);
  36907. juce_UseDebuggingNewOperator
  36908. private:
  36909. class ContentComponent : public Component
  36910. {
  36911. public:
  36912. ContentComponent();
  36913. ~ContentComponent();
  36914. void paint (Graphics& g);
  36915. void resized();
  36916. String instructions;
  36917. GlyphArrangement text;
  36918. FileBrowserComponent* chooserComponent;
  36919. FilePreviewComponent* previewComponent;
  36920. TextButton* okButton;
  36921. TextButton* cancelButton;
  36922. };
  36923. ContentComponent* content;
  36924. const bool warnAboutOverwritingExistingFiles;
  36925. FileChooserDialogBox (const FileChooserDialogBox&);
  36926. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  36927. };
  36928. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36929. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  36930. #endif
  36931. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36932. #endif
  36933. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36934. /********* Start of inlined file: juce_FileListComponent.h *********/
  36935. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36936. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36937. /**
  36938. A component that displays the files in a directory as a listbox.
  36939. This implements the DirectoryContentsDisplayComponent base class so that
  36940. it can be used in a FileBrowserComponent.
  36941. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  36942. class and the FileBrowserListener class.
  36943. @see DirectoryContentsList, FileTreeComponent
  36944. */
  36945. class JUCE_API FileListComponent : public ListBox,
  36946. public DirectoryContentsDisplayComponent,
  36947. private ListBoxModel,
  36948. private ChangeListener
  36949. {
  36950. public:
  36951. /** Creates a listbox to show the contents of a specified directory.
  36952. */
  36953. FileListComponent (DirectoryContentsList& listToShow);
  36954. /** Destructor. */
  36955. ~FileListComponent();
  36956. /** Returns the file that the user has currently selected.
  36957. Returns File::nonexistent if none is selected.
  36958. */
  36959. const File getSelectedFile() const;
  36960. /** Scrolls to the top of the list. */
  36961. void scrollToTop();
  36962. /** @internal */
  36963. void changeListenerCallback (void*);
  36964. /** @internal */
  36965. int getNumRows();
  36966. /** @internal */
  36967. void paintListBoxItem (int, Graphics&, int, int, bool);
  36968. /** @internal */
  36969. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  36970. /** @internal */
  36971. void selectedRowsChanged (int lastRowSelected);
  36972. /** @internal */
  36973. void deleteKeyPressed (int currentSelectedRow);
  36974. /** @internal */
  36975. void returnKeyPressed (int currentSelectedRow);
  36976. juce_UseDebuggingNewOperator
  36977. private:
  36978. FileListComponent (const FileListComponent&);
  36979. const FileListComponent& operator= (const FileListComponent&);
  36980. File lastDirectory;
  36981. };
  36982. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  36983. /********* End of inlined file: juce_FileListComponent.h *********/
  36984. #endif
  36985. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36986. /********* Start of inlined file: juce_FilenameComponent.h *********/
  36987. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36988. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36989. class FilenameComponent;
  36990. /**
  36991. Listens for events happening to a FilenameComponent.
  36992. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  36993. register one of these objects for event callbacks when the filename is changed.
  36994. @See FilenameComponent
  36995. */
  36996. class JUCE_API FilenameComponentListener
  36997. {
  36998. public:
  36999. /** Destructor. */
  37000. virtual ~FilenameComponentListener() {}
  37001. /** This method is called after the FilenameComponent's file has been changed. */
  37002. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37003. };
  37004. /**
  37005. Shows a filename as an editable text box, with a 'browse' button and a
  37006. drop-down list for recently selected files.
  37007. A handy component for dialogue boxes where you want the user to be able to
  37008. select a file or directory.
  37009. Attach an FilenameComponentListener using the addListener() method, and it will
  37010. get called each time the user changes the filename, either by browsing for a file
  37011. and clicking 'ok', or by typing a new filename into the box and pressing return.
  37012. @see FileChooser, ComboBox
  37013. */
  37014. class JUCE_API FilenameComponent : public Component,
  37015. public SettableTooltipClient,
  37016. public FileDragAndDropTarget,
  37017. private AsyncUpdater,
  37018. private ButtonListener,
  37019. private ComboBoxListener
  37020. {
  37021. public:
  37022. /** Creates a FilenameComponent.
  37023. @param name the name for this component.
  37024. @param currentFile the file to initially show in the box
  37025. @param canEditFilename if true, the user can manually edit the filename; if false,
  37026. they can only change it by browsing for a new file
  37027. @param isDirectory if true, the file will be treated as a directory, and
  37028. an appropriate directory browser used
  37029. @param isForSaving if true, the file browser will allow non-existent files to
  37030. be picked, as the file is assumed to be used for saving rather
  37031. than loading
  37032. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37033. If an empty string is passed in, then the pattern is assumed to be "*"
  37034. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37035. to any filenames that are entered or chosen
  37036. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37037. will only appear if the initial file isn't valid)
  37038. */
  37039. FilenameComponent (const String& name,
  37040. const File& currentFile,
  37041. const bool canEditFilename,
  37042. const bool isDirectory,
  37043. const bool isForSaving,
  37044. const String& fileBrowserWildcard,
  37045. const String& enforcedSuffix,
  37046. const String& textWhenNothingSelected);
  37047. /** Destructor. */
  37048. ~FilenameComponent();
  37049. /** Returns the currently displayed filename. */
  37050. const File getCurrentFile() const;
  37051. /** Changes the current filename.
  37052. If addToRecentlyUsedList is true, the filename will also be added to the
  37053. drop-down list of recent files.
  37054. If sendChangeNotification is false, then the listeners won't be told of the
  37055. change.
  37056. */
  37057. void setCurrentFile (File newFile,
  37058. const bool addToRecentlyUsedList,
  37059. const bool sendChangeNotification = true);
  37060. /** Changes whether the use can type into the filename box.
  37061. */
  37062. void setFilenameIsEditable (const bool shouldBeEditable);
  37063. /** Sets a file or directory to be the default starting point for the browser to show.
  37064. This is only used if the current file hasn't been set.
  37065. */
  37066. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37067. /** Returns all the entries on the recent files list.
  37068. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37069. state of this list.
  37070. @see setRecentlyUsedFilenames
  37071. */
  37072. const StringArray getRecentlyUsedFilenames() const;
  37073. /** Sets all the entries on the recent files list.
  37074. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37075. state of this list.
  37076. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37077. */
  37078. void setRecentlyUsedFilenames (const StringArray& filenames);
  37079. /** Adds an entry to the recently-used files dropdown list.
  37080. If the file is already in the list, it will be moved to the top. A limit
  37081. is also placed on the number of items that are kept in the list.
  37082. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37083. */
  37084. void addRecentlyUsedFile (const File& file);
  37085. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37086. */
  37087. void setMaxNumberOfRecentFiles (const int newMaximum);
  37088. /** Changes the text shown on the 'browse' button.
  37089. By default this button just says "..." but you can change it. The button itself
  37090. can be changed using the look-and-feel classes, so it might not actually have any
  37091. text on it.
  37092. */
  37093. void setBrowseButtonText (const String& browseButtonText);
  37094. /** Adds a listener that will be called when the selected file is changed. */
  37095. void addListener (FilenameComponentListener* const listener) throw();
  37096. /** Removes a previously-registered listener. */
  37097. void removeListener (FilenameComponentListener* const listener) throw();
  37098. /** Gives the component a tooltip. */
  37099. void setTooltip (const String& newTooltip);
  37100. /** @internal */
  37101. void paintOverChildren (Graphics& g);
  37102. /** @internal */
  37103. void resized();
  37104. /** @internal */
  37105. void lookAndFeelChanged();
  37106. /** @internal */
  37107. bool isInterestedInFileDrag (const StringArray& files);
  37108. /** @internal */
  37109. void filesDropped (const StringArray& files, int, int);
  37110. /** @internal */
  37111. void fileDragEnter (const StringArray& files, int, int);
  37112. /** @internal */
  37113. void fileDragExit (const StringArray& files);
  37114. juce_UseDebuggingNewOperator
  37115. private:
  37116. ComboBox* filenameBox;
  37117. String lastFilename;
  37118. Button* browseButton;
  37119. int maxRecentFiles;
  37120. bool isDir, isSaving, isFileDragOver;
  37121. String wildcard, enforcedSuffix, browseButtonText;
  37122. SortedSet <void*> listeners;
  37123. File defaultBrowseFile;
  37124. void comboBoxChanged (ComboBox*);
  37125. void buttonClicked (Button* button);
  37126. void handleAsyncUpdate();
  37127. FilenameComponent (const FilenameComponent&);
  37128. const FilenameComponent& operator= (const FilenameComponent&);
  37129. };
  37130. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37131. /********* End of inlined file: juce_FilenameComponent.h *********/
  37132. #endif
  37133. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37134. #endif
  37135. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37136. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37137. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37138. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37139. /**
  37140. Shows a set of file paths in a list, allowing them to be added, removed or
  37141. re-ordered.
  37142. @see FileSearchPath
  37143. */
  37144. class JUCE_API FileSearchPathListComponent : public Component,
  37145. public SettableTooltipClient,
  37146. public FileDragAndDropTarget,
  37147. private ButtonListener,
  37148. private ListBoxModel
  37149. {
  37150. public:
  37151. /** Creates an empty FileSearchPathListComponent.
  37152. */
  37153. FileSearchPathListComponent();
  37154. /** Destructor. */
  37155. ~FileSearchPathListComponent();
  37156. /** Returns the path as it is currently shown. */
  37157. const FileSearchPath& getPath() const throw() { return path; }
  37158. /** Changes the current path. */
  37159. void setPath (const FileSearchPath& newPath);
  37160. /** Sets a file or directory to be the default starting point for the browser to show.
  37161. This is only used if the current file hasn't been set.
  37162. */
  37163. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37164. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37165. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37166. methods.
  37167. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37168. */
  37169. enum ColourIds
  37170. {
  37171. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37172. Make this transparent if you don't want the background to be filled. */
  37173. };
  37174. /** @internal */
  37175. int getNumRows();
  37176. /** @internal */
  37177. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37178. /** @internal */
  37179. void deleteKeyPressed (int lastRowSelected);
  37180. /** @internal */
  37181. void returnKeyPressed (int lastRowSelected);
  37182. /** @internal */
  37183. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37184. /** @internal */
  37185. void selectedRowsChanged (int lastRowSelected);
  37186. /** @internal */
  37187. void resized();
  37188. /** @internal */
  37189. void paint (Graphics& g);
  37190. /** @internal */
  37191. bool isInterestedInFileDrag (const StringArray& files);
  37192. /** @internal */
  37193. void filesDropped (const StringArray& files, int, int);
  37194. /** @internal */
  37195. void buttonClicked (Button* button);
  37196. juce_UseDebuggingNewOperator
  37197. private:
  37198. FileSearchPath path;
  37199. File defaultBrowseTarget;
  37200. ListBox* listBox;
  37201. Button* addButton;
  37202. Button* removeButton;
  37203. Button* changeButton;
  37204. Button* upButton;
  37205. Button* downButton;
  37206. void changed() throw();
  37207. void updateButtons() throw();
  37208. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37209. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37210. };
  37211. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37212. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37213. #endif
  37214. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37215. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37216. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37217. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37218. /**
  37219. A component that displays the files in a directory as a treeview.
  37220. This implements the DirectoryContentsDisplayComponent base class so that
  37221. it can be used in a FileBrowserComponent.
  37222. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37223. class and the FileBrowserListener class.
  37224. @see DirectoryContentsList, FileListComponent
  37225. */
  37226. class JUCE_API FileTreeComponent : public TreeView,
  37227. public DirectoryContentsDisplayComponent
  37228. {
  37229. public:
  37230. /** Creates a listbox to show the contents of a specified directory.
  37231. */
  37232. FileTreeComponent (DirectoryContentsList& listToShow);
  37233. /** Destructor. */
  37234. ~FileTreeComponent();
  37235. /** Returns the number of selected files in the tree.
  37236. */
  37237. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37238. /** Returns one of the files that the user has currently selected.
  37239. Returns File::nonexistent if none is selected.
  37240. */
  37241. const File getSelectedFile (int index) const throw();
  37242. /** Returns the first of the files that the user has currently selected.
  37243. Returns File::nonexistent if none is selected.
  37244. */
  37245. const File getSelectedFile() const;
  37246. /** Scrolls the list to the top. */
  37247. void scrollToTop();
  37248. /** Setting a name for this allows tree items to be dragged.
  37249. The string that you pass in here will be returned by the getDragSourceDescription()
  37250. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37251. */
  37252. void setDragAndDropDescription (const String& description) throw();
  37253. /** Returns the last value that was set by setDragAndDropDescription().
  37254. */
  37255. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37256. juce_UseDebuggingNewOperator
  37257. private:
  37258. String dragAndDropDescription;
  37259. FileTreeComponent (const FileTreeComponent&);
  37260. const FileTreeComponent& operator= (const FileTreeComponent&);
  37261. };
  37262. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37263. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37264. #endif
  37265. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37266. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37267. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37268. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37269. /**
  37270. A simple preview component that shows thumbnails of image files.
  37271. @see FileChooserDialogBox, FilePreviewComponent
  37272. */
  37273. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37274. private Timer
  37275. {
  37276. public:
  37277. /** Creates an ImagePreviewComponent. */
  37278. ImagePreviewComponent();
  37279. /** Destructor. */
  37280. ~ImagePreviewComponent();
  37281. /** @internal */
  37282. void selectedFileChanged (const File& newSelectedFile);
  37283. /** @internal */
  37284. void paint (Graphics& g);
  37285. /** @internal */
  37286. void timerCallback();
  37287. juce_UseDebuggingNewOperator
  37288. private:
  37289. File fileToLoad;
  37290. Image* currentThumbnail;
  37291. String currentDetails;
  37292. void getThumbSize (int& w, int& h) const;
  37293. ImagePreviewComponent (const ImagePreviewComponent&);
  37294. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37295. };
  37296. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37297. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37298. #endif
  37299. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37300. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37301. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37302. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37303. /**
  37304. A type of FileFilter that works by wildcard pattern matching.
  37305. This filter only allows files that match one of the specified patterns, but
  37306. allows all directories through.
  37307. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37308. */
  37309. class JUCE_API WildcardFileFilter : public FileFilter
  37310. {
  37311. public:
  37312. /**
  37313. Creates a wildcard filter for one or more patterns.
  37314. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37315. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37316. or .aiff.
  37317. The description is a name to show the user in a list of possible patterns, so
  37318. for the wav/aiff example, your description might be "audio files".
  37319. */
  37320. WildcardFileFilter (const String& wildcardPatterns,
  37321. const String& description);
  37322. /** Destructor. */
  37323. ~WildcardFileFilter();
  37324. /** Returns true if the filename matches one of the patterns specified. */
  37325. bool isFileSuitable (const File& file) const;
  37326. /** This always returns true. */
  37327. bool isDirectorySuitable (const File& file) const;
  37328. juce_UseDebuggingNewOperator
  37329. private:
  37330. StringArray wildcards;
  37331. };
  37332. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37333. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37334. #endif
  37335. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37336. /********* Start of inlined file: juce_AlertWindow.h *********/
  37337. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37338. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37339. /** A window that displays a message and has buttons for the user to react to it.
  37340. For simple dialog boxes with just a couple of buttons on them, there are
  37341. some static methods for running these.
  37342. For more complex dialogs, an AlertWindow can be created, then it can have some
  37343. buttons and components added to it, and its runModalLoop() method is then used to
  37344. show it. The value returned by runModalLoop() shows which button the
  37345. user pressed to dismiss the box.
  37346. @see ThreadWithProgressWindow
  37347. */
  37348. class JUCE_API AlertWindow : public TopLevelWindow,
  37349. private ButtonListener
  37350. {
  37351. public:
  37352. /** The type of icon to show in the dialog box. */
  37353. enum AlertIconType
  37354. {
  37355. NoIcon, /**< No icon will be shown on the dialog box. */
  37356. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37357. user to answer a question. */
  37358. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37359. warning about something and shouldn't be ignored. */
  37360. InfoIcon /**< An icon that indicates that the dialog box is just
  37361. giving the user some information, which doesn't require
  37362. a response from them. */
  37363. };
  37364. /** Creates an AlertWindow.
  37365. @param title the headline to show at the top of the dialog box
  37366. @param message a longer, more descriptive message to show underneath the
  37367. headline
  37368. @param iconType the type of icon to display
  37369. */
  37370. AlertWindow (const String& title,
  37371. const String& message,
  37372. AlertIconType iconType);
  37373. /** Destroys the AlertWindow */
  37374. ~AlertWindow();
  37375. /** Returns the type of alert icon that was specified when the window
  37376. was created. */
  37377. AlertIconType getAlertType() const throw() { return alertIconType; }
  37378. /** Changes the dialog box's message.
  37379. This will also resize the window to fit the new message if required.
  37380. */
  37381. void setMessage (const String& message);
  37382. /** Adds a button to the window.
  37383. @param name the text to show on the button
  37384. @param returnValue the value that should be returned from runModalLoop()
  37385. if this is the button that the user presses.
  37386. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37387. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37388. */
  37389. void addButton (const String& name,
  37390. const int returnValue,
  37391. const KeyPress& shortcutKey1 = KeyPress(),
  37392. const KeyPress& shortcutKey2 = KeyPress());
  37393. /** Returns the number of buttons that the window currently has. */
  37394. int getNumButtons() const;
  37395. /** Adds a textbox to the window for entering strings.
  37396. @param name an internal name for the text-box. This is the name to pass to
  37397. the getTextEditorContents() method to find out what the
  37398. user typed-in.
  37399. @param initialContents a string to show in the text box when it's first shown
  37400. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37401. text-box to label it.
  37402. @param isPasswordBox if true, the text editor will display asterisks instead of
  37403. the actual text
  37404. @see getTextEditorContents
  37405. */
  37406. void addTextEditor (const String& name,
  37407. const String& initialContents,
  37408. const String& onScreenLabel = String::empty,
  37409. const bool isPasswordBox = false);
  37410. /** Returns the contents of a named textbox.
  37411. After showing an AlertWindow that contains a text editor, this can be
  37412. used to find out what the user has typed into it.
  37413. @param nameOfTextEditor the name of the text box that you're interested in
  37414. @see addTextEditor
  37415. */
  37416. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37417. /** Adds a drop-down list of choices to the box.
  37418. After the box has been shown, the getComboBoxComponent() method can
  37419. be used to find out which item the user picked.
  37420. @param name the label to use for the drop-down list
  37421. @param items the list of items to show in it
  37422. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37423. combo-box to label it.
  37424. @see getComboBoxComponent
  37425. */
  37426. void addComboBox (const String& name,
  37427. const StringArray& items,
  37428. const String& onScreenLabel = String::empty);
  37429. /** Returns a drop-down list that was added to the AlertWindow.
  37430. @param nameOfList the name that was passed into the addComboBox() method
  37431. when creating the drop-down
  37432. @returns the ComboBox component, or 0 if none was found for the given name.
  37433. */
  37434. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37435. /** Adds a block of text.
  37436. This is handy for adding a multi-line note next to a textbox or combo-box,
  37437. to provide more details about what's going on.
  37438. */
  37439. void addTextBlock (const String& text);
  37440. /** Adds a progress-bar to the window.
  37441. @param progressValue a variable that will be repeatedly checked while the
  37442. dialog box is visible, to see how far the process has
  37443. got. The value should be in the range 0 to 1.0
  37444. */
  37445. void addProgressBarComponent (double& progressValue);
  37446. /** Adds a user-defined component to the dialog box.
  37447. @param component the component to add - its size should be set up correctly
  37448. before it is passed in. The caller is responsible for deleting
  37449. the component later on - the AlertWindow won't delete it.
  37450. */
  37451. void addCustomComponent (Component* const component);
  37452. /** Returns the number of custom components in the dialog box.
  37453. @see getCustomComponent, addCustomComponent
  37454. */
  37455. int getNumCustomComponents() const;
  37456. /** Returns one of the custom components in the dialog box.
  37457. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37458. will return 0
  37459. @see getNumCustomComponents, addCustomComponent
  37460. */
  37461. Component* getCustomComponent (const int index) const;
  37462. /** Removes one of the custom components in the dialog box.
  37463. Note that this won't delete it, it just removes the component from the window
  37464. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37465. will return 0
  37466. @returns the component that was removed (or zero)
  37467. @see getNumCustomComponents, addCustomComponent
  37468. */
  37469. Component* removeCustomComponent (const int index);
  37470. /** Returns true if the window contains any components other than just buttons.*/
  37471. bool containsAnyExtraComponents() const;
  37472. // easy-to-use message box functions:
  37473. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37474. The box is shown modally, and the method returns after the user
  37475. has clicked the button (or pressed the escape or return keys).
  37476. @param iconType the type of icon to show
  37477. @param title the headline to show at the top of the box
  37478. @param message a longer, more descriptive message to show underneath the
  37479. headline
  37480. @param buttonText the text to show in the button - if this string is empty, the
  37481. default string "ok" (or a localised version) will be used.
  37482. */
  37483. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37484. const String& title,
  37485. const String& message,
  37486. const String& buttonText = String::empty);
  37487. /** Shows a dialog box with two buttons.
  37488. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37489. to trigger the first button, and the escape key for the second button.
  37490. @param iconType the type of icon to show
  37491. @param title the headline to show at the top of the box
  37492. @param message a longer, more descriptive message to show underneath the
  37493. headline
  37494. @param button1Text the text to show in the first button - if this string is
  37495. empty, the default string "ok" (or a localised version of it)
  37496. will be used.
  37497. @param button2Text the text to show in the second button - if this string is
  37498. empty, the default string "cancel" (or a localised version of it)
  37499. will be used.
  37500. @returns true if button 1 was clicked, false if it was button 2
  37501. */
  37502. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37503. const String& title,
  37504. const String& message,
  37505. const String& button1Text = String::empty,
  37506. const String& button2Text = String::empty);
  37507. /** Shows a dialog box with three buttons.
  37508. Ideal for yes/no/cancel boxes.
  37509. The escape key can be used to trigger the third button.
  37510. @param iconType the type of icon to show
  37511. @param title the headline to show at the top of the box
  37512. @param message a longer, more descriptive message to show underneath the
  37513. headline
  37514. @param button1Text the text to show in the first button - if an empty string, then
  37515. "yes" will be used (or a localised version of it)
  37516. @param button2Text the text to show in the first button - if an empty string, then
  37517. "no" will be used (or a localised version of it)
  37518. @param button3Text the text to show in the first button - if an empty string, then
  37519. "cancel" will be used (or a localised version of it)
  37520. @returns one of the following values:
  37521. - 0 if the third button was pressed (normally used for 'cancel')
  37522. - 1 if the first button was pressed (normally used for 'yes')
  37523. - 2 if the middle button was pressed (normally used for 'no')
  37524. */
  37525. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  37526. const String& title,
  37527. const String& message,
  37528. const String& button1Text = String::empty,
  37529. const String& button2Text = String::empty,
  37530. const String& button3Text = String::empty);
  37531. /** Shows an operating-system native dialog box.
  37532. @param title the title to use at the top
  37533. @param bodyText the longer message to show
  37534. @param isOkCancel if true, this will show an ok/cancel box, if false,
  37535. it'll show a box with just an ok button
  37536. @returns true if the ok button was pressed, false if they pressed cancel.
  37537. */
  37538. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  37539. const String& bodyText,
  37540. bool isOkCancel);
  37541. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  37542. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37543. methods.
  37544. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37545. */
  37546. enum ColourIds
  37547. {
  37548. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  37549. textColourId = 0x1001810, /**< The colour for the text. */
  37550. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  37551. };
  37552. juce_UseDebuggingNewOperator
  37553. protected:
  37554. /** @internal */
  37555. void paint (Graphics& g);
  37556. /** @internal */
  37557. void mouseDown (const MouseEvent& e);
  37558. /** @internal */
  37559. void mouseDrag (const MouseEvent& e);
  37560. /** @internal */
  37561. bool keyPressed (const KeyPress& key);
  37562. /** @internal */
  37563. void buttonClicked (Button* button);
  37564. /** @internal */
  37565. void lookAndFeelChanged();
  37566. private:
  37567. String text;
  37568. TextLayout textLayout;
  37569. AlertIconType alertIconType;
  37570. ComponentBoundsConstrainer constrainer;
  37571. ComponentDragger dragger;
  37572. Rectangle textArea;
  37573. VoidArray buttons, textBoxes, comboBoxes;
  37574. VoidArray progressBars, customComps, textBlocks, allComps;
  37575. StringArray textboxNames, comboBoxNames;
  37576. Font font;
  37577. void updateLayout (const bool onlyIncreaseSize);
  37578. // disable copy constructor
  37579. AlertWindow (const AlertWindow&);
  37580. const AlertWindow& operator= (const AlertWindow&);
  37581. };
  37582. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  37583. /********* End of inlined file: juce_AlertWindow.h *********/
  37584. #endif
  37585. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  37586. #endif
  37587. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37588. /********* Start of inlined file: juce_DialogWindow.h *********/
  37589. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37590. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  37591. /**
  37592. A dialog-box style window.
  37593. This class is a convenient way of creating a DocumentWindow with a close button
  37594. that can be triggered by pressing the escape key.
  37595. Any of the methods available to a DocumentWindow or ResizableWindow are also
  37596. available to this, so it can be made resizable, have a menu bar, etc.
  37597. To add items to the box, see the ResizableWindow::setContentComponent() method.
  37598. Don't add components directly to this class - always put them in a content component!
  37599. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  37600. the user clicking the close button - for more info, see the DocumentWindow
  37601. help.
  37602. @see DocumentWindow, ResizableWindow
  37603. */
  37604. class JUCE_API DialogWindow : public DocumentWindow
  37605. {
  37606. public:
  37607. /** Creates a DialogWindow.
  37608. @param name the name to give the component - this is also
  37609. the title shown at the top of the window. To change
  37610. this later, use setName()
  37611. @param backgroundColour the colour to use for filling the window's background.
  37612. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37613. close button to be triggered
  37614. @param addToDesktop if true, the window will be automatically added to the
  37615. desktop; if false, you can use it as a child component
  37616. */
  37617. DialogWindow (const String& name,
  37618. const Colour& backgroundColour,
  37619. const bool escapeKeyTriggersCloseButton,
  37620. const bool addToDesktop = true);
  37621. /** Destructor.
  37622. If a content component has been set with setContentComponent(), it
  37623. will be deleted.
  37624. */
  37625. ~DialogWindow();
  37626. /** Easy way of quickly showing a dialog box containing a given component.
  37627. This will open and display a DialogWindow containing a given component, returning
  37628. when the user clicks its close button.
  37629. It returns the value that was returned by the dialog box's runModalLoop() call.
  37630. To close the dialog programatically, you should call exitModalState (returnValue) on
  37631. the DialogWindow that is created. To find a pointer to this window from your
  37632. contentComponent, you can do something like this:
  37633. @code
  37634. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  37635. if (dw != 0)
  37636. dw->exitModalState (1234);
  37637. @endcode
  37638. @param dialogTitle the dialog box's title
  37639. @param contentComponent the content component for the dialog box. Make sure
  37640. that this has been set to the size you want it to
  37641. be before calling this method. The component won't
  37642. be deleted by this call, so you can re-use it or delete
  37643. it afterwards
  37644. @param componentToCentreAround if this is non-zero, it indicates a component that
  37645. you'd like to show this dialog box in front of. See the
  37646. DocumentWindow::centreAroundComponent() method for more
  37647. info on this parameter
  37648. @param backgroundColour a colour to use for the dialog box's background colour
  37649. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37650. close button to be triggered
  37651. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  37652. a corner resizer
  37653. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  37654. to use a border or corner resizer component. See ResizableWindow::setResizable()
  37655. */
  37656. static int showModalDialog (const String& dialogTitle,
  37657. Component* contentComponent,
  37658. Component* componentToCentreAround,
  37659. const Colour& backgroundColour,
  37660. const bool escapeKeyTriggersCloseButton,
  37661. const bool shouldBeResizable = false,
  37662. const bool useBottomRightCornerResizer = false);
  37663. juce_UseDebuggingNewOperator
  37664. protected:
  37665. /** @internal */
  37666. void resized();
  37667. private:
  37668. bool escapeKeyTriggersCloseButton;
  37669. DialogWindow (const DialogWindow&);
  37670. const DialogWindow& operator= (const DialogWindow&);
  37671. };
  37672. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  37673. /********* End of inlined file: juce_DialogWindow.h *********/
  37674. #endif
  37675. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37676. #endif
  37677. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37678. #endif
  37679. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37680. /********* Start of inlined file: juce_SplashScreen.h *********/
  37681. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  37682. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  37683. /** A component for showing a splash screen while your app starts up.
  37684. This will automatically position itself, and delete itself when the app has
  37685. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  37686. this).
  37687. To use it, just create one of these in your JUCEApplication::initialise() method,
  37688. call its show() method and let the object delete itself later.
  37689. E.g. @code
  37690. void MyApp::initialise (const String& commandLine)
  37691. {
  37692. SplashScreen* splash = new SplashScreen();
  37693. splash->show (T("welcome to my app"),
  37694. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  37695. 4000, false);
  37696. .. no need to delete the splash screen - it'll do that itself.
  37697. }
  37698. @endcode
  37699. */
  37700. class JUCE_API SplashScreen : public Component,
  37701. public Timer,
  37702. private DeletedAtShutdown
  37703. {
  37704. public:
  37705. /** Creates a SplashScreen object.
  37706. After creating one of these (or your subclass of it), call one of the show()
  37707. methods to display it.
  37708. */
  37709. SplashScreen();
  37710. /** Destructor. */
  37711. ~SplashScreen();
  37712. /** Creates a SplashScreen object that will display an image.
  37713. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37714. screen. This method will also dispatch any pending messages to make sure that when
  37715. it returns, the splash screen has been completely drawn, and your initialisation
  37716. code can carry on.
  37717. @param title the name to give the component
  37718. @param backgroundImage an image to draw on the component. The component's size
  37719. will be set to the size of this image, and if the image is
  37720. semi-transparent, the component will be made semi-transparent
  37721. too. This image will be deleted (or released from the ImageCache
  37722. if that's how it was created) by the splash screen object when
  37723. it is itself deleted.
  37724. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37725. should stay visible for. If the initialisation takes longer than
  37726. this time, the splash screen will wait for it to finish before
  37727. disappearing, but if initialisation is very quick, this lets
  37728. you make sure that people get a good look at your splash.
  37729. @param useDropShadow if true, the window will have a drop shadow
  37730. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37731. the mouse (anywhere)
  37732. */
  37733. void show (const String& title,
  37734. Image* const backgroundImage,
  37735. const int minimumTimeToDisplayFor,
  37736. const bool useDropShadow,
  37737. const bool removeOnMouseClick = true);
  37738. /** Creates a SplashScreen object with a specified size.
  37739. For a custom splash screen, you can use this method to display it at a certain size
  37740. and then override the paint() method yourself to do whatever's necessary.
  37741. As soon as this is called, the SplashScreen will be displayed in the centre of the
  37742. screen. This method will also dispatch any pending messages to make sure that when
  37743. it returns, the splash screen has been completely drawn, and your initialisation
  37744. code can carry on.
  37745. @param title the name to give the component
  37746. @param width the width to use
  37747. @param height the height to use
  37748. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  37749. should stay visible for. If the initialisation takes longer than
  37750. this time, the splash screen will wait for it to finish before
  37751. disappearing, but if initialisation is very quick, this lets
  37752. you make sure that people get a good look at your splash.
  37753. @param useDropShadow if true, the window will have a drop shadow
  37754. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  37755. the mouse (anywhere)
  37756. */
  37757. void show (const String& title,
  37758. const int width,
  37759. const int height,
  37760. const int minimumTimeToDisplayFor,
  37761. const bool useDropShadow,
  37762. const bool removeOnMouseClick = true);
  37763. /** @internal */
  37764. void paint (Graphics& g);
  37765. /** @internal */
  37766. void timerCallback();
  37767. juce_UseDebuggingNewOperator
  37768. private:
  37769. Image* backgroundImage;
  37770. Time earliestTimeToDelete;
  37771. int originalClickCounter;
  37772. bool isImageInCache;
  37773. SplashScreen (const SplashScreen&);
  37774. const SplashScreen& operator= (const SplashScreen&);
  37775. };
  37776. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  37777. /********* End of inlined file: juce_SplashScreen.h *********/
  37778. #endif
  37779. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37780. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  37781. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37782. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37783. /**
  37784. A thread that automatically pops up a modal dialog box with a progress bar
  37785. and cancel button while it's busy running.
  37786. These are handy for performing some sort of task while giving the user feedback
  37787. about how long there is to go, etc.
  37788. E.g. @code
  37789. class MyTask : public ThreadWithProgressWindow
  37790. {
  37791. public:
  37792. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  37793. {
  37794. }
  37795. ~MyTask()
  37796. {
  37797. }
  37798. void run()
  37799. {
  37800. for (int i = 0; i < thingsToDo; ++i)
  37801. {
  37802. // must check this as often as possible, because this is
  37803. // how we know if the user's pressed 'cancel'
  37804. if (threadShouldExit())
  37805. break;
  37806. // this will update the progress bar on the dialog box
  37807. setProgress (i / (double) thingsToDo);
  37808. // ... do the business here...
  37809. }
  37810. }
  37811. };
  37812. void doTheTask()
  37813. {
  37814. MyTask m;
  37815. if (m.runThread())
  37816. {
  37817. // thread finished normally..
  37818. }
  37819. else
  37820. {
  37821. // user pressed the cancel button..
  37822. }
  37823. }
  37824. @endcode
  37825. @see Thread, AlertWindow
  37826. */
  37827. class JUCE_API ThreadWithProgressWindow : public Thread,
  37828. private Timer
  37829. {
  37830. public:
  37831. /** Creates the thread.
  37832. Initially, the dialog box won't be visible, it'll only appear when the
  37833. runThread() method is called.
  37834. @param windowTitle the title to go at the top of the dialog box
  37835. @param hasProgressBar whether the dialog box should have a progress bar (see
  37836. setProgress() )
  37837. @param hasCancelButton whether the dialog box should have a cancel button
  37838. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  37839. the thread to stop before killing it forcibly (see
  37840. Thread::stopThread() )
  37841. @param cancelButtonText the text that should be shown in the cancel button
  37842. (if it has one)
  37843. */
  37844. ThreadWithProgressWindow (const String& windowTitle,
  37845. const bool hasProgressBar,
  37846. const bool hasCancelButton,
  37847. const int timeOutMsWhenCancelling = 10000,
  37848. const String& cancelButtonText = JUCE_T("Cancel"));
  37849. /** Destructor. */
  37850. ~ThreadWithProgressWindow();
  37851. /** Starts the thread and waits for it to finish.
  37852. This will start the thread, make the dialog box appear, and wait until either
  37853. the thread finishes normally, or until the cancel button is pressed.
  37854. Before returning, the dialog box will be hidden.
  37855. @param threadPriority the priority to use when starting the thread - see
  37856. Thread::startThread() for values
  37857. @returns true if the thread finished normally; false if the user pressed cancel
  37858. */
  37859. bool runThread (const int threadPriority = 5);
  37860. /** The thread should call this periodically to update the position of the progress bar.
  37861. @param newProgress the progress, from 0.0 to 1.0
  37862. @see setStatusMessage
  37863. */
  37864. void setProgress (const double newProgress);
  37865. /** The thread can call this to change the message that's displayed in the dialog box.
  37866. */
  37867. void setStatusMessage (const String& newStatusMessage);
  37868. juce_UseDebuggingNewOperator
  37869. private:
  37870. void timerCallback();
  37871. double progress;
  37872. AlertWindow alertWindow;
  37873. String message;
  37874. CriticalSection messageLock;
  37875. const int timeOutMsWhenCancelling;
  37876. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  37877. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  37878. };
  37879. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  37880. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  37881. #endif
  37882. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  37883. #endif
  37884. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37885. #endif
  37886. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37887. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  37888. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37889. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37890. #if JUCE_WIN32 || DOXYGEN
  37891. /**
  37892. A Windows-specific class that can create and embed an ActiveX control inside
  37893. itself.
  37894. To use it, create one of these, put it in place and make sure it's visible in a
  37895. window, then use createControl() to instantiate an ActiveX control. The control
  37896. will then be moved and resized to follow the movements of this component.
  37897. Of course, since the control is a heavyweight window, it'll obliterate any
  37898. juce components that may overlap this component, but that's life.
  37899. */
  37900. class JUCE_API ActiveXControlComponent : public Component
  37901. {
  37902. public:
  37903. /** Create an initially-empty container. */
  37904. ActiveXControlComponent();
  37905. /** Destructor. */
  37906. ~ActiveXControlComponent();
  37907. /** Tries to create an ActiveX control and embed it in this peer.
  37908. The peer controlIID is a pointer to an IID structure - it's treated
  37909. as a void* because when including the Juce headers, you might not always
  37910. have included windows.h first, in which case IID wouldn't be defined.
  37911. e.g. @code
  37912. const IID myIID = __uuidof (QTControl);
  37913. myControlComp->createControl (&myIID);
  37914. @endcode
  37915. */
  37916. bool createControl (const void* controlIID);
  37917. /** Deletes the ActiveX control, if one has been created.
  37918. */
  37919. void deleteControl();
  37920. /** Returns true if a control is currently in use. */
  37921. bool isControlOpen() const throw() { return control != 0; }
  37922. /** Does a QueryInterface call on the embedded control object.
  37923. This allows you to cast the control to whatever type of COM object you need.
  37924. The iid parameter is a pointer to an IID structure - it's treated
  37925. as a void* because when including the Juce headers, you might not always
  37926. have included windows.h first, in which case IID wouldn't be defined, but
  37927. you should just pass a pointer to an IID.
  37928. e.g. @code
  37929. const IID iid = __uuidof (IOleWindow);
  37930. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  37931. if (oleWindow != 0)
  37932. {
  37933. HWND hwnd;
  37934. oleWindow->GetWindow (&hwnd);
  37935. ...
  37936. oleWindow->Release();
  37937. }
  37938. @endcode
  37939. */
  37940. void* queryInterface (const void* iid) const;
  37941. /** Set this to false to stop mouse events being allowed through to the control.
  37942. */
  37943. void setMouseEventsAllowed (const bool eventsCanReachControl);
  37944. /** Returns true if mouse events are allowed to get through to the control.
  37945. */
  37946. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  37947. /** @internal */
  37948. void paint (Graphics& g);
  37949. /** @internal */
  37950. void* originalWndProc;
  37951. juce_UseDebuggingNewOperator
  37952. private:
  37953. friend class ActiveXControlData;
  37954. void* control;
  37955. bool mouseEventsAllowed;
  37956. ActiveXControlComponent (const ActiveXControlComponent&);
  37957. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  37958. void setControlBounds (const Rectangle& bounds) const;
  37959. void setControlVisible (const bool b) const;
  37960. };
  37961. #endif
  37962. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  37963. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  37964. #endif
  37965. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37966. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  37967. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37968. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  37969. class MidiInputSelectorComponentListBox;
  37970. /**
  37971. A component containing controls to let the user change the audio settings of
  37972. an AudioDeviceManager object.
  37973. Very easy to use - just create one of these and show it to the user.
  37974. @see AudioDeviceManager
  37975. */
  37976. class JUCE_API AudioDeviceSelectorComponent : public Component,
  37977. public ComboBoxListener,
  37978. public ButtonListener,
  37979. public ChangeListener
  37980. {
  37981. public:
  37982. /** Creates the component.
  37983. If your app needs only output channels, you might ask for a maximum of 0 input
  37984. channels, and the component won't display any options for choosing the input
  37985. channels. And likewise if you're doing an input-only app.
  37986. @param deviceManager the device manager that this component should control
  37987. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  37988. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  37989. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  37990. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  37991. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  37992. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  37993. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  37994. treated as a set of separate mono channels.
  37995. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  37996. are shown, with an "advanced" button that shows the rest of them
  37997. */
  37998. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  37999. const int minAudioInputChannels,
  38000. const int maxAudioInputChannels,
  38001. const int minAudioOutputChannels,
  38002. const int maxAudioOutputChannels,
  38003. const bool showMidiInputOptions,
  38004. const bool showMidiOutputSelector,
  38005. const bool showChannelsAsStereoPairs,
  38006. const bool hideAdvancedOptionsWithButton);
  38007. /** Destructor */
  38008. ~AudioDeviceSelectorComponent();
  38009. /** @internal */
  38010. void resized();
  38011. /** @internal */
  38012. void comboBoxChanged (ComboBox*);
  38013. /** @internal */
  38014. void buttonClicked (Button*);
  38015. /** @internal */
  38016. void changeListenerCallback (void*);
  38017. juce_UseDebuggingNewOperator
  38018. private:
  38019. AudioDeviceManager& deviceManager;
  38020. ComboBox* deviceTypeDropDown;
  38021. Label* deviceTypeDropDownLabel;
  38022. Component* audioDeviceSettingsComp;
  38023. String audioDeviceSettingsCompType;
  38024. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  38025. const bool showChannelsAsStereoPairs;
  38026. const bool hideAdvancedOptionsWithButton;
  38027. MidiInputSelectorComponentListBox* midiInputsList;
  38028. Label* midiInputsLabel;
  38029. ComboBox* midiOutputSelector;
  38030. Label* midiOutputLabel;
  38031. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  38032. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  38033. };
  38034. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38035. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38036. #endif
  38037. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38038. /********* Start of inlined file: juce_BubbleComponent.h *********/
  38039. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38040. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38041. /**
  38042. A component for showing a message or other graphics inside a speech-bubble-shaped
  38043. outline, pointing at a location on the screen.
  38044. This is a base class that just draws and positions the bubble shape, but leaves
  38045. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  38046. that draws a text message.
  38047. To use it, create your subclass, then either add it to a parent component or
  38048. put it on the desktop with addToDesktop (0), use setPosition() to
  38049. resize and position it, then make it visible.
  38050. @see BubbleMessageComponent
  38051. */
  38052. class JUCE_API BubbleComponent : public Component
  38053. {
  38054. protected:
  38055. /** Creates a BubbleComponent.
  38056. Your subclass will need to implement the getContentSize() and paintContent()
  38057. methods to draw the bubble's contents.
  38058. */
  38059. BubbleComponent();
  38060. public:
  38061. /** Destructor. */
  38062. ~BubbleComponent();
  38063. /** A list of permitted placements for the bubble, relative to the co-ordinates
  38064. at which it should be pointing.
  38065. @see setAllowedPlacement
  38066. */
  38067. enum BubblePlacement
  38068. {
  38069. above = 1,
  38070. below = 2,
  38071. left = 4,
  38072. right = 8
  38073. };
  38074. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  38075. point at which it's pointing.
  38076. By default when setPosition() is called, the bubble will place itself either
  38077. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  38078. the values in BubblePlacement to restrict this choice.
  38079. E.g. if you only want your bubble to appear above or below the target area,
  38080. use setAllowedPlacement (above | below);
  38081. @see BubblePlacement
  38082. */
  38083. void setAllowedPlacement (const int newPlacement);
  38084. /** Moves and resizes the bubble to point at a given component.
  38085. This will resize the bubble to fit its content, then find a position for it
  38086. so that it's next to, but doesn't overlap the given component.
  38087. It'll put itself either above, below, or to the side of the component depending
  38088. on where there's the most space, honouring any restrictions that were set
  38089. with setAllowedPlacement().
  38090. */
  38091. void setPosition (Component* componentToPointTo);
  38092. /** Moves and resizes the bubble to point at a given point.
  38093. This will resize the bubble to fit its content, then position it
  38094. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  38095. are relative to either the bubble component's parent component if it has one, or
  38096. they are screen co-ordinates if not.
  38097. It'll put itself either above, below, or to the side of this point, depending
  38098. on where there's the most space, honouring any restrictions that were set
  38099. with setAllowedPlacement().
  38100. */
  38101. void setPosition (const int arrowTipX,
  38102. const int arrowTipY);
  38103. /** Moves and resizes the bubble to point at a given rectangle.
  38104. This will resize the bubble to fit its content, then find a position for it
  38105. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  38106. co-ordinates are relative to either the bubble component's parent component
  38107. if it has one, or they are screen co-ordinates if not.
  38108. It'll put itself either above, below, or to the side of the component depending
  38109. on where there's the most space, honouring any restrictions that were set
  38110. with setAllowedPlacement().
  38111. */
  38112. void setPosition (const Rectangle& rectangleToPointTo);
  38113. protected:
  38114. /** Subclasses should override this to return the size of the content they
  38115. want to draw inside the bubble.
  38116. */
  38117. virtual void getContentSize (int& width, int& height) = 0;
  38118. /** Subclasses should override this to draw their bubble's contents.
  38119. The graphics object's clip region and the dimensions passed in here are
  38120. set up to paint just the rectangle inside the bubble.
  38121. */
  38122. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38123. public:
  38124. /** @internal */
  38125. void paint (Graphics& g);
  38126. juce_UseDebuggingNewOperator
  38127. private:
  38128. Rectangle content;
  38129. int side, allowablePlacements;
  38130. float arrowTipX, arrowTipY;
  38131. DropShadowEffect shadow;
  38132. BubbleComponent (const BubbleComponent&);
  38133. const BubbleComponent& operator= (const BubbleComponent&);
  38134. };
  38135. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38136. /********* End of inlined file: juce_BubbleComponent.h *********/
  38137. #endif
  38138. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38139. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38140. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38141. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38142. /**
  38143. A speech-bubble component that displays a short message.
  38144. This can be used to show a message with the tail of the speech bubble
  38145. pointing to a particular component or location on the screen.
  38146. @see BubbleComponent
  38147. */
  38148. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38149. private Timer
  38150. {
  38151. public:
  38152. /** Creates a bubble component.
  38153. After creating one a BubbleComponent, do the following:
  38154. - add it to an appropriate parent component, or put it on the
  38155. desktop with Component::addToDesktop (0).
  38156. - use the showAt() method to show a message.
  38157. - it will make itself invisible after it times-out (and can optionally
  38158. also delete itself), or you can reuse it somewhere else by calling
  38159. showAt() again.
  38160. */
  38161. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38162. /** Destructor. */
  38163. ~BubbleMessageComponent();
  38164. /** Shows a message bubble at a particular position.
  38165. This shows the bubble with its stem pointing to the given location
  38166. (co-ordinates being relative to its parent component).
  38167. For details about exactly how it decides where to position itself, see
  38168. BubbleComponent::updatePosition().
  38169. @param x the x co-ordinate of end of the bubble's tail
  38170. @param y the y co-ordinate of end of the bubble's tail
  38171. @param message the text to display
  38172. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38173. from its parent compnent. If this is 0 or less, it
  38174. will stay there until manually removed.
  38175. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38176. mouse button is pressed (anywhere on the screen)
  38177. @param deleteSelfAfterUse if true, then the component will delete itself after
  38178. it becomes invisible
  38179. */
  38180. void showAt (int x, int y,
  38181. const String& message,
  38182. const int numMillisecondsBeforeRemoving,
  38183. const bool removeWhenMouseClicked = true,
  38184. const bool deleteSelfAfterUse = false);
  38185. /** Shows a message bubble next to a particular component.
  38186. This shows the bubble with its stem pointing at the given component.
  38187. For details about exactly how it decides where to position itself, see
  38188. BubbleComponent::updatePosition().
  38189. @param component the component that you want to point at
  38190. @param message the text to display
  38191. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38192. from its parent compnent. If this is 0 or less, it
  38193. will stay there until manually removed.
  38194. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38195. mouse button is pressed (anywhere on the screen)
  38196. @param deleteSelfAfterUse if true, then the component will delete itself after
  38197. it becomes invisible
  38198. */
  38199. void showAt (Component* const component,
  38200. const String& message,
  38201. const int numMillisecondsBeforeRemoving,
  38202. const bool removeWhenMouseClicked = true,
  38203. const bool deleteSelfAfterUse = false);
  38204. /** @internal */
  38205. void getContentSize (int& w, int& h);
  38206. /** @internal */
  38207. void paintContent (Graphics& g, int w, int h);
  38208. /** @internal */
  38209. void timerCallback();
  38210. juce_UseDebuggingNewOperator
  38211. private:
  38212. int fadeOutLength, mouseClickCounter;
  38213. TextLayout textLayout;
  38214. int64 expiryTime;
  38215. bool deleteAfterUse;
  38216. void init (const int numMillisecondsBeforeRemoving,
  38217. const bool removeWhenMouseClicked,
  38218. const bool deleteSelfAfterUse);
  38219. BubbleMessageComponent (const BubbleMessageComponent&);
  38220. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38221. };
  38222. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38223. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38224. #endif
  38225. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38226. /********* Start of inlined file: juce_ColourSelector.h *********/
  38227. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38228. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38229. /**
  38230. A component that lets the user choose a colour.
  38231. This shows RGB sliders and a colourspace that the user can pick colours from.
  38232. This class is also a ChangeBroadcaster, so listeners can register to be told
  38233. when the colour changes.
  38234. */
  38235. class JUCE_API ColourSelector : public Component,
  38236. public ChangeBroadcaster,
  38237. protected SliderListener
  38238. {
  38239. public:
  38240. /** Options for the type of selector to show. These are passed into the constructor. */
  38241. enum ColourSelectorOptions
  38242. {
  38243. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38244. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38245. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38246. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38247. };
  38248. /** Creates a ColourSelector object.
  38249. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38250. which of the selector's features should be visible.
  38251. The edgeGap value specifies the amount of space to leave around the edge.
  38252. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38253. colourspace and hue selector components.
  38254. */
  38255. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38256. const int edgeGap = 4,
  38257. const int gapAroundColourSpaceComponent = 7);
  38258. /** Destructor. */
  38259. ~ColourSelector();
  38260. /** Returns the colour that the user has currently selected.
  38261. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38262. register to be told when the colour changes.
  38263. @see setCurrentColour
  38264. */
  38265. const Colour getCurrentColour() const;
  38266. /** Changes the colour that is currently being shown.
  38267. */
  38268. void setCurrentColour (const Colour& newColour);
  38269. /** Tells the selector how many preset colour swatches you want to have on the component.
  38270. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38271. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38272. their values.
  38273. */
  38274. virtual int getNumSwatches() const;
  38275. /** Called by the selector to find out the colour of one of the swatches.
  38276. Your subclass should return the colour of the swatch with the given index.
  38277. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38278. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38279. their values.
  38280. */
  38281. virtual const Colour getSwatchColour (const int index) const;
  38282. /** Called by the selector when the user puts a new colour into one of the swatches.
  38283. Your subclass should change the colour of the swatch with the given index.
  38284. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38285. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38286. their values.
  38287. */
  38288. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38289. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38290. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38291. methods.
  38292. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38293. */
  38294. enum ColourIds
  38295. {
  38296. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38297. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38298. };
  38299. juce_UseDebuggingNewOperator
  38300. private:
  38301. friend class ColourSpaceView;
  38302. friend class HueSelectorComp;
  38303. Colour colour;
  38304. float h, s, v;
  38305. Slider* sliders[4];
  38306. Component* colourSpace;
  38307. Component* hueSelector;
  38308. VoidArray swatchComponents;
  38309. const int flags;
  38310. int topSpace, edgeGap;
  38311. void setHue (float newH);
  38312. void setSV (float newS, float newV);
  38313. void updateHSV();
  38314. void update();
  38315. void sliderValueChanged (Slider*);
  38316. void paint (Graphics& g);
  38317. void resized();
  38318. ColourSelector (const ColourSelector&);
  38319. const ColourSelector& operator= (const ColourSelector&);
  38320. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38321. // have changed - if you get an error here, update your code to use the new constructor instead..
  38322. // (xxx - note to self: remember to remove this at some point in the future)
  38323. ColourSelector (const bool);
  38324. };
  38325. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38326. /********* End of inlined file: juce_ColourSelector.h *********/
  38327. #endif
  38328. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  38329. #endif
  38330. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38331. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  38332. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38333. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38334. /**
  38335. A component that contains another component, and can magnify or shrink it.
  38336. This component will continually update its size so that it fits the zoomed
  38337. version of the content component that you put inside it, so don't try to
  38338. change the size of this component directly - instead change that of the
  38339. content component.
  38340. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  38341. to remap mouse events correctly. This means that the content component won't
  38342. appear to be a direct child of this component, and instead will think its
  38343. on the desktop.
  38344. */
  38345. class JUCE_API MagnifierComponent : public Component
  38346. {
  38347. public:
  38348. /** Creates a MagnifierComponent.
  38349. This component will continually update its size so that it fits the zoomed
  38350. version of the content component that you put inside it, so don't try to
  38351. change the size of this component directly - instead change that of the
  38352. content component.
  38353. @param contentComponent the component to add as the magnified one
  38354. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  38355. be deleted when this component is deleted. If false,
  38356. it's the caller's responsibility to delete it later.
  38357. */
  38358. MagnifierComponent (Component* const contentComponent,
  38359. const bool deleteContentCompWhenNoLongerNeeded);
  38360. /** Destructor. */
  38361. ~MagnifierComponent();
  38362. /** Returns the current content component. */
  38363. Component* getContentComponent() const throw() { return content; }
  38364. /** Changes the zoom level.
  38365. The scale factor must be greater than zero. Values less than 1 will shrink the
  38366. image; values greater than 1 will multiply its size by this amount.
  38367. When this is called, this component will change its size to fit the full extent
  38368. of the newly zoomed content.
  38369. */
  38370. void setScaleFactor (double newScaleFactor);
  38371. /** Returns the current zoom factor. */
  38372. double getScaleFactor() const throw() { return scaleFactor; }
  38373. juce_UseDebuggingNewOperator
  38374. /** @internal */
  38375. void childBoundsChanged (Component*);
  38376. private:
  38377. Component* content;
  38378. Component* holderComp;
  38379. double scaleFactor;
  38380. ComponentPeer* peer;
  38381. bool deleteContent;
  38382. void paint (Graphics& g);
  38383. void mouseDown (const MouseEvent& e);
  38384. void mouseUp (const MouseEvent& e);
  38385. void mouseDrag (const MouseEvent& e);
  38386. void mouseMove (const MouseEvent& e);
  38387. void mouseEnter (const MouseEvent& e);
  38388. void mouseExit (const MouseEvent& e);
  38389. void mouseWheelMove (const MouseEvent& e, float, float);
  38390. int scaleInt (const int n) const throw();
  38391. MagnifierComponent (const MagnifierComponent&);
  38392. const MagnifierComponent& operator= (const MagnifierComponent&);
  38393. };
  38394. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38395. /********* End of inlined file: juce_MagnifierComponent.h *********/
  38396. #endif
  38397. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38398. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  38399. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38400. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38401. /**
  38402. A component that displays a piano keyboard, whose notes can be clicked on.
  38403. This component will mimic a physical midi keyboard, showing the current state of
  38404. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  38405. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  38406. Another feature is that the computer keyboard can also be used to play notes. By
  38407. default it maps the top two rows of a standard querty keyboard to the notes, but
  38408. these can be remapped if needed. It will only respond to keypresses when it has
  38409. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  38410. The component is also a ChangeBroadcaster, so if you want to be informed when the
  38411. keyboard is scrolled, you can register a ChangeListener for callbacks.
  38412. @see MidiKeyboardState
  38413. */
  38414. class JUCE_API MidiKeyboardComponent : public Component,
  38415. public MidiKeyboardStateListener,
  38416. public ChangeBroadcaster,
  38417. private Timer,
  38418. private AsyncUpdater
  38419. {
  38420. public:
  38421. /** The direction of the keyboard.
  38422. @see setOrientation
  38423. */
  38424. enum Orientation
  38425. {
  38426. horizontalKeyboard,
  38427. verticalKeyboardFacingLeft,
  38428. verticalKeyboardFacingRight,
  38429. };
  38430. /** Creates a MidiKeyboardComponent.
  38431. @param state the midi keyboard model that this component will represent
  38432. @param orientation whether the keyboard is horizonal or vertical
  38433. */
  38434. MidiKeyboardComponent (MidiKeyboardState& state,
  38435. const Orientation orientation);
  38436. /** Destructor. */
  38437. ~MidiKeyboardComponent();
  38438. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  38439. on the component.
  38440. Values are 0 to 1.0, where 1.0 is the heaviest.
  38441. @see setMidiChannel
  38442. */
  38443. void setVelocity (const float velocity);
  38444. /** Changes the midi channel number that will be used for events triggered by clicking
  38445. on the component.
  38446. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  38447. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  38448. Although this is the channel used for outgoing events, the component can display
  38449. incoming events from more than one channel - see setMidiChannelsToDisplay()
  38450. @see setVelocity
  38451. */
  38452. void setMidiChannel (const int midiChannelNumber);
  38453. /** Returns the midi channel that the keyboard is using for midi messages.
  38454. @see setMidiChannel
  38455. */
  38456. int getMidiChannel() const throw() { return midiChannel; }
  38457. /** Sets a mask to indicate which incoming midi channels should be represented by
  38458. key movements.
  38459. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  38460. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  38461. in this mask, the on-screen keys will also go down.
  38462. By default, this mask is set to 0xffff (all channels displayed).
  38463. @see setMidiChannel
  38464. */
  38465. void setMidiChannelsToDisplay (const int midiChannelMask);
  38466. /** Returns the current set of midi channels represented by the component.
  38467. This is the value that was set with setMidiChannelsToDisplay().
  38468. */
  38469. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  38470. /** Changes the width used to draw the white keys. */
  38471. void setKeyWidth (const float widthInPixels);
  38472. /** Returns the width that was set by setKeyWidth(). */
  38473. float getKeyWidth() const throw() { return keyWidth; }
  38474. /** Changes the keyboard's current direction. */
  38475. void setOrientation (const Orientation newOrientation);
  38476. /** Returns the keyboard's current direction. */
  38477. const Orientation getOrientation() const throw() { return orientation; }
  38478. /** Sets the range of midi notes that the keyboard will be limited to.
  38479. By default the range is 0 to 127 (inclusive), but you can limit this if you
  38480. only want a restricted set of the keys to be shown.
  38481. Note that the values here are inclusive and must be between 0 and 127.
  38482. */
  38483. void setAvailableRange (const int lowestNote,
  38484. const int highestNote);
  38485. /** Returns the first note in the available range.
  38486. @see setAvailableRange
  38487. */
  38488. int getRangeStart() const throw() { return rangeStart; }
  38489. /** Returns the last note in the available range.
  38490. @see setAvailableRange
  38491. */
  38492. int getRangeEnd() const throw() { return rangeEnd; }
  38493. /** If the keyboard extends beyond the size of the component, this will scroll
  38494. it to show the given key at the start.
  38495. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  38496. base class to send a callback to any ChangeListeners that have been registered.
  38497. */
  38498. void setLowestVisibleKey (int noteNumber);
  38499. /** Returns the number of the first key shown in the component.
  38500. @see setLowestVisibleKey
  38501. */
  38502. int getLowestVisibleKey() const throw() { return firstKey; }
  38503. /** If set to true, then scroll buttons will appear at either end of the keyboard
  38504. if there are too many notes to fit them all in the component at once.
  38505. */
  38506. void setScrollButtonsVisible (const bool canScroll);
  38507. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38508. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38509. methods.
  38510. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38511. */
  38512. enum ColourIds
  38513. {
  38514. whiteNoteColourId = 0x1005000,
  38515. blackNoteColourId = 0x1005001,
  38516. keySeparatorLineColourId = 0x1005002,
  38517. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  38518. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  38519. textLabelColourId = 0x1005005,
  38520. upDownButtonBackgroundColourId = 0x1005006,
  38521. upDownButtonArrowColourId = 0x1005007
  38522. };
  38523. /** Returns the position within the component of the left-hand edge of a key.
  38524. Depending on the keyboard's orientation, this may be a horizontal or vertical
  38525. distance, in either direction.
  38526. */
  38527. int getKeyStartPosition (const int midiNoteNumber) const;
  38528. /** Deletes all key-mappings.
  38529. @see setKeyPressForNote
  38530. */
  38531. void clearKeyMappings();
  38532. /** Maps a key-press to a given note.
  38533. @param key the key that should trigger the note
  38534. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  38535. be. The actual midi note that gets played will be
  38536. this value + (12 * the current base octave). To change
  38537. the base octave, see setKeyPressBaseOctave()
  38538. */
  38539. void setKeyPressForNote (const KeyPress& key,
  38540. const int midiNoteOffsetFromC);
  38541. /** Removes any key-mappings for a given note.
  38542. For a description of what the note number means, see setKeyPressForNote().
  38543. */
  38544. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  38545. /** Changes the base note above which key-press-triggered notes are played.
  38546. The set of key-mappings that trigger notes can be moved up and down to cover
  38547. the entire scale using this method.
  38548. The value passed in is an octave number between 0 and 10 (inclusive), and
  38549. indicates which C is the base note to which the key-mapped notes are
  38550. relative.
  38551. */
  38552. void setKeyPressBaseOctave (const int newOctaveNumber);
  38553. /** This sets the octave number which is shown as the octave number for middle C.
  38554. This affects only the default implementation of getWhiteNoteText(), which
  38555. passes this octave number to MidiMessage::getMidiNoteName() in order to
  38556. get the note text. See MidiMessage::getMidiNoteName() for more info about
  38557. the parameter.
  38558. By default this value is set to 3.
  38559. @see getOctaveForMiddleC
  38560. */
  38561. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  38562. /** This returns the value set by setOctaveForMiddleC().
  38563. @see setOctaveForMiddleC
  38564. */
  38565. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  38566. /** @internal */
  38567. void paint (Graphics& g);
  38568. /** @internal */
  38569. void resized();
  38570. /** @internal */
  38571. void mouseMove (const MouseEvent& e);
  38572. /** @internal */
  38573. void mouseDrag (const MouseEvent& e);
  38574. /** @internal */
  38575. void mouseDown (const MouseEvent& e);
  38576. /** @internal */
  38577. void mouseUp (const MouseEvent& e);
  38578. /** @internal */
  38579. void mouseEnter (const MouseEvent& e);
  38580. /** @internal */
  38581. void mouseExit (const MouseEvent& e);
  38582. /** @internal */
  38583. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38584. /** @internal */
  38585. void timerCallback();
  38586. /** @internal */
  38587. bool keyStateChanged();
  38588. /** @internal */
  38589. void focusLost (FocusChangeType cause);
  38590. /** @internal */
  38591. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  38592. /** @internal */
  38593. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  38594. /** @internal */
  38595. void handleAsyncUpdate();
  38596. /** @internal */
  38597. void colourChanged();
  38598. juce_UseDebuggingNewOperator
  38599. protected:
  38600. friend class MidiKeyboardUpDownButton;
  38601. /** Draws a white note in the given rectangle.
  38602. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38603. currently pressed down.
  38604. When doing this, be sure to note the keyboard's orientation.
  38605. */
  38606. virtual void drawWhiteNote (int midiNoteNumber,
  38607. Graphics& g,
  38608. int x, int y, int w, int h,
  38609. bool isDown, bool isOver,
  38610. const Colour& lineColour,
  38611. const Colour& textColour);
  38612. /** Draws a black note in the given rectangle.
  38613. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38614. currently pressed down.
  38615. When doing this, be sure to note the keyboard's orientation.
  38616. */
  38617. virtual void drawBlackNote (int midiNoteNumber,
  38618. Graphics& g,
  38619. int x, int y, int w, int h,
  38620. bool isDown, bool isOver,
  38621. const Colour& noteFillColour);
  38622. /** Allows text to be drawn on the white notes.
  38623. By default this is used to label the C in each octave, but could be used for other things.
  38624. @see setOctaveForMiddleC
  38625. */
  38626. virtual const String getWhiteNoteText (const int midiNoteNumber);
  38627. /** Draws the up and down buttons that change the base note. */
  38628. virtual void drawUpDownButton (Graphics& g, int w, int h,
  38629. const bool isMouseOver,
  38630. const bool isButtonPressed,
  38631. const bool movesOctavesUp);
  38632. /** Callback when the mouse is clicked on a key.
  38633. You could use this to do things like handle right-clicks on keys, etc.
  38634. Return true if you want the click to trigger the note, or false if you
  38635. want to handle it yourself and not have the note played.
  38636. @see mouseDraggedToKey
  38637. */
  38638. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  38639. /** Callback when the mouse is dragged from one key onto another.
  38640. @see mouseDownOnKey
  38641. */
  38642. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  38643. /** Calculates the positon of a given midi-note.
  38644. This can be overridden to create layouts with custom key-widths.
  38645. @param midiNoteNumber the note to find
  38646. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  38647. @param x the x position of the left-hand edge of the key (this method
  38648. always works in terms of a horizontal keyboard)
  38649. @param w the width of the key
  38650. */
  38651. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  38652. int& x, int& w) const;
  38653. private:
  38654. MidiKeyboardState& state;
  38655. int xOffset, blackNoteLength;
  38656. float keyWidth;
  38657. Orientation orientation;
  38658. int midiChannel, midiInChannelMask;
  38659. float velocity;
  38660. int noteUnderMouse, mouseDownNote;
  38661. BitArray keysPressed, keysCurrentlyDrawnDown;
  38662. int rangeStart, rangeEnd, firstKey;
  38663. bool canScroll, mouseDragging;
  38664. Button* scrollDown;
  38665. Button* scrollUp;
  38666. Array <KeyPress> keyPresses;
  38667. Array <int> keyPressNotes;
  38668. int keyMappingOctave;
  38669. int octaveNumForMiddleC;
  38670. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  38671. int xyToNote (int x, int y);
  38672. int remappedXYToNote (int x, int y) const;
  38673. void resetAnyKeysInUse();
  38674. void updateNoteUnderMouse (int x, int y);
  38675. void repaintNote (const int midiNoteNumber);
  38676. MidiKeyboardComponent (const MidiKeyboardComponent&);
  38677. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  38678. };
  38679. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38680. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  38681. #endif
  38682. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38683. /********* Start of inlined file: juce_NSViewComponent.h *********/
  38684. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38685. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38686. #if ! DOXYGEN
  38687. class NSViewComponentInternal;
  38688. #endif
  38689. #if JUCE_MAC || DOXYGEN
  38690. /**
  38691. A Mac-specific class that can create and embed an NSView inside itself.
  38692. To use it, create one of these, put it in place and make sure it's visible in a
  38693. window, then use setView() to assign an NSView to it. The view will then be
  38694. moved and resized to follow the movements of this component.
  38695. Of course, since the view is a native object, it'll obliterate any
  38696. juce components that may overlap this component, but that's life.
  38697. */
  38698. class JUCE_API NSViewComponent : public Component
  38699. {
  38700. public:
  38701. /** Create an initially-empty container. */
  38702. NSViewComponent();
  38703. /** Destructor. */
  38704. ~NSViewComponent();
  38705. /** Assigns an NSView to this peer.
  38706. The view will be retained and released by this component for as long as
  38707. it is needed. To remove the current view, just call setView (0).
  38708. Note: a void* is used here to avoid including the cocoa headers as
  38709. part of the juce.h, but the method expects an NSView*.
  38710. */
  38711. void setView (void* nsView);
  38712. /** Returns the current NSView.
  38713. Note: a void* is returned here to avoid including the cocoa headers as
  38714. a requirement of juce.h, so you should just cast the object to an NSView*.
  38715. */
  38716. void* getView() const;
  38717. /** @internal */
  38718. void paint (Graphics& g);
  38719. juce_UseDebuggingNewOperator
  38720. private:
  38721. friend class NSViewComponentInternal;
  38722. NSViewComponentInternal* info;
  38723. NSViewComponent (const NSViewComponent&);
  38724. const NSViewComponent& operator= (const NSViewComponent&);
  38725. };
  38726. #endif
  38727. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  38728. /********* End of inlined file: juce_NSViewComponent.h *********/
  38729. #endif
  38730. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38731. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  38732. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38733. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38734. // this is used to disable OpenGL, and is defined in juce_Config.h
  38735. #if JUCE_OPENGL || DOXYGEN
  38736. class OpenGLComponentWatcher;
  38737. /**
  38738. Represents the various properties of an OpenGL bitmap format.
  38739. @see OpenGLComponent::setPixelFormat
  38740. */
  38741. struct OpenGLPixelFormat
  38742. {
  38743. /** Creates an OpenGLPixelFormat.
  38744. The default constructor just initialises the object as a simple 8-bit
  38745. RGBA format.
  38746. */
  38747. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  38748. const int alphaBits = 8,
  38749. const int depthBufferBits = 16,
  38750. const int stencilBufferBits = 0) throw();
  38751. int redBits; /**< The number of bits per pixel to use for the red channel. */
  38752. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  38753. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  38754. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  38755. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  38756. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  38757. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  38758. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  38759. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  38760. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  38761. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  38762. /** Returns a list of all the pixel formats that can be used in this system.
  38763. A reference component is needed in case there are multiple screens with different
  38764. capabilities - in which case, the one that the component is on will be used.
  38765. */
  38766. static void getAvailablePixelFormats (Component* component,
  38767. OwnedArray <OpenGLPixelFormat>& results);
  38768. bool operator== (const OpenGLPixelFormat&) const throw();
  38769. juce_UseDebuggingNewOperator
  38770. };
  38771. /**
  38772. A base class for types of OpenGL context.
  38773. An OpenGLComponent will supply its own context for drawing in its window.
  38774. */
  38775. class OpenGLContext
  38776. {
  38777. public:
  38778. /** Destructor. */
  38779. virtual ~OpenGLContext();
  38780. /** Makes this context the currently active one. */
  38781. virtual bool makeActive() const throw() = 0;
  38782. /** If this context is currently active, it is disactivated. */
  38783. virtual bool makeInactive() const throw() = 0;
  38784. /** Returns true if this context is currently active. */
  38785. virtual bool isActive() const throw() = 0;
  38786. /** Swaps the buffers (if the context can do this). */
  38787. virtual void swapBuffers() = 0;
  38788. /** Sets whether the context checks the vertical sync before swapping.
  38789. The value is the number of frames to allow between buffer-swapping. This is
  38790. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  38791. and greater numbers indicate that it should swap less often.
  38792. Returns true if it sets the value successfully.
  38793. */
  38794. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  38795. /** Returns the current swap-sync interval.
  38796. See setSwapInterval() for info about the value returned.
  38797. */
  38798. virtual int getSwapInterval() const = 0;
  38799. /** Returns the pixel format being used by this context. */
  38800. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  38801. /** For windowed contexts, this moves the context within the bounds of
  38802. its parent window.
  38803. */
  38804. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  38805. /** For windowed contexts, this triggers a repaint of the window.
  38806. (Not relevent on all platforms).
  38807. */
  38808. virtual void repaint() = 0;
  38809. /** Returns an OS-dependent handle to the raw GL context.
  38810. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  38811. a GLXContext.
  38812. */
  38813. virtual void* getRawContext() const throw() = 0;
  38814. /** This tries to create a context that can be used for drawing into the
  38815. area occupied by the specified component.
  38816. Note that you probably shouldn't use this method directly unless you know what
  38817. you're doing - the OpenGLComponent calls this and manages the context for you.
  38818. */
  38819. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  38820. const OpenGLPixelFormat& pixelFormat,
  38821. const OpenGLContext* const contextToShareWith);
  38822. /** Returns the context that's currently in active use by the calling thread.
  38823. Returns 0 if there isn't an active context.
  38824. */
  38825. static OpenGLContext* getCurrentContext();
  38826. juce_UseDebuggingNewOperator
  38827. protected:
  38828. OpenGLContext() throw();
  38829. };
  38830. /**
  38831. A component that contains an OpenGL canvas.
  38832. Override this, add it to whatever component you want to, and use the renderOpenGL()
  38833. method to draw its contents.
  38834. */
  38835. class JUCE_API OpenGLComponent : public Component
  38836. {
  38837. public:
  38838. /** Creates an OpenGLComponent.
  38839. */
  38840. OpenGLComponent();
  38841. /** Destructor. */
  38842. ~OpenGLComponent();
  38843. /** Changes the pixel format used by this component.
  38844. @see OpenGLPixelFormat::getAvailablePixelFormats()
  38845. */
  38846. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  38847. /** Returns the pixel format that this component is currently using. */
  38848. const OpenGLPixelFormat getPixelFormat() const;
  38849. /** Specifies an OpenGL context which should be shared with the one that this
  38850. component is using.
  38851. This is an OpenGL feature that lets two contexts share their texture data.
  38852. Note that this pointer is stored by the component, and when the component
  38853. needs to recreate its internal context for some reason, the same context
  38854. will be used again to share lists. So if you pass a context in here,
  38855. don't delete the context while this component is still using it! You can
  38856. call shareWith (0) to stop this component from sharing with it.
  38857. */
  38858. void shareWith (OpenGLContext* contextToShareListsWith);
  38859. /** Returns the context that this component is sharing with.
  38860. @see shareWith
  38861. */
  38862. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  38863. /** Flips the openGL buffers over. */
  38864. void swapBuffers();
  38865. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  38866. When this is called, makeCurrentContextActive() will already have been called
  38867. for you, so you just need to draw.
  38868. */
  38869. virtual void renderOpenGL() = 0;
  38870. /** This method is called when the component creates a new OpenGL context.
  38871. A new context may be created when the component is first used, or when it
  38872. is moved to a different window, or when the window is hidden and re-shown,
  38873. etc.
  38874. You can use this callback as an opportunity to set up things like textures
  38875. that your context needs.
  38876. New contexts are created on-demand by the makeCurrentContextActive() method - so
  38877. if the context is deleted, e.g. by changing the pixel format or window, no context
  38878. will be created until the next call to makeCurrentContextActive(), which will
  38879. synchronously create one and call this method. This means that if you're using
  38880. a non-GUI thread for rendering, you can make sure this method is be called by
  38881. your renderer thread.
  38882. When this callback happens, the context will already have been made current
  38883. using the makeCurrentContextActive() method, so there's no need to call it
  38884. again in your code.
  38885. */
  38886. virtual void newOpenGLContextCreated() = 0;
  38887. /** Returns the context that will draw into this component.
  38888. This may return 0 if the component is currently invisible or hasn't currently
  38889. got a context. The context object can be deleted and a new one created during
  38890. the lifetime of this component, and there may be times when it doesn't have one.
  38891. @see newOpenGLContextCreated()
  38892. */
  38893. OpenGLContext* getCurrentContext() const throw() { return context; }
  38894. /** Makes this component the current openGL context.
  38895. You might want to use this in things like your resize() method, before calling
  38896. GL commands.
  38897. If this returns false, then the context isn't active, so you should avoid
  38898. making any calls.
  38899. This call may actually create a context if one isn't currently initialised. If
  38900. it does this, it will also synchronously call the newOpenGLContextCreated()
  38901. method to let you initialise it as necessary.
  38902. @see OpenGLContext::makeActive
  38903. */
  38904. bool makeCurrentContextActive();
  38905. /** Stops the current component being the active OpenGL context.
  38906. This is the opposite of makeCurrentContextActive()
  38907. @see OpenGLContext::makeInactive
  38908. */
  38909. void makeCurrentContextInactive();
  38910. /** Returns true if this component is the active openGL context for the
  38911. current thread.
  38912. @see OpenGLContext::isActive
  38913. */
  38914. bool isActiveContext() const throw();
  38915. /** Calls the rendering callback, and swaps the buffers afterwards.
  38916. This is called automatically by paint() when the component needs to be rendered.
  38917. It can be overridden if you need to decouple the rendering from the paint callback
  38918. and render with a custom thread.
  38919. Returns true if the operation succeeded.
  38920. */
  38921. virtual bool renderAndSwapBuffers();
  38922. /** This returns a critical section that can be used to lock the current context.
  38923. Because the context that is used by this component can change, e.g. when the
  38924. component is shown or hidden, then if you're rendering to it on a background
  38925. thread, this allows you to lock the context for the duration of your rendering
  38926. routine.
  38927. */
  38928. CriticalSection& getContextLock() throw() { return contextLock; }
  38929. /** @internal */
  38930. void paint (Graphics& g);
  38931. /** Returns the native handle of an embedded heavyweight window, if there is one.
  38932. E.g. On windows, this will return the HWND of the sub-window containing
  38933. the opengl context, on the mac it'll be the NSOpenGLView.
  38934. */
  38935. void* getNativeWindowHandle() const;
  38936. juce_UseDebuggingNewOperator
  38937. private:
  38938. friend class OpenGLComponentWatcher;
  38939. OpenGLComponentWatcher* componentWatcher;
  38940. OpenGLContext* context;
  38941. OpenGLContext* contextToShareListsWith;
  38942. CriticalSection contextLock;
  38943. OpenGLPixelFormat preferredPixelFormat;
  38944. bool needToUpdateViewport;
  38945. void deleteContext();
  38946. void updateContextPosition();
  38947. void internalRepaint (int x, int y, int w, int h);
  38948. OpenGLComponent (const OpenGLComponent&);
  38949. const OpenGLComponent& operator= (const OpenGLComponent&);
  38950. };
  38951. #endif
  38952. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  38953. /********* End of inlined file: juce_OpenGLComponent.h *********/
  38954. #endif
  38955. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38956. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  38957. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38958. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  38959. /**
  38960. A component with a set of buttons at the top for changing between pages of
  38961. preferences.
  38962. This is just a handy way of writing a Mac-style preferences panel where you
  38963. have a row of buttons along the top for the different preference categories,
  38964. each button having an icon above its name. Clicking these will show an
  38965. appropriate prefs page below it.
  38966. You can either put one of these inside your own component, or just use the
  38967. showInDialogBox() method to show it in a window and run it modally.
  38968. To use it, just add a set of named pages with the addSettingsPage() method,
  38969. and implement the createComponentForPage() method to create suitable components
  38970. for each of these pages.
  38971. */
  38972. class JUCE_API PreferencesPanel : public Component,
  38973. private ButtonListener
  38974. {
  38975. public:
  38976. /** Creates an empty panel.
  38977. Use addSettingsPage() to add some pages to it in your constructor.
  38978. */
  38979. PreferencesPanel();
  38980. /** Destructor. */
  38981. ~PreferencesPanel();
  38982. /** Creates a page using a set of drawables to define the page's icon.
  38983. Note that the other version of this method is much easier if you're using
  38984. an image instead of a custom drawable.
  38985. @param pageTitle the name of this preferences page - you'll need to
  38986. make sure your createComponentForPage() method creates
  38987. a suitable component when it is passed this name
  38988. @param normalIcon the drawable to display in the page's button normally
  38989. @param overIcon the drawable to display in the page's button when the mouse is over
  38990. @param downIcon the drawable to display in the page's button when the button is down
  38991. @see DrawableButton
  38992. */
  38993. void addSettingsPage (const String& pageTitle,
  38994. const Drawable* normalIcon,
  38995. const Drawable* overIcon,
  38996. const Drawable* downIcon);
  38997. /** Creates a page using a set of drawables to define the page's icon.
  38998. The other version of this method gives you more control over the icon, but this
  38999. one is much easier if you're just loading it from a file.
  39000. @param pageTitle the name of this preferences page - you'll need to
  39001. make sure your createComponentForPage() method creates
  39002. a suitable component when it is passed this name
  39003. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  39004. For this to look good, you'll probably want to use a nice
  39005. transparent png file.
  39006. @param imageDataSize the size of the image data, in bytes
  39007. */
  39008. void addSettingsPage (const String& pageTitle,
  39009. const char* imageData,
  39010. const int imageDataSize);
  39011. /** Utility method to display this panel in a DialogWindow.
  39012. Calling this will create a DialogWindow containing this panel with the
  39013. given size and title, and will run it modally, returning when the user
  39014. closes the dialog box.
  39015. */
  39016. void showInDialogBox (const String& dialogtitle,
  39017. int dialogWidth,
  39018. int dialogHeight,
  39019. const Colour& backgroundColour = Colours::white);
  39020. /** Subclasses must override this to return a component for each preferences page.
  39021. The subclass should return a pointer to a new component representing the named
  39022. page, which the panel will then display.
  39023. The panel will delete the component later when the user goes to another page
  39024. or deletes the panel.
  39025. */
  39026. virtual Component* createComponentForPage (const String& pageName) = 0;
  39027. /** Changes the current page being displayed. */
  39028. void setCurrentPage (const String& pageName);
  39029. /** @internal */
  39030. void resized();
  39031. /** @internal */
  39032. void paint (Graphics& g);
  39033. /** @internal */
  39034. void buttonClicked (Button* button);
  39035. juce_UseDebuggingNewOperator
  39036. private:
  39037. String currentPageName;
  39038. Component* currentPage;
  39039. int buttonSize;
  39040. PreferencesPanel (const PreferencesPanel&);
  39041. const PreferencesPanel& operator= (const PreferencesPanel&);
  39042. };
  39043. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39044. /********* End of inlined file: juce_PreferencesPanel.h *********/
  39045. #endif
  39046. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39047. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  39048. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39049. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39050. // this is used to disable QuickTime, and is defined in juce_Config.h
  39051. #if JUCE_QUICKTIME || DOXYGEN
  39052. #if JUCE_WIN32
  39053. typedef ActiveXControlComponent QTCompBaseClass;
  39054. #else
  39055. typedef NSViewComponent QTCompBaseClass;
  39056. #endif
  39057. /**
  39058. A window that can play back a QuickTime movie.
  39059. */
  39060. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  39061. {
  39062. public:
  39063. /** Creates a QuickTimeMovieComponent, initially blank.
  39064. Use the loadMovie() method to load a movie once you've added the
  39065. component to a window, (or put it on the desktop as a heavyweight window).
  39066. Loading a movie when the component isn't visible can cause problems, as
  39067. QuickTime needs a window handle to initialise properly.
  39068. */
  39069. QuickTimeMovieComponent();
  39070. /** Destructor. */
  39071. ~QuickTimeMovieComponent();
  39072. /** Returns true if QT is installed and working on this machine.
  39073. */
  39074. static bool isQuickTimeAvailable() throw();
  39075. /** Tries to load a QuickTime movie into the player.
  39076. It's best to call this function once you've added the component to a window,
  39077. (or put it on the desktop as a heavyweight window). Loading a movie when the
  39078. component isn't visible can cause problems, because QuickTime needs a window
  39079. handle to do its stuff.
  39080. @param movieFile the .mov file to open
  39081. @param isControllerVisible whether to show a controller bar at the bottom
  39082. @returns true if the movie opens successfully
  39083. */
  39084. bool loadMovie (const File& movieFile,
  39085. const bool isControllerVisible);
  39086. bool loadMovie (InputStream* movieStream,
  39087. const bool isControllerVisible);
  39088. /** Closes the movie, if one is open. */
  39089. void closeMovie();
  39090. /** Returns the movie file that is currently open.
  39091. If there isn't one, this returns File::nonexistent
  39092. */
  39093. const File getCurrentMovieFile() const;
  39094. /** Returns true if there's currently a movie open. */
  39095. bool isMovieOpen() const;
  39096. /** Returns the length of the movie, in seconds. */
  39097. double getMovieDuration() const;
  39098. /** Returns the movie's natural size, in pixels.
  39099. You can use this to resize the component to show the movie at its preferred
  39100. scale.
  39101. If no movie is loaded, the size returned will be 0 x 0.
  39102. */
  39103. void getMovieNormalSize (int& width, int& height) const;
  39104. /** This will position the component within a given area, keeping its aspect
  39105. ratio correct according to the movie's normal size.
  39106. The component will be made as large as it can go within the space, and will
  39107. be aligned according to the justification value if this means there are gaps at
  39108. the top or sides.
  39109. */
  39110. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  39111. const RectanglePlacement& placement);
  39112. /** Starts the movie playing. */
  39113. void play();
  39114. /** Stops the movie playing. */
  39115. void stop();
  39116. /** Returns true if the movie is currently playing. */
  39117. bool isPlaying() const;
  39118. /** Moves the movie's position back to the start. */
  39119. void goToStart();
  39120. /** Sets the movie's position to a given time. */
  39121. void setPosition (const double seconds);
  39122. /** Returns the current play position of the movie. */
  39123. double getPosition() const;
  39124. /** Changes the movie playback rate.
  39125. A value of 1 is normal speed, greater values play it proportionately faster,
  39126. smaller values play it slower.
  39127. */
  39128. void setSpeed (const float newSpeed);
  39129. /** Changes the movie's playback volume.
  39130. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39131. */
  39132. void setMovieVolume (const float newVolume);
  39133. /** Returns the movie's playback volume.
  39134. @returns the volume in the range 0 (silent) to 1.0 (full)
  39135. */
  39136. float getMovieVolume() const;
  39137. /** Tells the movie whether it should loop. */
  39138. void setLooping (const bool shouldLoop);
  39139. /** Returns true if the movie is currently looping.
  39140. @see setLooping
  39141. */
  39142. bool isLooping() const;
  39143. /** True if the native QuickTime controller bar is shown in the window.
  39144. @see loadMovie
  39145. */
  39146. bool isControllerVisible() const;
  39147. /** @internal */
  39148. void paint (Graphics& g);
  39149. juce_UseDebuggingNewOperator
  39150. private:
  39151. File movieFile;
  39152. bool movieLoaded, controllerVisible, looping;
  39153. #if JUCE_WIN32
  39154. /** @internal */
  39155. void parentHierarchyChanged();
  39156. /** @internal */
  39157. void visibilityChanged();
  39158. void createControlIfNeeded();
  39159. bool isControlCreated() const;
  39160. void* internal;
  39161. #else
  39162. void* movie;
  39163. #endif
  39164. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39165. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39166. };
  39167. #endif
  39168. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39169. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39170. #endif
  39171. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39172. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  39173. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39174. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39175. #if JUCE_WIN32 || JUCE_LINUX
  39176. /**
  39177. On Windows only, this component sits in the taskbar tray as a small icon.
  39178. To use it, just create one of these components, but don't attempt to make it
  39179. visible, add it to a parent, or put it on the desktop.
  39180. You can then call setIconImage() to create an icon for it in the taskbar.
  39181. To change the icon's tooltip, you can use setIconTooltip().
  39182. To respond to mouse-events, you can override the normal mouseDown(),
  39183. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  39184. position will not be valid, you can use this to respond to clicks. Traditionally
  39185. you'd use a left-click to show your application's window, and a right-click
  39186. to show a pop-up menu.
  39187. */
  39188. class JUCE_API SystemTrayIconComponent : public Component
  39189. {
  39190. public:
  39191. SystemTrayIconComponent();
  39192. /** Destructor. */
  39193. ~SystemTrayIconComponent();
  39194. /** Changes the image shown in the taskbar.
  39195. */
  39196. void setIconImage (const Image& newImage);
  39197. /** Changes the tooltip that Windows shows above the icon. */
  39198. void setIconTooltip (const String& tooltip);
  39199. #if JUCE_LINUX
  39200. /** @internal */
  39201. void paint (Graphics& g);
  39202. #endif
  39203. juce_UseDebuggingNewOperator
  39204. private:
  39205. SystemTrayIconComponent (const SystemTrayIconComponent&);
  39206. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  39207. };
  39208. #endif
  39209. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39210. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  39211. #endif
  39212. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39213. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  39214. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39215. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39216. #if JUCE_WEB_BROWSER
  39217. class WebBrowserComponentInternal;
  39218. /**
  39219. A component that displays an embedded web browser.
  39220. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  39221. Windows, probably IE.
  39222. */
  39223. class WebBrowserComponent : public Component
  39224. {
  39225. public:
  39226. /** Creates a WebBrowserComponent.
  39227. Once it's created and visible, send the browser to a URL using goToURL().
  39228. */
  39229. WebBrowserComponent();
  39230. /** Destructor. */
  39231. ~WebBrowserComponent();
  39232. /** Sends the browser to a particular URL.
  39233. @param url the URL to go to.
  39234. @param headers an optional set of parameters to put in the HTTP header. If
  39235. you supply this, it should be a set of string in the form
  39236. "HeaderKey: HeaderValue"
  39237. @param postData an optional block of data that will be attached to the HTTP
  39238. POST request
  39239. */
  39240. void goToURL (const String& url,
  39241. const StringArray* headers = 0,
  39242. const MemoryBlock* postData = 0);
  39243. /** Stops the current page loading.
  39244. */
  39245. void stop();
  39246. /** Sends the browser back one page.
  39247. */
  39248. void goBack();
  39249. /** Sends the browser forward one page.
  39250. */
  39251. void goForward();
  39252. /** This callback is called when the browser is about to navigate
  39253. to a new location.
  39254. You can override this method to perform some action when the user
  39255. tries to go to a particular URL. To allow the operation to carry on,
  39256. return true, or return false to stop the navigation happening.
  39257. */
  39258. virtual bool pageAboutToLoad (const String& newURL);
  39259. /** @internal */
  39260. void paint (Graphics& g);
  39261. /** @internal */
  39262. void resized();
  39263. /** @internal */
  39264. void parentHierarchyChanged();
  39265. /** @internal */
  39266. void visibilityChanged();
  39267. juce_UseDebuggingNewOperator
  39268. private:
  39269. WebBrowserComponentInternal* browser;
  39270. bool blankPageShown;
  39271. String lastURL;
  39272. StringArray lastHeaders;
  39273. MemoryBlock lastPostData;
  39274. void reloadLastURL();
  39275. void checkWindowAssociation();
  39276. WebBrowserComponent (const WebBrowserComponent&);
  39277. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  39278. };
  39279. #endif
  39280. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39281. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  39282. #endif
  39283. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39284. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39285. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39286. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39287. class ToggleButton;
  39288. class TextButton;
  39289. class AlertWindow;
  39290. class TextLayout;
  39291. class ScrollBar;
  39292. class BubbleComponent;
  39293. class ComboBox;
  39294. class Button;
  39295. class FilenameComponent;
  39296. class DocumentWindow;
  39297. class ResizableWindow;
  39298. class GroupComponent;
  39299. class MenuBarComponent;
  39300. class DropShadower;
  39301. class GlyphArrangement;
  39302. class PropertyComponent;
  39303. class TableHeaderComponent;
  39304. class Toolbar;
  39305. class ToolbarItemComponent;
  39306. class PopupMenu;
  39307. class ProgressBar;
  39308. class FileBrowserComponent;
  39309. class DirectoryContentsDisplayComponent;
  39310. class FilePreviewComponent;
  39311. /**
  39312. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39313. can be used to apply different 'skins' to the application.
  39314. */
  39315. class JUCE_API LookAndFeel
  39316. {
  39317. public:
  39318. /** Creates the default JUCE look and feel. */
  39319. LookAndFeel();
  39320. /** Destructor. */
  39321. virtual ~LookAndFeel();
  39322. /** Returns the current default look-and-feel for a component to use when it
  39323. hasn't got one explicitly set.
  39324. @see setDefaultLookAndFeel
  39325. */
  39326. static LookAndFeel& getDefaultLookAndFeel() throw();
  39327. /** Changes the default look-and-feel.
  39328. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39329. set to 0, it will revert to using the default one. The
  39330. object passed-in must be deleted by the caller when
  39331. it's no longer needed.
  39332. @see getDefaultLookAndFeel
  39333. */
  39334. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39335. /** Looks for a colour that has been registered with the given colour ID number.
  39336. If a colour has been set for this ID number using setColour(), then it is
  39337. returned. If none has been set, it will just return Colours::black.
  39338. The colour IDs for various purposes are stored as enums in the components that
  39339. they are relevent to - for an example, see Slider::ColourIds,
  39340. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39341. If you're looking up a colour for use in drawing a component, it's usually
  39342. best not to call this directly, but to use the Component::findColour() method
  39343. instead. That will first check whether a suitable colour has been registered
  39344. directly with the component, and will fall-back on calling the component's
  39345. LookAndFeel's findColour() method if none is found.
  39346. @see setColour, Component::findColour, Component::setColour
  39347. */
  39348. const Colour findColour (const int colourId) const throw();
  39349. /** Registers a colour to be used for a particular purpose.
  39350. For more details, see the comments for findColour().
  39351. @see findColour, Component::findColour, Component::setColour
  39352. */
  39353. void setColour (const int colourId, const Colour& colour) throw();
  39354. /** Draws the lozenge-shaped background for a standard button. */
  39355. virtual void drawButtonBackground (Graphics& g,
  39356. Button& button,
  39357. const Colour& backgroundColour,
  39358. bool isMouseOverButton,
  39359. bool isButtonDown);
  39360. /** Draws the text for a TextButton. */
  39361. virtual void drawButtonText (Graphics& g,
  39362. TextButton& button,
  39363. bool isMouseOverButton,
  39364. bool isButtonDown);
  39365. /** Draws the contents of a standard ToggleButton. */
  39366. virtual void drawToggleButton (Graphics& g,
  39367. ToggleButton& button,
  39368. bool isMouseOverButton,
  39369. bool isButtonDown);
  39370. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39371. virtual void drawTickBox (Graphics& g,
  39372. Component& component,
  39373. int x, int y, int w, int h,
  39374. const bool ticked,
  39375. const bool isEnabled,
  39376. const bool isMouseOverButton,
  39377. const bool isButtonDown);
  39378. /** Draws the contents of a message box.
  39379. */
  39380. virtual void drawAlertBox (Graphics& g,
  39381. AlertWindow& alert,
  39382. const Rectangle& textArea,
  39383. TextLayout& textLayout);
  39384. virtual int getAlertBoxWindowFlags();
  39385. virtual int getAlertWindowButtonHeight();
  39386. virtual const Font getAlertWindowFont();
  39387. /** Draws a progress bar.
  39388. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39389. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39390. isn't known). It can use the current time as a basis for playing an animation.
  39391. (Used by progress bars in AlertWindow).
  39392. */
  39393. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39394. int width, int height,
  39395. double progress, const String& textToShow);
  39396. /** Draws one of the buttons on a scrollbar.
  39397. @param g the context to draw into
  39398. @param scrollbar the bar itself
  39399. @param width the width of the button
  39400. @param height the height of the button
  39401. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39402. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39403. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39404. @param isButtonDown whether the mouse button's held down
  39405. */
  39406. virtual void drawScrollbarButton (Graphics& g,
  39407. ScrollBar& scrollbar,
  39408. int width, int height,
  39409. int buttonDirection,
  39410. bool isScrollbarVertical,
  39411. bool isMouseOverButton,
  39412. bool isButtonDown);
  39413. /** Draws the thumb area of a scrollbar.
  39414. @param g the context to draw into
  39415. @param scrollbar the bar itself
  39416. @param x the x position of the left edge of the thumb area to draw in
  39417. @param y the y position of the top edge of the thumb area to draw in
  39418. @param width the width of the thumb area to draw in
  39419. @param height the height of the thumb area to draw in
  39420. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39421. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39422. thumb, or its x position for horizontal bars
  39423. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39424. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39425. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39426. currently dragging the thumb
  39427. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39428. */
  39429. virtual void drawScrollbar (Graphics& g,
  39430. ScrollBar& scrollbar,
  39431. int x, int y,
  39432. int width, int height,
  39433. bool isScrollbarVertical,
  39434. int thumbStartPosition,
  39435. int thumbSize,
  39436. bool isMouseOver,
  39437. bool isMouseDown);
  39438. /** Returns the component effect to use for a scrollbar */
  39439. virtual ImageEffectFilter* getScrollbarEffect();
  39440. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39441. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39442. /** Returns the default thickness to use for a scrollbar. */
  39443. virtual int getDefaultScrollbarWidth();
  39444. /** Returns the length in pixels to use for a scrollbar button. */
  39445. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39446. /** Returns a tick shape for use in yes/no boxes, etc. */
  39447. virtual const Path getTickShape (const float height);
  39448. /** Returns a cross shape for use in yes/no boxes, etc. */
  39449. virtual const Path getCrossShape (const float height);
  39450. /** Draws the + or - box in a treeview. */
  39451. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus);
  39452. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39453. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39454. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39455. virtual Image* getDefaultFolderImage();
  39456. virtual Image* getDefaultDocumentFileImage();
  39457. virtual void createFileChooserHeaderText (const String& title,
  39458. const String& instructions,
  39459. GlyphArrangement& destArrangement,
  39460. int width);
  39461. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39462. const String& filename, Image* icon,
  39463. const String& fileSizeDescription,
  39464. const String& fileTimeDescription,
  39465. const bool isDirectory,
  39466. const bool isItemSelected,
  39467. const int itemIndex);
  39468. virtual Button* createFileBrowserGoUpButton();
  39469. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39470. DirectoryContentsDisplayComponent* fileListComponent,
  39471. FilePreviewComponent* previewComp,
  39472. ComboBox* currentPathBox,
  39473. TextEditor* filenameBox,
  39474. Button* goUpButton);
  39475. virtual void drawBubble (Graphics& g,
  39476. float tipX, float tipY,
  39477. float boxX, float boxY, float boxW, float boxH);
  39478. /** Fills the background of a popup menu component. */
  39479. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39480. /** Draws one of the items in a popup menu. */
  39481. virtual void drawPopupMenuItem (Graphics& g,
  39482. int width, int height,
  39483. const bool isSeparator,
  39484. const bool isActive,
  39485. const bool isHighlighted,
  39486. const bool isTicked,
  39487. const bool hasSubMenu,
  39488. const String& text,
  39489. const String& shortcutKeyText,
  39490. Image* image,
  39491. const Colour* const textColour);
  39492. /** Returns the size and style of font to use in popup menus. */
  39493. virtual const Font getPopupMenuFont();
  39494. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  39495. int width, int height,
  39496. bool isScrollUpArrow);
  39497. /** Finds the best size for an item in a popup menu. */
  39498. virtual void getIdealPopupMenuItemSize (const String& text,
  39499. const bool isSeparator,
  39500. int standardMenuItemHeight,
  39501. int& idealWidth,
  39502. int& idealHeight);
  39503. virtual int getMenuWindowFlags();
  39504. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39505. bool isMouseOverBar,
  39506. MenuBarComponent& menuBar);
  39507. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39508. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39509. virtual void drawMenuBarItem (Graphics& g,
  39510. int width, int height,
  39511. int itemIndex,
  39512. const String& itemText,
  39513. bool isMouseOverItem,
  39514. bool isMenuOpen,
  39515. bool isMouseOverBar,
  39516. MenuBarComponent& menuBar);
  39517. virtual void drawComboBox (Graphics& g, int width, int height,
  39518. const bool isButtonDown,
  39519. int buttonX, int buttonY,
  39520. int buttonW, int buttonH,
  39521. ComboBox& box);
  39522. virtual const Font getComboBoxFont (ComboBox& box);
  39523. virtual Label* createComboBoxTextBox (ComboBox& box);
  39524. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  39525. virtual void drawLabel (Graphics& g, Label& label);
  39526. virtual void drawLinearSlider (Graphics& g,
  39527. int x, int y,
  39528. int width, int height,
  39529. float sliderPos,
  39530. float minSliderPos,
  39531. float maxSliderPos,
  39532. const Slider::SliderStyle style,
  39533. Slider& slider);
  39534. virtual void drawLinearSliderBackground (Graphics& g,
  39535. int x, int y,
  39536. int width, int height,
  39537. float sliderPos,
  39538. float minSliderPos,
  39539. float maxSliderPos,
  39540. const Slider::SliderStyle style,
  39541. Slider& slider);
  39542. virtual void drawLinearSliderThumb (Graphics& g,
  39543. int x, int y,
  39544. int width, int height,
  39545. float sliderPos,
  39546. float minSliderPos,
  39547. float maxSliderPos,
  39548. const Slider::SliderStyle style,
  39549. Slider& slider);
  39550. virtual int getSliderThumbRadius (Slider& slider);
  39551. virtual void drawRotarySlider (Graphics& g,
  39552. int x, int y,
  39553. int width, int height,
  39554. float sliderPosProportional,
  39555. const float rotaryStartAngle,
  39556. const float rotaryEndAngle,
  39557. Slider& slider);
  39558. virtual Button* createSliderButton (const bool isIncrement);
  39559. virtual Label* createSliderTextBox (Slider& slider);
  39560. virtual ImageEffectFilter* getSliderEffect();
  39561. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  39562. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  39563. virtual Button* createFilenameComponentBrowseButton (const String& text);
  39564. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  39565. ComboBox* filenameBox, Button* browseButton);
  39566. virtual void drawCornerResizer (Graphics& g,
  39567. int w, int h,
  39568. bool isMouseOver,
  39569. bool isMouseDragging);
  39570. virtual void drawResizableFrame (Graphics& g,
  39571. int w, int h,
  39572. const BorderSize& borders);
  39573. virtual void drawResizableWindowBorder (Graphics& g,
  39574. int w, int h,
  39575. const BorderSize& border,
  39576. ResizableWindow& window);
  39577. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  39578. Graphics& g, int w, int h,
  39579. int titleSpaceX, int titleSpaceW,
  39580. const Image* icon,
  39581. bool drawTitleTextOnLeft);
  39582. virtual Button* createDocumentWindowButton (int buttonType);
  39583. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39584. int titleBarX, int titleBarY,
  39585. int titleBarW, int titleBarH,
  39586. Button* minimiseButton,
  39587. Button* maximiseButton,
  39588. Button* closeButton,
  39589. bool positionTitleBarButtonsOnLeft);
  39590. virtual int getDefaultMenuBarHeight();
  39591. virtual DropShadower* createDropShadowerForComponent (Component* component);
  39592. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  39593. int w, int h,
  39594. bool isVerticalBar,
  39595. bool isMouseOver,
  39596. bool isMouseDragging);
  39597. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  39598. const String& text,
  39599. const Justification& position,
  39600. GroupComponent& group);
  39601. virtual void createTabButtonShape (Path& p,
  39602. int width, int height,
  39603. int tabIndex,
  39604. const String& text,
  39605. Button& button,
  39606. TabbedButtonBar::Orientation orientation,
  39607. const bool isMouseOver,
  39608. const bool isMouseDown,
  39609. const bool isFrontTab);
  39610. virtual void fillTabButtonShape (Graphics& g,
  39611. const Path& path,
  39612. const Colour& preferredBackgroundColour,
  39613. int tabIndex,
  39614. const String& text,
  39615. Button& button,
  39616. TabbedButtonBar::Orientation orientation,
  39617. const bool isMouseOver,
  39618. const bool isMouseDown,
  39619. const bool isFrontTab);
  39620. virtual void drawTabButtonText (Graphics& g,
  39621. int x, int y, int w, int h,
  39622. const Colour& preferredBackgroundColour,
  39623. int tabIndex,
  39624. const String& text,
  39625. Button& button,
  39626. TabbedButtonBar::Orientation orientation,
  39627. const bool isMouseOver,
  39628. const bool isMouseDown,
  39629. const bool isFrontTab);
  39630. virtual int getTabButtonOverlap (int tabDepth);
  39631. virtual int getTabButtonSpaceAroundImage();
  39632. virtual int getTabButtonBestWidth (int tabIndex,
  39633. const String& text,
  39634. int tabDepth,
  39635. Button& button);
  39636. virtual void drawTabButton (Graphics& g,
  39637. int w, int h,
  39638. const Colour& preferredColour,
  39639. int tabIndex,
  39640. const String& text,
  39641. Button& button,
  39642. TabbedButtonBar::Orientation orientation,
  39643. const bool isMouseOver,
  39644. const bool isMouseDown,
  39645. const bool isFrontTab);
  39646. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  39647. int w, int h,
  39648. TabbedButtonBar& tabBar,
  39649. TabbedButtonBar::Orientation orientation);
  39650. virtual Button* createTabBarExtrasButton();
  39651. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  39652. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  39653. int width, int height,
  39654. bool isMouseOver, bool isMouseDown,
  39655. int columnFlags);
  39656. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  39657. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  39658. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  39659. bool isMouseOver, bool isMouseDown,
  39660. ToolbarItemComponent& component);
  39661. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  39662. const String& text, ToolbarItemComponent& component);
  39663. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  39664. bool isOpen, int width, int height);
  39665. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  39666. PropertyComponent& component);
  39667. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  39668. PropertyComponent& component);
  39669. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  39670. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  39671. /**
  39672. */
  39673. virtual void playAlertSound();
  39674. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  39675. static void drawGlassSphere (Graphics& g,
  39676. const float x, const float y,
  39677. const float diameter,
  39678. const Colour& colour,
  39679. const float outlineThickness) throw();
  39680. static void drawGlassPointer (Graphics& g,
  39681. const float x, const float y,
  39682. const float diameter,
  39683. const Colour& colour, const float outlineThickness,
  39684. const int direction) throw();
  39685. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  39686. static void drawGlassLozenge (Graphics& g,
  39687. const float x, const float y,
  39688. const float width, const float height,
  39689. const Colour& colour,
  39690. const float outlineThickness,
  39691. const float cornerSize,
  39692. const bool flatOnLeft, const bool flatOnRight,
  39693. const bool flatOnTop, const bool flatOnBottom) throw();
  39694. juce_UseDebuggingNewOperator
  39695. protected:
  39696. // xxx the following methods are only here to cause a compiler error, because they've been
  39697. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  39698. // error if you try to build a subclass with the old versions.
  39699. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  39700. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  39701. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  39702. virtual void getTabButtonBestWidth (int, const String&, int) {}
  39703. private:
  39704. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  39705. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  39706. Array <int> colourIds;
  39707. Array <Colour> colours;
  39708. void drawShinyButtonShape (Graphics& g,
  39709. float x, float y, float w, float h, float maxCornerSize,
  39710. const Colour& baseColour,
  39711. const float strokeWidth,
  39712. const bool flatOnLeft,
  39713. const bool flatOnRight,
  39714. const bool flatOnTop,
  39715. const bool flatOnBottom) throw();
  39716. LookAndFeel (const LookAndFeel&);
  39717. const LookAndFeel& operator= (const LookAndFeel&);
  39718. };
  39719. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  39720. /********* End of inlined file: juce_LookAndFeel.h *********/
  39721. #endif
  39722. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39723. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39724. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39725. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39726. /**
  39727. The original Juce look-and-feel.
  39728. */
  39729. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  39730. {
  39731. public:
  39732. /** Creates the default JUCE look and feel. */
  39733. OldSchoolLookAndFeel();
  39734. /** Destructor. */
  39735. virtual ~OldSchoolLookAndFeel();
  39736. /** Draws the lozenge-shaped background for a standard button. */
  39737. virtual void drawButtonBackground (Graphics& g,
  39738. Button& button,
  39739. const Colour& backgroundColour,
  39740. bool isMouseOverButton,
  39741. bool isButtonDown);
  39742. /** Draws the contents of a standard ToggleButton. */
  39743. virtual void drawToggleButton (Graphics& g,
  39744. ToggleButton& button,
  39745. bool isMouseOverButton,
  39746. bool isButtonDown);
  39747. virtual void drawTickBox (Graphics& g,
  39748. Component& component,
  39749. int x, int y, int w, int h,
  39750. const bool ticked,
  39751. const bool isEnabled,
  39752. const bool isMouseOverButton,
  39753. const bool isButtonDown);
  39754. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39755. int width, int height,
  39756. double progress, const String& textToShow);
  39757. virtual void drawScrollbarButton (Graphics& g,
  39758. ScrollBar& scrollbar,
  39759. int width, int height,
  39760. int buttonDirection,
  39761. bool isScrollbarVertical,
  39762. bool isMouseOverButton,
  39763. bool isButtonDown);
  39764. virtual void drawScrollbar (Graphics& g,
  39765. ScrollBar& scrollbar,
  39766. int x, int y,
  39767. int width, int height,
  39768. bool isScrollbarVertical,
  39769. int thumbStartPosition,
  39770. int thumbSize,
  39771. bool isMouseOver,
  39772. bool isMouseDown);
  39773. virtual ImageEffectFilter* getScrollbarEffect();
  39774. virtual void drawTextEditorOutline (Graphics& g,
  39775. int width, int height,
  39776. TextEditor& textEditor);
  39777. /** Fills the background of a popup menu component. */
  39778. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39779. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39780. bool isMouseOverBar,
  39781. MenuBarComponent& menuBar);
  39782. virtual void drawComboBox (Graphics& g, int width, int height,
  39783. const bool isButtonDown,
  39784. int buttonX, int buttonY,
  39785. int buttonW, int buttonH,
  39786. ComboBox& box);
  39787. virtual const Font getComboBoxFont (ComboBox& box);
  39788. virtual void drawLinearSlider (Graphics& g,
  39789. int x, int y,
  39790. int width, int height,
  39791. float sliderPos,
  39792. float minSliderPos,
  39793. float maxSliderPos,
  39794. const Slider::SliderStyle style,
  39795. Slider& slider);
  39796. virtual int getSliderThumbRadius (Slider& slider);
  39797. virtual Button* createSliderButton (const bool isIncrement);
  39798. virtual ImageEffectFilter* getSliderEffect();
  39799. virtual void drawCornerResizer (Graphics& g,
  39800. int w, int h,
  39801. bool isMouseOver,
  39802. bool isMouseDragging);
  39803. virtual Button* createDocumentWindowButton (int buttonType);
  39804. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39805. int titleBarX, int titleBarY,
  39806. int titleBarW, int titleBarH,
  39807. Button* minimiseButton,
  39808. Button* maximiseButton,
  39809. Button* closeButton,
  39810. bool positionTitleBarButtonsOnLeft);
  39811. juce_UseDebuggingNewOperator
  39812. private:
  39813. DropShadowEffect scrollbarShadow;
  39814. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  39815. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  39816. };
  39817. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  39818. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  39819. #endif
  39820. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39821. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  39822. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39823. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  39824. /**
  39825. A class to take care of the logic involved with the loading/saving of some kind
  39826. of document.
  39827. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  39828. functions you need for documents that get saved to a file, so this class attempts
  39829. to abstract most of the boring stuff.
  39830. Your subclass should just implement all the pure virtual methods, and you can
  39831. then use the higher-level public methods to do the load/save dialogs, to warn the user
  39832. about overwriting files, etc.
  39833. The document object keeps track of whether it has changed since it was last saved or
  39834. loaded, so when you change something, call its changed() method. This will set a
  39835. flag so it knows it needs saving, and will also broadcast a change message using the
  39836. ChangeBroadcaster base class.
  39837. @see ChangeBroadcaster
  39838. */
  39839. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  39840. {
  39841. public:
  39842. /** Creates a FileBasedDocument.
  39843. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  39844. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  39845. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  39846. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  39847. */
  39848. FileBasedDocument (const String& fileExtension,
  39849. const String& fileWildCard,
  39850. const String& openFileDialogTitle,
  39851. const String& saveFileDialogTitle);
  39852. /** Destructor. */
  39853. virtual ~FileBasedDocument();
  39854. /** Returns true if the changed() method has been called since the file was
  39855. last saved or loaded.
  39856. @see resetChangedFlag, changed
  39857. */
  39858. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  39859. /** Called to indicate that the document has changed and needs saving.
  39860. This method will also trigger a change message to be sent out using the
  39861. ChangeBroadcaster base class.
  39862. After calling the method, the hasChangedSinceSaved() method will return true, until
  39863. it is reset either by saving to a file or using the resetChangedFlag() method.
  39864. @see hasChangedSinceSaved, resetChangedFlag
  39865. */
  39866. virtual void changed();
  39867. /** Sets the state of the 'changed' flag.
  39868. The 'changed' flag is set to true when the changed() method is called - use this method
  39869. to reset it or to set it without also broadcasting a change message.
  39870. @see changed, hasChangedSinceSaved
  39871. */
  39872. void setChangedFlag (const bool hasChanged);
  39873. /** Tries to open a file.
  39874. If the file opens correctly, the document's file (see the getFile() method) is set
  39875. to this new one; if it fails, the document's file is left unchanged, and optionally
  39876. a message box is shown telling the user there was an error.
  39877. @returns true if the new file loaded successfully
  39878. @see loadDocument, loadFromUserSpecifiedFile
  39879. */
  39880. bool loadFrom (const File& fileToLoadFrom,
  39881. const bool showMessageOnFailure);
  39882. /** Asks the user for a file and tries to load it.
  39883. This will pop up a dialog box using the title, file extension and
  39884. wildcard specified in the document's constructor, and asks the user
  39885. for a file. If they pick one, the loadFrom() method is used to
  39886. try to load it, optionally showing a message if it fails.
  39887. @returns true if a file was loaded; false if the user cancelled or if they
  39888. picked a file which failed to load correctly
  39889. @see loadFrom
  39890. */
  39891. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  39892. /** A set of possible outcomes of one of the save() methods
  39893. */
  39894. enum SaveResult
  39895. {
  39896. savedOk = 0, /**< indicates that a file was saved successfully. */
  39897. userCancelledSave, /**< indicates that the user aborted the save operation. */
  39898. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  39899. };
  39900. /** Tries to save the document to the last file it was saved or loaded from.
  39901. This will always try to write to the file, even if the document isn't flagged as
  39902. having changed.
  39903. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  39904. true, it will prompt the user to pick a file, as if
  39905. saveAsInteractive() was called.
  39906. @param showMessageOnFailure if true it will show a warning message when if the
  39907. save operation fails
  39908. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  39909. */
  39910. SaveResult save (const bool askUserForFileIfNotSpecified,
  39911. const bool showMessageOnFailure);
  39912. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  39913. it if they say yes.
  39914. If you've got a document open and want to close it (e.g. to quit the app), this is the
  39915. method to call.
  39916. If the document doesn't need saving it'll return the value savedOk so
  39917. you can go ahead and delete the document.
  39918. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  39919. return savedOk, so again, you can safely delete the document.
  39920. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  39921. close-document operation.
  39922. And if they click "save changes", it'll try to save and either return savedOk, or
  39923. failedToWriteToFile if there was a problem.
  39924. @see save, saveAs, saveAsInteractive
  39925. */
  39926. SaveResult saveIfNeededAndUserAgrees();
  39927. /** Tries to save the document to a specified file.
  39928. If this succeeds, it'll also change the document's internal file (as returned by
  39929. the getFile() method). If it fails, the file will be left unchanged.
  39930. @param newFile the file to try to write to
  39931. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39932. the user first if they want to overwrite it
  39933. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  39934. use the saveAsInteractive() method to ask the user for a
  39935. filename
  39936. @param showMessageOnFailure if true and the write operation fails, it'll show
  39937. a message box to warn the user
  39938. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  39939. */
  39940. SaveResult saveAs (const File& newFile,
  39941. const bool warnAboutOverwritingExistingFiles,
  39942. const bool askUserForFileIfNotSpecified,
  39943. const bool showMessageOnFailure);
  39944. /** Prompts the user for a filename and tries to save to it.
  39945. This will pop up a dialog box using the title, file extension and
  39946. wildcard specified in the document's constructor, and asks the user
  39947. for a file. If they pick one, the saveAs() method is used to try to save
  39948. to this file.
  39949. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  39950. the user first if they want to overwrite it
  39951. @see saveIfNeededAndUserAgrees, save, saveAs
  39952. */
  39953. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  39954. /** Returns the file that this document was last successfully saved or loaded from.
  39955. When the document object is created, this will be set to File::nonexistent.
  39956. It is changed when one of the load or save methods is used, or when setFile()
  39957. is used to explicitly set it.
  39958. */
  39959. const File getFile() const throw() { return documentFile; }
  39960. /** Sets the file that this document thinks it was loaded from.
  39961. This won't actually load anything - it just changes the file stored internally.
  39962. @see getFile
  39963. */
  39964. void setFile (const File& newFile);
  39965. protected:
  39966. /** Overload this to return the title of the document.
  39967. This is used in message boxes, filenames and file choosers, so it should be
  39968. something sensible.
  39969. */
  39970. virtual const String getDocumentTitle() = 0;
  39971. /** This method should try to load your document from the given file.
  39972. If it fails, it should return an error message. If it succeeds, it should return
  39973. an empty string.
  39974. */
  39975. virtual const String loadDocument (const File& file) = 0;
  39976. /** This method should try to write your document to the given file.
  39977. If it fails, it should return an error message. If it succeeds, it should return
  39978. an empty string.
  39979. */
  39980. virtual const String saveDocument (const File& file) = 0;
  39981. /** This is used for dialog boxes to make them open at the last folder you
  39982. were using.
  39983. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39984. the last document that was used - you might want to store this value
  39985. in a static variable, or even in your application's properties. It should
  39986. be a global setting rather than a property of this object.
  39987. This method works very well in conjunction with a RecentlyOpenedFilesList
  39988. object to manage your recent-files list.
  39989. As a default value, it's ok to return File::nonexistent, and the document
  39990. object will use a sensible one instead.
  39991. @see RecentlyOpenedFilesList
  39992. */
  39993. virtual const File getLastDocumentOpened() = 0;
  39994. /** This is used for dialog boxes to make them open at the last folder you
  39995. were using.
  39996. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  39997. the last document that was used - you might want to store this value
  39998. in a static variable, or even in your application's properties. It should
  39999. be a global setting rather than a property of this object.
  40000. This method works very well in conjunction with a RecentlyOpenedFilesList
  40001. object to manage your recent-files list.
  40002. @see RecentlyOpenedFilesList
  40003. */
  40004. virtual void setLastDocumentOpened (const File& file) = 0;
  40005. public:
  40006. juce_UseDebuggingNewOperator
  40007. private:
  40008. File documentFile;
  40009. bool changedSinceSave;
  40010. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  40011. FileBasedDocument (const FileBasedDocument&);
  40012. const FileBasedDocument& operator= (const FileBasedDocument&);
  40013. };
  40014. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40015. /********* End of inlined file: juce_FileBasedDocument.h *********/
  40016. #endif
  40017. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40018. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40019. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40020. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40021. /**
  40022. Manages a set of files for use as a list of recently-opened documents.
  40023. This is a handy class for holding your list of recently-opened documents, with
  40024. helpful methods for things like purging any non-existent files, automatically
  40025. adding them to a menu, and making persistence easy.
  40026. @see File, FileBasedDocument
  40027. */
  40028. class JUCE_API RecentlyOpenedFilesList
  40029. {
  40030. public:
  40031. /** Creates an empty list.
  40032. */
  40033. RecentlyOpenedFilesList();
  40034. /** Destructor. */
  40035. ~RecentlyOpenedFilesList();
  40036. /** Sets a limit for the number of files that will be stored in the list.
  40037. When addFile() is called, then if there is no more space in the list, the
  40038. least-recently added file will be dropped.
  40039. @see getMaxNumberOfItems
  40040. */
  40041. void setMaxNumberOfItems (const int newMaxNumber);
  40042. /** Returns the number of items that this list will store.
  40043. @see setMaxNumberOfItems
  40044. */
  40045. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  40046. /** Returns the number of files in the list.
  40047. The most recently added file is always at index 0.
  40048. */
  40049. int getNumFiles() const;
  40050. /** Returns one of the files in the list.
  40051. The most recently added file is always at index 0.
  40052. */
  40053. const File getFile (const int index) const;
  40054. /** Returns an array of all the absolute pathnames in the list.
  40055. */
  40056. const StringArray& getAllFilenames() const throw() { return files; }
  40057. /** Clears all the files from the list. */
  40058. void clear();
  40059. /** Adds a file to the list.
  40060. The file will be added at index 0. If this file is already in the list, it will
  40061. be moved up to index 0, but a file can only appear once in the list.
  40062. If the list already contains the maximum number of items that is permitted, the
  40063. least-recently added file will be dropped from the end.
  40064. */
  40065. void addFile (const File& file);
  40066. /** Checks each of the files in the list, removing any that don't exist.
  40067. You might want to call this after reloading a list of files, or before putting them
  40068. on a menu.
  40069. */
  40070. void removeNonExistentFiles();
  40071. /** Adds entries to a menu, representing each of the files in the list.
  40072. This is handy for creating an "open recent file..." menu in your app. The
  40073. menu items are numbered consecutively starting with the baseItemId value,
  40074. and can either be added as complete pathnames, or just the last part of the
  40075. filename.
  40076. If dontAddNonExistentFiles is true, then each file will be checked and only those
  40077. that exist will be added.
  40078. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  40079. pointers to file objects. Any files that appear in this list will not be added to the
  40080. menu - the reason for this is that you might have a number of files already open, so
  40081. might not want these to be shown in the menu.
  40082. It returns the number of items that were added.
  40083. */
  40084. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  40085. const int baseItemId,
  40086. const bool showFullPaths,
  40087. const bool dontAddNonExistentFiles,
  40088. const File** filesToAvoid = 0);
  40089. /** Returns a string that encapsulates all the files in the list.
  40090. The string that is returned can later be passed into restoreFromString() in
  40091. order to recreate the list. This is handy for persisting your list, e.g. in
  40092. a PropertiesFile object.
  40093. @see restoreFromString
  40094. */
  40095. const String toString() const;
  40096. /** Restores the list from a previously stringified version of the list.
  40097. Pass in a stringified version created with toString() in order to persist/restore
  40098. your list.
  40099. @see toString
  40100. */
  40101. void restoreFromString (const String& stringifiedVersion);
  40102. juce_UseDebuggingNewOperator
  40103. private:
  40104. StringArray files;
  40105. int maxNumberOfItems;
  40106. };
  40107. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40108. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40109. #endif
  40110. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40111. #endif
  40112. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  40113. #endif
  40114. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40115. #endif
  40116. #endif
  40117. /********* End of inlined file: juce_app_includes.h *********/
  40118. #endif
  40119. #if JUCE_MSVC
  40120. #pragma warning (pop)
  40121. #pragma pack (pop)
  40122. #endif
  40123. #if JUCE_MAC
  40124. #pragma align=reset
  40125. #endif
  40126. END_JUCE_NAMESPACE
  40127. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40128. #ifdef JUCE_NAMESPACE
  40129. // this will obviously save a lot of typing, but can be disabled by
  40130. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40131. using namespace JUCE_NAMESPACE;
  40132. /* On the Mac, these symbols are defined in the Mac libraries, so
  40133. these macros make it easier to reference them without writing out
  40134. the namespace every time.
  40135. If you run into difficulties where these macros interfere with the contents
  40136. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40137. the comments in that file for more information.
  40138. */
  40139. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40140. #define Component JUCE_NAMESPACE::Component
  40141. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40142. #define Point JUCE_NAMESPACE::Point
  40143. #define Button JUCE_NAMESPACE::Button
  40144. #endif
  40145. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40146. it easier to use the juce version explicitly.
  40147. If you run into difficulties where this macro interferes with other 3rd party header
  40148. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40149. file for more information.
  40150. */
  40151. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40152. #define Rectangle JUCE_NAMESPACE::Rectangle
  40153. #endif
  40154. #endif
  40155. #endif
  40156. /* Easy autolinking to the right JUCE libraries under win32.
  40157. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40158. including this header file.
  40159. */
  40160. #if JUCE_MSVC
  40161. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40162. /** If you want your application to link to Juce as a DLL instead of
  40163. a static library (on win32), just define the JUCE_DLL macro before
  40164. including juce.h
  40165. */
  40166. #ifdef JUCE_DLL
  40167. #ifdef JUCE_DEBUG
  40168. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40169. #else
  40170. #define AUTOLINKEDLIB "JUCE.lib"
  40171. #endif
  40172. #else
  40173. #ifdef JUCE_DEBUG
  40174. #ifdef _WIN64
  40175. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40176. #else
  40177. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40178. #endif
  40179. #else
  40180. #ifdef _WIN64
  40181. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40182. #else
  40183. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40184. #endif
  40185. #endif
  40186. #endif
  40187. #pragma comment(lib, AUTOLINKEDLIB)
  40188. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40189. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40190. #endif
  40191. // Auto-link the other win32 libs that are needed by library calls..
  40192. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40193. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40194. // Auto-links to various win32 libs that are needed by library calls..
  40195. #pragma comment(lib, "kernel32.lib")
  40196. #pragma comment(lib, "user32.lib")
  40197. #pragma comment(lib, "shell32.lib")
  40198. #pragma comment(lib, "gdi32.lib")
  40199. #pragma comment(lib, "vfw32.lib")
  40200. #pragma comment(lib, "comdlg32.lib")
  40201. #pragma comment(lib, "winmm.lib")
  40202. #pragma comment(lib, "wininet.lib")
  40203. #pragma comment(lib, "ole32.lib")
  40204. #pragma comment(lib, "advapi32.lib")
  40205. #pragma comment(lib, "ws2_32.lib")
  40206. #pragma comment(lib, "comsupp.lib")
  40207. #if JUCE_OPENGL
  40208. #pragma comment(lib, "OpenGL32.Lib")
  40209. #pragma comment(lib, "GlU32.Lib")
  40210. #endif
  40211. #if JUCE_QUICKTIME
  40212. #pragma comment (lib, "QTMLClient.lib")
  40213. #endif
  40214. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40215. #endif
  40216. #endif
  40217. #endif
  40218. /*
  40219. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40220. AppSubClass is the name of a class derived from JUCEApplication.
  40221. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40222. */
  40223. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40224. #define START_JUCE_APPLICATION(AppClass) \
  40225. int main (int argc, char* argv[]) \
  40226. { \
  40227. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40228. }
  40229. #elif JUCE_WIN32
  40230. #ifdef _CONSOLE
  40231. #define START_JUCE_APPLICATION(AppClass) \
  40232. int main (int, char* argv[]) \
  40233. { \
  40234. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40235. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40236. }
  40237. #elif ! defined (_AFXDLL)
  40238. #ifdef _WINDOWS_
  40239. #define START_JUCE_APPLICATION(AppClass) \
  40240. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40241. { \
  40242. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40243. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40244. }
  40245. #else
  40246. #define START_JUCE_APPLICATION(AppClass) \
  40247. int __stdcall WinMain (int, int, const char*, int) \
  40248. { \
  40249. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40250. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40251. }
  40252. #endif
  40253. #endif
  40254. #endif
  40255. #endif // __JUCE_JUCEHEADER__
  40256. /********* End of inlined file: juce.h *********/
  40257. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__