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.

54492 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. /** Setting this allows the build to use old Carbon libraries that will be
  174. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  175. reasons.
  176. */
  177. #ifndef JUCE_SUPPORT_CARBON
  178. #define JUCE_SUPPORT_CARBON 1
  179. #endif
  180. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  181. codebase - you might need to use this if you're linking to some of these libraries
  182. yourself.
  183. */
  184. #ifndef JUCE_INCLUDE_ZLIB_CODE
  185. #define JUCE_INCLUDE_ZLIB_CODE 1
  186. #endif
  187. #ifndef JUCE_INCLUDE_FLAC_CODE
  188. #define JUCE_INCLUDE_FLAC_CODE 1
  189. #endif
  190. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  191. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  192. #endif
  193. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  194. #define JUCE_INCLUDE_PNGLIB_CODE 1
  195. #endif
  196. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  197. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  198. #endif
  199. /** Enable this to add extra memory-leak info to the new and delete operators.
  200. (Currently, this only affects Windows builds in debug mode).
  201. */
  202. #ifndef JUCE_CHECK_MEMORY_LEAKS
  203. #define JUCE_CHECK_MEMORY_LEAKS 1
  204. #endif
  205. /** Enable this to turn on juce's internal catching of exceptions.
  206. Turning it off will avoid any exception catching. With it on, all exceptions
  207. are passed to the JUCEApplication::unhandledException() callback for logging.
  208. */
  209. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  210. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  211. #endif
  212. /** If this macro is set, the Juce String class will use unicode as its
  213. internal representation. If it isn't set, it'll use ANSI.
  214. */
  215. #ifndef JUCE_STRINGS_ARE_UNICODE
  216. #define JUCE_STRINGS_ARE_UNICODE 1
  217. #endif
  218. #endif
  219. /********* End of inlined file: juce_Config.h *********/
  220. #ifdef JUCE_NAMESPACE
  221. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  222. #define END_JUCE_NAMESPACE }
  223. #else
  224. #define BEGIN_JUCE_NAMESPACE
  225. #define END_JUCE_NAMESPACE
  226. #endif
  227. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  228. /********* Start of inlined file: juce_PlatformDefs.h *********/
  229. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  230. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  231. /* This file figures out which platform is being built, and defines some macros
  232. that the rest of the code can use for OS-specific compilation.
  233. Macros that will be set here are:
  234. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  235. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  236. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  237. - Either JUCE_INTEL or JUCE_PPC
  238. - Either JUCE_GCC or JUCE_MSVC
  239. On the Mac, it also defines MACOS_10_2_OR_EARLIER if the build is targeting OSX10.2,
  240. and MACOS_10_3_OR_EARLIER if it is targeting either 10.2 or 10.3
  241. It also includes a set of macros for debug console output and assertions.
  242. */
  243. #if (defined (_WIN32) || defined (_WIN64))
  244. #define JUCE_WIN32 1
  245. #else
  246. #if defined (LINUX) || defined (__linux__)
  247. #define JUCE_LINUX 1
  248. #else
  249. #define JUCE_MAC 1
  250. #endif
  251. #endif
  252. #if JUCE_WIN32
  253. #ifdef _MSC_VER
  254. #ifdef _WIN64
  255. #define JUCE_64BIT 1
  256. #else
  257. #define JUCE_32BIT 1
  258. #endif
  259. #endif
  260. #ifdef _DEBUG
  261. #define JUCE_DEBUG 1
  262. #endif
  263. /** If defined, this indicates that the processor is little-endian. */
  264. #define JUCE_LITTLE_ENDIAN 1
  265. #define JUCE_INTEL 1
  266. #endif
  267. #if JUCE_MAC
  268. #include <CoreFoundation/CoreFoundation.h>
  269. #ifndef NDEBUG
  270. #define JUCE_DEBUG 1
  271. #endif
  272. #ifdef __LITTLE_ENDIAN__
  273. #define JUCE_LITTLE_ENDIAN 1
  274. #else
  275. #define JUCE_BIG_ENDIAN 1
  276. #endif
  277. #if defined (__ppc__) || defined (__ppc64__)
  278. #define JUCE_PPC 1
  279. #else
  280. #define JUCE_INTEL 1
  281. #endif
  282. #ifdef __LP64__
  283. #define JUCE_64BIT 1
  284. #else
  285. #define JUCE_32BIT 1
  286. #endif
  287. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  288. #define MACOS_10_2_OR_EARLIER 1
  289. #endif
  290. #if (! defined (MAC_OS_X_VERSION_10_4)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  291. #define MACOS_10_3_OR_EARLIER 1
  292. #endif
  293. #if (! defined (MAC_OS_X_VERSION_10_5)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  294. #define MACOS_10_4_OR_EARLIER 1
  295. #endif
  296. #endif
  297. #if JUCE_LINUX
  298. #ifdef _DEBUG
  299. #define JUCE_DEBUG 1
  300. #endif
  301. // Allow override for big-endian Linux platforms
  302. #ifndef JUCE_BIG_ENDIAN
  303. #define JUCE_LITTLE_ENDIAN 1
  304. #endif
  305. #if defined (__LP64__) || defined (_LP64)
  306. #define JUCE_64BIT 1
  307. #else
  308. #define JUCE_32BIT 1
  309. #endif
  310. #define JUCE_INTEL 1
  311. #endif
  312. #ifdef JUCE_FORCE_DEBUG
  313. #undef JUCE_DEBUG
  314. #if JUCE_FORCE_DEBUG
  315. #define JUCE_DEBUG 1
  316. #endif
  317. #endif
  318. // Compiler type macros.
  319. #ifdef __GNUC__
  320. #define JUCE_GCC 1
  321. #elif defined (_MSC_VER)
  322. #define JUCE_MSVC 1
  323. #if _MSC_VER >= 1400
  324. #define JUCE_USE_INTRINSICS 1
  325. #endif
  326. #else
  327. #error unknown compiler
  328. #endif
  329. /** This macro defines the C calling convention used as the standard for Juce calls. */
  330. #if JUCE_MSVC
  331. #define JUCE_CALLTYPE __stdcall
  332. #else
  333. #define JUCE_CALLTYPE
  334. #endif
  335. // Debugging and assertion macros
  336. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  337. #if JUCE_LOG_ASSERTIONS
  338. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  339. #elif defined (JUCE_DEBUG)
  340. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  341. #else
  342. #define juce_LogCurrentAssertion
  343. #endif
  344. #ifdef JUCE_DEBUG
  345. // If debugging is enabled..
  346. /** Writes a string to the standard error stream.
  347. This is only compiled in a debug build.
  348. @see Logger::outputDebugString
  349. */
  350. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  351. /** Printf's a string to the standard error stream.
  352. This is only compiled in a debug build.
  353. @see Logger::outputDebugString
  354. */
  355. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  356. // Assertions..
  357. #if JUCE_WIN32 || DOXYGEN
  358. #if JUCE_USE_INTRINSICS
  359. #pragma intrinsic (__debugbreak)
  360. /** This will try to break the debugger if one is currently hosting this app.
  361. @see jassert()
  362. */
  363. #define juce_breakDebugger __debugbreak();
  364. #elif JUCE_GCC
  365. /** This will try to break the debugger if one is currently hosting this app.
  366. @see jassert()
  367. */
  368. #define juce_breakDebugger asm("int $3");
  369. #else
  370. /** This will try to break the debugger if one is currently hosting this app.
  371. @see jassert()
  372. */
  373. #define juce_breakDebugger { __asm int 3 }
  374. #endif
  375. #elif JUCE_MAC
  376. #define juce_breakDebugger Debugger();
  377. #elif JUCE_LINUX
  378. #define juce_breakDebugger kill (0, SIGTRAP);
  379. #endif
  380. /** This will always cause an assertion failure.
  381. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  382. in juce_Config.h).
  383. @see jassert()
  384. */
  385. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  386. /** Platform-independent assertion macro.
  387. This gets optimised out when not being built with debugging turned on.
  388. Be careful not to call any functions within its arguments that are vital to
  389. the behaviour of the program, because these won't get called in the release
  390. build.
  391. @see jassertfalse
  392. */
  393. #define jassert(expression) { if (! (expression)) jassertfalse }
  394. #else
  395. // If debugging is disabled, these dummy debug and assertion macros are used..
  396. #define DBG(dbgtext)
  397. #define DBG_PRINTF(dbgprintf)
  398. #define jassertfalse { juce_LogCurrentAssertion }
  399. #if JUCE_LOG_ASSERTIONS
  400. #define jassert(expression) { if (! (expression)) jassertfalse }
  401. #else
  402. #define jassert(a) { }
  403. #endif
  404. #endif
  405. #ifndef DOXYGEN
  406. template <bool b> struct JuceStaticAssert;
  407. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  408. #endif
  409. /** A compile-time assertion macro.
  410. If the expression parameter is false, the macro will cause a compile error.
  411. */
  412. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  413. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  414. #define JUCE_TRY try
  415. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  416. object so they can be logged by the application if it wants to.
  417. */
  418. #define JUCE_CATCH_EXCEPTION \
  419. catch (const std::exception& e) \
  420. { \
  421. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  422. } \
  423. catch (...) \
  424. { \
  425. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  426. }
  427. #define JUCE_CATCH_ALL catch (...) {}
  428. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  429. #else
  430. #define JUCE_TRY
  431. #define JUCE_CATCH_EXCEPTION
  432. #define JUCE_CATCH_ALL
  433. #define JUCE_CATCH_ALL_ASSERT
  434. #endif
  435. // Macros for inlining.
  436. #if JUCE_MSVC
  437. /** A platform-independent way of forcing an inline function.
  438. Use the syntax: @code
  439. forcedinline void myfunction (int x)
  440. @endcode
  441. */
  442. #ifdef JUCE_DEBUG
  443. #define forcedinline __forceinline
  444. #else
  445. #define forcedinline inline
  446. #endif
  447. /** A platform-independent way of stopping the compiler inlining a function.
  448. Use the syntax: @code
  449. juce_noinline void myfunction (int x)
  450. @endcode
  451. */
  452. #define juce_noinline
  453. #else
  454. /** A platform-independent way of forcing an inline function.
  455. Use the syntax: @code
  456. forcedinline void myfunction (int x)
  457. @endcode
  458. */
  459. #ifndef JUCE_DEBUG
  460. #define forcedinline inline __attribute__((always_inline))
  461. #else
  462. #define forcedinline inline
  463. #endif
  464. /** A platform-independent way of stopping the compiler inlining a function.
  465. Use the syntax: @code
  466. juce_noinline void myfunction (int x)
  467. @endcode
  468. */
  469. #define juce_noinline __attribute__((noinline))
  470. #endif
  471. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  472. /********* End of inlined file: juce_PlatformDefs.h *********/
  473. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  474. #if JUCE_MSVC
  475. #pragma warning (push)
  476. #pragma warning (disable: 4514 4245 4100)
  477. #endif
  478. #include <cstdlib>
  479. #include <cstdarg>
  480. #include <climits>
  481. #include <cmath>
  482. #include <cwchar>
  483. #include <stdexcept>
  484. #include <typeinfo>
  485. #include <cstring>
  486. #include <cstdio>
  487. #if JUCE_MAC || JUCE_LINUX
  488. #include <pthread.h>
  489. #endif
  490. #if JUCE_USE_INTRINSICS
  491. #include <intrin.h>
  492. #endif
  493. #if JUCE_MAC
  494. #if MACOS_10_3_OR_EARLIER
  495. #include <CoreServices/CoreServices.h>
  496. #else
  497. #include <libkern/OSAtomic.h>
  498. #endif
  499. #endif
  500. #if JUCE_LINUX
  501. #include <signal.h>
  502. #endif
  503. #if JUCE_MSVC && JUCE_DEBUG
  504. #include <crtdbg.h>
  505. #endif
  506. #if JUCE_MSVC
  507. #pragma warning (pop)
  508. #endif
  509. // DLL building settings on Win32
  510. #if JUCE_MSVC
  511. #ifdef JUCE_DLL_BUILD
  512. #define JUCE_API __declspec (dllexport)
  513. #pragma warning (disable: 4251)
  514. #elif defined (JUCE_DLL)
  515. #define JUCE_API __declspec (dllimport)
  516. #pragma warning (disable: 4251)
  517. #endif
  518. #endif
  519. #ifndef JUCE_API
  520. /** This macro is added to all juce public class declarations. */
  521. #define JUCE_API
  522. #endif
  523. /** This macro is added to all juce public function declarations. */
  524. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  525. // Now include some basics that are needed by most of the Juce classes...
  526. BEGIN_JUCE_NAMESPACE
  527. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  528. #if JUCE_LOG_ASSERTIONS
  529. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  530. #endif
  531. /********* Start of inlined file: juce_Memory.h *********/
  532. #ifndef __JUCE_MEMORY_JUCEHEADER__
  533. #define __JUCE_MEMORY_JUCEHEADER__
  534. /*
  535. This file defines the various juce_malloc(), juce_free() macros that should be used in
  536. preference to the standard calls.
  537. */
  538. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  539. #ifndef JUCE_DLL
  540. // Win32 debug non-DLL versions..
  541. /** This should be used instead of calling malloc directly. */
  542. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  543. /** This should be used instead of calling calloc directly. */
  544. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  545. /** This should be used instead of calling realloc directly. */
  546. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  547. /** This should be used instead of calling free directly. */
  548. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  549. #else
  550. // Win32 debug DLL versions..
  551. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  552. // way all juce calls in the DLL and in the host API will all use the same allocator.
  553. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  554. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  555. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  556. extern JUCE_API void juce_DebugFree (void* const block);
  557. /** This should be used instead of calling malloc directly. */
  558. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  559. /** This should be used instead of calling calloc directly. */
  560. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  561. /** This should be used instead of calling realloc directly. */
  562. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  563. /** This should be used instead of calling free directly. */
  564. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  565. #endif
  566. #if ! defined (_AFXDLL)
  567. /** This macro can be added to classes to add extra debugging information to the memory
  568. allocated for them, so you can see the type of objects involved when there's a dump
  569. of leaked objects at program shutdown. (Only works on win32 at the moment).
  570. */
  571. #define juce_UseDebuggingNewOperator \
  572. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  573. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  574. static void operator delete (void* p) { juce_free (p); }
  575. #endif
  576. #elif defined (JUCE_DLL)
  577. // Win32 DLL (release) versions..
  578. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  579. // way all juce calls in the DLL and in the host API will all use the same allocator.
  580. extern JUCE_API void* juce_Malloc (const int size);
  581. extern JUCE_API void* juce_Calloc (const int size);
  582. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  583. extern JUCE_API void juce_Free (void* const block);
  584. /** This should be used instead of calling malloc directly. */
  585. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  586. /** This should be used instead of calling calloc directly. */
  587. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  588. /** This should be used instead of calling realloc directly. */
  589. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  590. /** This should be used instead of calling free directly. */
  591. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  592. #define juce_UseDebuggingNewOperator \
  593. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  594. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  595. static void operator delete (void* p) { juce_free (p); }
  596. #else
  597. // Mac, Linux and Win32 (release) versions..
  598. /** This should be used instead of calling malloc directly. */
  599. #define juce_malloc(numBytes) malloc (numBytes)
  600. /** This should be used instead of calling calloc directly. */
  601. #define juce_calloc(numBytes) calloc (1, numBytes)
  602. /** This should be used instead of calling realloc directly. */
  603. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  604. /** This should be used instead of calling free directly. */
  605. #define juce_free(location) free (location)
  606. #endif
  607. /** This macro can be added to classes to add extra debugging information to the memory
  608. allocated for them, so you can see the type of objects involved when there's a dump
  609. of leaked objects at program shutdown. (Only works on win32 at the moment).
  610. Note that if you create a class that inherits from a class that uses this macro,
  611. your class must also use the macro, otherwise you'll probably get compile errors
  612. because of ambiguous new operators.
  613. Most of the JUCE classes use it, so see these for examples of where it should go.
  614. */
  615. #ifndef juce_UseDebuggingNewOperator
  616. #define juce_UseDebuggingNewOperator
  617. #endif
  618. #if JUCE_MSVC
  619. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  620. E.g.
  621. @code
  622. juce_ThreadLocal int myVariable;
  623. @endcode
  624. */
  625. #define juce_ThreadLocal __declspec(thread)
  626. #else
  627. #define juce_ThreadLocal __thread
  628. #endif
  629. /** Clears a block of memory. */
  630. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  631. /** Clears a reference to a local structure. */
  632. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  633. /** A handy macro that calls delete on a pointer if it's non-zero, and
  634. then sets the pointer to null.
  635. */
  636. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  637. #endif // __JUCE_MEMORY_JUCEHEADER__
  638. /********* End of inlined file: juce_Memory.h *********/
  639. /********* Start of inlined file: juce_MathsFunctions.h *********/
  640. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  641. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  642. /*
  643. This file sets up some handy mathematical typdefs and functions.
  644. */
  645. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  646. /** A platform-independent 8-bit signed integer type. */
  647. typedef signed char int8;
  648. /** A platform-independent 8-bit unsigned integer type. */
  649. typedef unsigned char uint8;
  650. /** A platform-independent 16-bit signed integer type. */
  651. typedef signed short int16;
  652. /** A platform-independent 16-bit unsigned integer type. */
  653. typedef unsigned short uint16;
  654. /** A platform-independent 32-bit signed integer type. */
  655. typedef signed int int32;
  656. /** A platform-independent 32-bit unsigned integer type. */
  657. typedef unsigned int uint32;
  658. #if JUCE_MSVC
  659. /** A platform-independent 64-bit integer type. */
  660. typedef __int64 int64;
  661. /** A platform-independent 64-bit unsigned integer type. */
  662. typedef unsigned __int64 uint64;
  663. /** A platform-independent macro for writing 64-bit literals, needed because
  664. different compilers have different syntaxes for this.
  665. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  666. GCC, or 0x1000000000 for MSVC.
  667. */
  668. #define literal64bit(longLiteral) ((__int64) longLiteral)
  669. #else
  670. /** A platform-independent 64-bit integer type. */
  671. typedef long long int64;
  672. /** A platform-independent 64-bit unsigned integer type. */
  673. typedef unsigned long long uint64;
  674. /** A platform-independent macro for writing 64-bit literals, needed because
  675. different compilers have different syntaxes for this.
  676. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  677. GCC, or 0x1000000000 for MSVC.
  678. */
  679. #define literal64bit(longLiteral) (longLiteral##LL)
  680. #endif
  681. #if JUCE_64BIT
  682. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  683. typedef int64 pointer_sized_int;
  684. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  685. typedef uint64 pointer_sized_uint;
  686. #elif _MSC_VER >= 1300
  687. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  688. typedef _W64 int pointer_sized_int;
  689. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  690. typedef _W64 unsigned int pointer_sized_uint;
  691. #else
  692. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  693. typedef int pointer_sized_int;
  694. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  695. typedef unsigned int pointer_sized_uint;
  696. #endif
  697. /** A platform-independent unicode character type. */
  698. typedef wchar_t juce_wchar;
  699. // Some indispensible min/max functions
  700. /** Returns the larger of two values. */
  701. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  702. /** Returns the larger of two values. */
  703. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  704. /** Returns the larger of two values. */
  705. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  706. /** Returns the larger of two values. */
  707. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  708. /** Returns the larger of three values. */
  709. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  710. /** Returns the larger of three values. */
  711. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  712. /** Returns the larger of three values. */
  713. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  714. /** Returns the larger of three values. */
  715. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  716. /** Returns the larger of four values. */
  717. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  718. /** Returns the larger of four values. */
  719. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  720. /** Returns the larger of four values. */
  721. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  722. /** Returns the larger of four values. */
  723. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  724. /** Returns the smaller of two values. */
  725. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  726. /** Returns the smaller of two values. */
  727. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  728. /** Returns the smaller of two values. */
  729. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  730. /** Returns the smaller of two values. */
  731. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  732. /** Returns the smaller of three values. */
  733. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  734. /** Returns the smaller of three values. */
  735. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  736. /** Returns the smaller of three values. */
  737. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  738. /** Returns the smaller of three values. */
  739. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  740. /** Returns the smaller of four values. */
  741. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  742. /** Returns the smaller of four values. */
  743. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  744. /** Returns the smaller of four values. */
  745. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  746. /** Returns the smaller of four values. */
  747. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  748. /** Constrains a value to keep it within a given range.
  749. This will check that the specified value lies between the lower and upper bounds
  750. specified, and if not, will return the nearest value that would be in-range. Effectively,
  751. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  752. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  753. the results will be unpredictable.
  754. @param lowerLimit the minimum value to return
  755. @param upperLimit the maximum value to return
  756. @param valueToConstrain the value to try to return
  757. @returns the closest value to valueToConstrain which lies between lowerLimit
  758. and upperLimit (inclusive)
  759. @see jlimit0To, jmin, jmax
  760. */
  761. template <class Type>
  762. inline Type jlimit (const Type lowerLimit,
  763. const Type upperLimit,
  764. const Type valueToConstrain) throw()
  765. {
  766. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  767. return (valueToConstrain < lowerLimit) ? lowerLimit
  768. : ((valueToConstrain > upperLimit) ? upperLimit
  769. : valueToConstrain);
  770. }
  771. /** Handy function to swap two values over.
  772. */
  773. template <class Type>
  774. inline void swapVariables (Type& variable1, Type& variable2) throw()
  775. {
  776. const Type tempVal = variable1;
  777. variable1 = variable2;
  778. variable2 = tempVal;
  779. }
  780. /** Handy macro for getting the number of elements in a simple const C array.
  781. E.g.
  782. @code
  783. static int myArray[] = { 1, 2, 3 };
  784. int numElements = numElementsInArray (myArray) // returns 3
  785. @endcode
  786. */
  787. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  788. // Some useful maths functions that aren't always present with all compilers and build settings.
  789. #if JUCE_WIN32 || defined (DOXYGEN)
  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. #elif MACOS_10_2_OR_EARLIER
  797. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  798. versions of these functions of various platforms and compilers. */
  799. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  800. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  801. versions of these functions of various platforms and compilers. */
  802. forcedinline float juce_hypotf (float a, float b) { return (float) hypot (a, b); }
  803. forcedinline float sinf (const float a) { return (float) sin (a); }
  804. forcedinline float cosf (const float a) { return (float) cos (a); }
  805. forcedinline float tanf (const float a) { return (float) tan (a); }
  806. forcedinline float atan2f (const float a, const float b) { return (float) atan2 (a, b); }
  807. forcedinline float sqrtf (const float a) { return (float) sqrt (a); }
  808. forcedinline float logf (const float a) { return (float) log (a); }
  809. forcedinline float powf (const float a, const float b) { return (float) pow (a, b); }
  810. forcedinline float expf (const float a) { return (float) exp (a); }
  811. #else
  812. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  813. versions of these functions of various platforms and compilers. */
  814. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  815. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  816. versions of these functions of various platforms and compilers. */
  817. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  818. #endif
  819. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  820. /** A predefined value for Pi, at double-precision.
  821. @see float_Pi
  822. */
  823. const double double_Pi = 3.1415926535897932384626433832795;
  824. /** A predefined value for Pi, at sngle-precision.
  825. @see double_Pi
  826. */
  827. const float float_Pi = 3.14159265358979323846f;
  828. /** The isfinite() method seems to vary greatly between platforms, so this is a
  829. platform-independent macro for it.
  830. */
  831. #if JUCE_LINUX
  832. #define juce_isfinite(v) std::isfinite(v)
  833. #elif JUCE_MAC
  834. #if MACOS_10_2_OR_EARLIER
  835. #define juce_isfinite(v) __isfinite(v)
  836. #elif MACOS_10_3_OR_EARLIER
  837. #ifdef isfinite
  838. #define juce_isfinite(v) isfinite(v)
  839. #else
  840. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  841. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  842. #endif
  843. #else
  844. #define juce_isfinite(v) std::isfinite(v)
  845. #endif
  846. #elif JUCE_WIN32 && ! defined (isfinite)
  847. #define juce_isfinite(v) _finite(v)
  848. #else
  849. #define juce_isfinite(v) isfinite(v)
  850. #endif
  851. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  852. /********* End of inlined file: juce_MathsFunctions.h *********/
  853. /********* Start of inlined file: juce_DataConversions.h *********/
  854. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  855. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  856. #if JUCE_USE_INTRINSICS
  857. #pragma intrinsic (_byteswap_ulong)
  858. #endif
  859. // Endianness conversions..
  860. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  861. forcedinline uint32 swapByteOrder (uint32 n) throw()
  862. {
  863. #if JUCE_MAC
  864. // Mac version
  865. return CFSwapInt32 (n);
  866. #elif JUCE_GCC
  867. // Inpenetrable GCC version..
  868. asm("bswap %%eax" : "=a"(n) : "a"(n));
  869. return n;
  870. #elif JUCE_USE_INTRINSICS
  871. // Win32 intrinsics version..
  872. return _byteswap_ulong (n);
  873. #else
  874. // Win32 version..
  875. __asm {
  876. mov eax, n
  877. bswap eax
  878. mov n, eax
  879. }
  880. return n;
  881. #endif
  882. }
  883. /** Swaps the byte-order of a 16-bit short. */
  884. inline uint16 swapByteOrder (const uint16 n) throw()
  885. {
  886. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  887. // Win32 intrinsics version..
  888. return (uint16) _byteswap_ushort (n);
  889. #else
  890. return (uint16) ((n << 8) | (n >> 8));
  891. #endif
  892. }
  893. inline uint64 swapByteOrder (const uint64 value) throw()
  894. {
  895. #if JUCE_MAC
  896. return CFSwapInt64 (value);
  897. #elif JUCE_USE_INTRINSICS
  898. return _byteswap_uint64 (value);
  899. #else
  900. return (((int64) swapByteOrder ((uint32) value)) << 32)
  901. | swapByteOrder ((uint32) (value >> 32));
  902. #endif
  903. }
  904. #if JUCE_LITTLE_ENDIAN
  905. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  906. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  907. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  908. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  909. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  910. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  911. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  912. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  913. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  914. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  915. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  916. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  917. /** Turns 4 bytes into a little-endian integer. */
  918. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  919. /** Turns 2 bytes into a little-endian integer. */
  920. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  921. /** Turns 4 bytes into a big-endian integer. */
  922. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  923. /** Turns 2 bytes into a big-endian integer. */
  924. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  925. #else
  926. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  927. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  928. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  929. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  930. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  931. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  932. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  933. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  934. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  935. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  936. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  937. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  938. /** Turns 4 bytes into a little-endian integer. */
  939. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  940. /** Turns 2 bytes into a little-endian integer. */
  941. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  942. /** Turns 4 bytes into a big-endian integer. */
  943. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  944. /** Turns 2 bytes into a big-endian integer. */
  945. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  946. #endif
  947. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  948. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  949. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  950. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  951. /** Copies a 24-bit number to 3 little-endian bytes. */
  952. 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); }
  953. /** Copies a 24-bit number to 3 big-endian bytes. */
  954. 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); }
  955. /** Fast floating-point-to-integer conversion.
  956. This is faster than using the normal c++ cast to convert a double to an int, and
  957. it will round the value to the nearest integer, rather than rounding it down
  958. like the normal cast does.
  959. Note that this routine gets its speed at the expense of some accuracy, and when
  960. rounding values whose floating point component is exactly 0.5, odd numbers and
  961. even numbers will be rounded up or down differently. For a more accurate conversion,
  962. see roundDoubleToIntAccurate().
  963. */
  964. inline int roundDoubleToInt (const double value) throw()
  965. {
  966. union { int asInt[2]; double asDouble; } n;
  967. n.asDouble = value + 6755399441055744.0;
  968. #if JUCE_BIG_ENDIAN
  969. return n.asInt [1];
  970. #else
  971. return n.asInt [0];
  972. #endif
  973. }
  974. /** Fast floating-point-to-integer conversion.
  975. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  976. fine for values above zero, but negative numbers are rounded the wrong way.
  977. */
  978. inline int roundDoubleToIntAccurate (const double value) throw()
  979. {
  980. return roundDoubleToInt (value + 1.5e-8);
  981. }
  982. /** Fast floating-point-to-integer conversion.
  983. This is faster than using the normal c++ cast to convert a float to an int, and
  984. it will round the value to the nearest integer, rather than rounding it down
  985. like the normal cast does.
  986. Note that this routine gets its speed at the expense of some accuracy, and when
  987. rounding values whose floating point component is exactly 0.5, odd numbers and
  988. even numbers will be rounded up or down differently.
  989. */
  990. inline int roundFloatToInt (const float value) throw()
  991. {
  992. union { int asInt[2]; double asDouble; } n;
  993. n.asDouble = value + 6755399441055744.0;
  994. #if JUCE_BIG_ENDIAN
  995. return n.asInt [1];
  996. #else
  997. return n.asInt [0];
  998. #endif
  999. }
  1000. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  1001. /********* End of inlined file: juce_DataConversions.h *********/
  1002. /********* Start of inlined file: juce_Logger.h *********/
  1003. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1004. #define __JUCE_LOGGER_JUCEHEADER__
  1005. /********* Start of inlined file: juce_String.h *********/
  1006. #ifndef __JUCE_STRING_JUCEHEADER__
  1007. #define __JUCE_STRING_JUCEHEADER__
  1008. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1009. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1010. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1011. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1012. (in the default system encoding) as its internal representation.
  1013. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1014. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1015. literals in the T("abcd") macro, so that it all works nicely either way round.
  1016. */
  1017. #if JUCE_STRINGS_ARE_UNICODE
  1018. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1019. typedef juce_wchar tchar;
  1020. #define juce_tcharToWideChar(c) (c)
  1021. #else
  1022. #define JUCE_T(stringLiteral) (stringLiteral)
  1023. typedef char tchar;
  1024. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1025. #endif
  1026. #if ! JUCE_DONT_DEFINE_MACROS
  1027. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1028. or unicode.
  1029. If you write your string literals in the form T("xyz"), this will either be compiled
  1030. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1031. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1032. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1033. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1034. the juce/src directory) to avoid defining this macro. See the comments in
  1035. juce_withoutMacros.h for more info.
  1036. */
  1037. #define T(stringLiteral) JUCE_T(stringLiteral)
  1038. #endif
  1039. /**
  1040. A set of methods for manipulating characters and character strings, with
  1041. duplicate methods to handle 8-bit and unicode characters.
  1042. These are defined as wrappers around the basic C string handlers, to provide
  1043. a clean, cross-platform layer, (because various platforms differ in the
  1044. range of C library calls that they provide).
  1045. @see String
  1046. */
  1047. class JUCE_API CharacterFunctions
  1048. {
  1049. public:
  1050. static int length (const char* const s) throw();
  1051. static int length (const juce_wchar* const s) throw();
  1052. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1053. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1054. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1055. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1056. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1057. static void append (char* dest, const char* src) throw();
  1058. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1059. static int compare (const char* const s1, const char* const s2) throw();
  1060. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1061. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1062. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1063. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1064. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1065. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1066. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1067. static const char* find (const char* const haystack, const char* const needle) throw();
  1068. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1069. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1070. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1071. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1072. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1073. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1074. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1075. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1076. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1077. static int getIntValue (const char* const s) throw();
  1078. static int getIntValue (const juce_wchar* s) throw();
  1079. static int64 getInt64Value (const char* s) throw();
  1080. static int64 getInt64Value (const juce_wchar* s) throw();
  1081. static double getDoubleValue (const char* const s) throw();
  1082. static double getDoubleValue (const juce_wchar* const s) throw();
  1083. static char toUpperCase (const char character) throw();
  1084. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1085. static void toUpperCase (char* s) throw();
  1086. static void toUpperCase (juce_wchar* s) throw();
  1087. static bool isUpperCase (const char character) throw();
  1088. static bool isUpperCase (const juce_wchar character) throw();
  1089. static char toLowerCase (const char character) throw();
  1090. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1091. static void toLowerCase (char* s) throw();
  1092. static void toLowerCase (juce_wchar* s) throw();
  1093. static bool isLowerCase (const char character) throw();
  1094. static bool isLowerCase (const juce_wchar character) throw();
  1095. static bool isWhitespace (const char character) throw();
  1096. static bool isWhitespace (const juce_wchar character) throw();
  1097. static bool isDigit (const char character) throw();
  1098. static bool isDigit (const juce_wchar character) throw();
  1099. static bool isLetter (const char character) throw();
  1100. static bool isLetter (const juce_wchar character) throw();
  1101. static bool isLetterOrDigit (const char character) throw();
  1102. static bool isLetterOrDigit (const juce_wchar character) throw();
  1103. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1104. hex digit.
  1105. */
  1106. static int getHexDigitValue (const tchar digit) throw();
  1107. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1108. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1109. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1110. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1111. };
  1112. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1113. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1114. /**
  1115. The JUCE String class!
  1116. Using a reference-counted internal representation, these strings are fast
  1117. and efficient, and there are methods to do just about any operation you'll ever
  1118. dream of.
  1119. @see StringArray, StringPairArray
  1120. */
  1121. class JUCE_API String
  1122. {
  1123. public:
  1124. /** Creates an empty string.
  1125. @see empty
  1126. */
  1127. String() throw();
  1128. /** Creates a copy of another string. */
  1129. String (const String& other) throw();
  1130. /** Creates a string from a zero-terminated text string.
  1131. The string is assumed to be stored in the default system encoding.
  1132. */
  1133. String (const char* const text) throw();
  1134. /** Creates a string from an string of characters.
  1135. This will use up the the first maxChars characters of the string (or
  1136. less if the string is actually shorter)
  1137. */
  1138. String (const char* const text,
  1139. const int maxChars) throw();
  1140. /** Creates a string from a zero-terminated unicode text string. */
  1141. String (const juce_wchar* const unicodeText) throw();
  1142. /** Creates a string from a unicode text string.
  1143. This will use up the the first maxChars characters of the string (or
  1144. less if the string is actually shorter)
  1145. */
  1146. String (const juce_wchar* const unicodeText,
  1147. const int maxChars) throw();
  1148. /** Creates a string from a single character. */
  1149. static const String charToString (const tchar character) throw();
  1150. /** Destructor. */
  1151. ~String() throw();
  1152. /** This is an empty string that can be used whenever one is needed.
  1153. It's better to use this than String() because it explains what's going on
  1154. and is more efficient.
  1155. */
  1156. static const String empty;
  1157. /** Generates a probably-unique 32-bit hashcode from this string. */
  1158. int hashCode() const throw();
  1159. /** Generates a probably-unique 64-bit hashcode from this string. */
  1160. int64 hashCode64() const throw();
  1161. /** Returns the number of characters in the string. */
  1162. int length() const throw();
  1163. // Assignment and concatenation operators..
  1164. /** Replaces this string's contents with another string. */
  1165. const String& operator= (const tchar* const other) throw();
  1166. /** Replaces this string's contents with another string. */
  1167. const String& operator= (const String& other) throw();
  1168. /** Appends another string at the end of this one. */
  1169. const String& operator+= (const tchar* const textToAppend) throw();
  1170. /** Appends another string at the end of this one. */
  1171. const String& operator+= (const String& stringToAppend) throw();
  1172. /** Appends a character at the end of this string. */
  1173. const String& operator+= (const char characterToAppend) throw();
  1174. /** Appends a character at the end of this string. */
  1175. const String& operator+= (const juce_wchar characterToAppend) throw();
  1176. /** Appends a string at the end of this one.
  1177. @param textToAppend the string to add
  1178. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1179. */
  1180. void append (const tchar* const textToAppend,
  1181. const int maxCharsToTake) throw();
  1182. /** Appends a string at the end of this one.
  1183. @returns the concatenated string
  1184. */
  1185. const String operator+ (const String& stringToAppend) const throw();
  1186. /** Appends a string at the end of this one.
  1187. @returns the concatenated string
  1188. */
  1189. const String operator+ (const tchar* const textToAppend) const throw();
  1190. /** Appends a character at the end of this one.
  1191. @returns the concatenated string
  1192. */
  1193. const String operator+ (const tchar characterToAppend) const throw();
  1194. /** Appends a character at the end of this string. */
  1195. String& operator<< (const char n) throw();
  1196. /** Appends a character at the end of this string. */
  1197. String& operator<< (const juce_wchar n) throw();
  1198. /** Appends another string at the end of this one. */
  1199. String& operator<< (const char* const text) throw();
  1200. /** Appends another string at the end of this one. */
  1201. String& operator<< (const juce_wchar* const text) throw();
  1202. /** Appends another string at the end of this one. */
  1203. String& operator<< (const String& text) throw();
  1204. /** Appends a decimal number at the end of this string. */
  1205. String& operator<< (const short number) throw();
  1206. /** Appends a decimal number at the end of this string. */
  1207. String& operator<< (const int number) throw();
  1208. /** Appends a decimal number at the end of this string. */
  1209. String& operator<< (const unsigned int number) throw();
  1210. /** Appends a decimal number at the end of this string. */
  1211. String& operator<< (const float number) throw();
  1212. /** Appends a decimal number at the end of this string. */
  1213. String& operator<< (const double number) throw();
  1214. // Comparison methods..
  1215. /** Returns true if the string contains no characters.
  1216. Note that there's also an isNotEmpty() method to help write readable code.
  1217. @see containsNonWhitespaceChars()
  1218. */
  1219. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1220. /** Returns true if the string contains at least one character.
  1221. Note that there's also an isEmpty() method to help write readable code.
  1222. @see containsNonWhitespaceChars()
  1223. */
  1224. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1225. /** Case-sensitive comparison with another string. */
  1226. bool operator== (const String& other) const throw();
  1227. /** Case-sensitive comparison with another string. */
  1228. bool operator== (const tchar* const other) const throw();
  1229. /** Case-sensitive comparison with another string. */
  1230. bool operator!= (const String& other) const throw();
  1231. /** Case-sensitive comparison with another string. */
  1232. bool operator!= (const tchar* const other) const throw();
  1233. /** Case-insensitive comparison with another string. */
  1234. bool equalsIgnoreCase (const String& other) const throw();
  1235. /** Case-insensitive comparison with another string. */
  1236. bool equalsIgnoreCase (const tchar* const other) const throw();
  1237. /** Case-sensitive comparison with another string. */
  1238. bool operator> (const String& other) const throw();
  1239. /** Case-sensitive comparison with another string. */
  1240. bool operator< (const tchar* const other) const throw();
  1241. /** Case-sensitive comparison with another string. */
  1242. bool operator>= (const String& other) const throw();
  1243. /** Case-sensitive comparison with another string. */
  1244. bool operator<= (const tchar* const other) const throw();
  1245. /** Case-sensitive comparison with another string.
  1246. @returns 0 if the two strings are identical; negative if this string
  1247. comes before the other one alphabetically, or positive if it
  1248. comes after it.
  1249. */
  1250. int compare (const tchar* const other) const throw();
  1251. /** Case-insensitive comparison with another string.
  1252. @returns 0 if the two strings are identical; negative if this string
  1253. comes before the other one alphabetically, or positive if it
  1254. comes after it.
  1255. */
  1256. int compareIgnoreCase (const tchar* const other) const throw();
  1257. /** Lexicographic comparison with another string.
  1258. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1259. characters, making it good for sorting human-readable strings.
  1260. @returns 0 if the two strings are identical; negative if this string
  1261. comes before the other one alphabetically, or positive if it
  1262. comes after it.
  1263. */
  1264. int compareLexicographically (const tchar* const other) const throw();
  1265. /** Tests whether the string begins with another string.
  1266. Uses a case-sensitive comparison.
  1267. */
  1268. bool startsWith (const tchar* const text) const throw();
  1269. /** Tests whether the string begins with a particular character.
  1270. Uses a case-sensitive comparison.
  1271. */
  1272. bool startsWithChar (const tchar character) const throw();
  1273. /** Tests whether the string begins with another string.
  1274. Uses a case-insensitive comparison.
  1275. */
  1276. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1277. /** Tests whether the string ends with another string.
  1278. Uses a case-sensitive comparison.
  1279. */
  1280. bool endsWith (const tchar* const text) const throw();
  1281. /** Tests whether the string ends with a particular character.
  1282. Uses a case-sensitive comparison.
  1283. */
  1284. bool endsWithChar (const tchar character) const throw();
  1285. /** Tests whether the string ends with another string.
  1286. Uses a case-insensitive comparison.
  1287. */
  1288. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1289. /** Tests whether the string contains another substring.
  1290. Uses a case-sensitive comparison.
  1291. */
  1292. bool contains (const tchar* const text) const throw();
  1293. /** Tests whether the string contains a particular character.
  1294. Uses a case-sensitive comparison.
  1295. */
  1296. bool containsChar (const tchar character) const throw();
  1297. /** Tests whether the string contains another substring.
  1298. Uses a case-insensitive comparison.
  1299. */
  1300. bool containsIgnoreCase (const tchar* const text) const throw();
  1301. /** Tests whether the string contains another substring as a distict word.
  1302. @returns true if the string contains this word, surrounded by
  1303. non-alphanumeric characters
  1304. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1305. */
  1306. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1307. /** Tests whether the string contains another substring as a distict word.
  1308. @returns true if the string contains this word, surrounded by
  1309. non-alphanumeric characters
  1310. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1311. */
  1312. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1313. /** Finds an instance of another substring if it exists as a distict word.
  1314. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1315. then this will return the index of the start of the substring. If it isn't
  1316. found, then it will return -1
  1317. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1318. */
  1319. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1320. /** Finds an instance of another substring if it exists as a distict word.
  1321. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1322. then this will return the index of the start of the substring. If it isn't
  1323. found, then it will return -1
  1324. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1325. */
  1326. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1327. /** Looks for any of a set of characters in the string.
  1328. Uses a case-sensitive comparison.
  1329. @returns true if the string contains any of the characters from
  1330. the string that is passed in.
  1331. */
  1332. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1333. /** Looks for a set of characters in the string.
  1334. Uses a case-sensitive comparison.
  1335. @returns true if the all the characters in the string are also found in the
  1336. string that is passed in.
  1337. */
  1338. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1339. /** Returns true if this string contains any non-whitespace characters.
  1340. This will return false if the string contains only whitespace characters, or
  1341. if it's empty.
  1342. It is equivalent to calling "myString.trim().isNotEmpty()".
  1343. */
  1344. bool containsNonWhitespaceChars() const throw();
  1345. /** Returns true if the string matches this simple wildcard expression.
  1346. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1347. This isn't a full-blown regex though! The only wildcard characters supported
  1348. are "*" and "?". It's mainly intended for filename pattern matching.
  1349. */
  1350. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1351. // Substring location methods..
  1352. /** Searches for a character inside this string.
  1353. Uses a case-sensitive comparison.
  1354. @returns the index of the first occurrence of the character in this
  1355. string, or -1 if it's not found.
  1356. */
  1357. int indexOfChar (const tchar characterToLookFor) const throw();
  1358. /** Searches for a character inside this string.
  1359. Uses a case-sensitive comparison.
  1360. @param startIndex the index from which the search should proceed
  1361. @param characterToLookFor the character to look for
  1362. @returns the index of the first occurrence of the character in this
  1363. string, or -1 if it's not found.
  1364. */
  1365. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1366. /** Returns the index of the first character that matches one of the characters
  1367. passed-in to this method.
  1368. This scans the string, beginning from the startIndex supplied, and if it finds
  1369. a character that appears in the string charactersToLookFor, it returns its index.
  1370. If none of these characters are found, it returns -1.
  1371. If ignoreCase is true, the comparison will be case-insensitive.
  1372. @see indexOfChar, lastIndexOfAnyOf
  1373. */
  1374. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1375. const int startIndex = 0,
  1376. const bool ignoreCase = false) const throw();
  1377. /** Searches for a substring within this string.
  1378. Uses a case-sensitive comparison.
  1379. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1380. */
  1381. int indexOf (const tchar* const text) const throw();
  1382. /** Searches for a substring within this string.
  1383. Uses a case-sensitive comparison.
  1384. @param startIndex the index from which the search should proceed
  1385. @param textToLookFor the string to search for
  1386. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1387. */
  1388. int indexOf (const int startIndex,
  1389. const tchar* const textToLookFor) const throw();
  1390. /** Searches for a substring within this string.
  1391. Uses a case-insensitive comparison.
  1392. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1393. */
  1394. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1395. /** Searches for a substring within this string.
  1396. Uses a case-insensitive comparison.
  1397. @param startIndex the index from which the search should proceed
  1398. @param textToLookFor the string to search for
  1399. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1400. */
  1401. int indexOfIgnoreCase (const int startIndex,
  1402. const tchar* const textToLookFor) const throw();
  1403. /** Searches for a character inside this string (working backwards from the end of the string).
  1404. Uses a case-sensitive comparison.
  1405. @returns the index of the last occurrence of the character in this
  1406. string, or -1 if it's not found.
  1407. */
  1408. int lastIndexOfChar (const tchar character) const throw();
  1409. /** Searches for a substring inside this string (working backwards from the end of the string).
  1410. Uses a case-sensitive comparison.
  1411. @returns the index of the start of the last occurrence of the
  1412. substring within this string, or -1 if it's not found.
  1413. */
  1414. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1415. /** Searches for a substring inside this string (working backwards from the end of the string).
  1416. Uses a case-insensitive comparison.
  1417. @returns the index of the start of the last occurrence of the
  1418. substring within this string, or -1 if it's not found.
  1419. */
  1420. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1421. /** Returns the index of the last character in this string that matches one of the
  1422. characters passed-in to this method.
  1423. This scans the string backwards, starting from its end, and if it finds
  1424. a character that appears in the string charactersToLookFor, it returns its index.
  1425. If none of these characters are found, it returns -1.
  1426. If ignoreCase is true, the comparison will be case-insensitive.
  1427. @see lastIndexOf, indexOfAnyOf
  1428. */
  1429. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1430. const bool ignoreCase = false) const throw();
  1431. // Substring extraction and manipulation methods..
  1432. /** Returns the character at this index in the string.
  1433. No checks are made to see if the index is within a valid range, so be careful!
  1434. */
  1435. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1436. /** Returns a character from the string such that it can also be altered.
  1437. This can be used as a way of easily changing characters in the string.
  1438. Note that the index passed-in is not checked to see whether it's in-range, so
  1439. be careful when using this.
  1440. */
  1441. tchar& operator[] (const int index) throw();
  1442. /** Returns the final character of the string.
  1443. If the string is empty this will return 0.
  1444. */
  1445. tchar getLastCharacter() const throw();
  1446. /** Returns a subsection of the string.
  1447. If the range specified is beyond the limits of the string, as much as
  1448. possible is returned.
  1449. @param startIndex the index of the start of the substring needed
  1450. @param endIndex all characters from startIndex up to (but not including)
  1451. this index are returned
  1452. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1453. */
  1454. const String substring (int startIndex,
  1455. int endIndex) const throw();
  1456. /** Returns a section of the string, starting from a given position.
  1457. @param startIndex the first character to include. If this is beyond the end
  1458. of the string, an empty string is returned. If it is zero or
  1459. less, the whole string is returned.
  1460. @returns the substring from startIndex up to the end of the string
  1461. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1462. */
  1463. const String substring (const int startIndex) const throw();
  1464. /** Returns a version of this string with a number of characters removed
  1465. from the end.
  1466. @param numberToDrop the number of characters to drop from the end of the
  1467. string. If this is greater than the length of the string,
  1468. an empty string will be returned. If zero or less, the
  1469. original string will be returned.
  1470. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1471. */
  1472. const String dropLastCharacters (const int numberToDrop) const throw();
  1473. /** Returns a section of the string starting from a given substring.
  1474. This will search for the first occurrence of the given substring, and
  1475. return the section of the string starting from the point where this is
  1476. found (optionally not including the substring itself).
  1477. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1478. fromFirstOccurrenceOf ("34", false) would return "56".
  1479. If the substring isn't found, the method will return an empty string.
  1480. If ignoreCase is true, the comparison will be case-insensitive.
  1481. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1482. */
  1483. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1484. const bool includeSubStringInResult,
  1485. const bool ignoreCase) const throw();
  1486. /** Returns a section of the string starting from the last occurrence of a given substring.
  1487. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1488. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1489. return the whole of the original string.
  1490. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1491. */
  1492. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1493. const bool includeSubStringInResult,
  1494. const bool ignoreCase) const throw();
  1495. /** Returns the start of this string, up to the first occurrence of a substring.
  1496. This will search for the first occurrence of a given substring, and then
  1497. return a copy of the string, up to the position of this substring,
  1498. optionally including or excluding the substring itself in the result.
  1499. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1500. upTo ("34", true) would return "1234".
  1501. If the substring isn't found, this will return the whole of the original string.
  1502. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1503. */
  1504. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1505. const bool includeSubStringInResult,
  1506. const bool ignoreCase) const throw();
  1507. /** Returns the start of this string, up to the last occurrence of a substring.
  1508. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1509. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1510. */
  1511. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1512. const bool includeSubStringInResult,
  1513. const bool ignoreCase) const throw();
  1514. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1515. const String trim() const throw();
  1516. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1517. const String trimStart() const throw();
  1518. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1519. const String trimEnd() const throw();
  1520. /** Returns an upper-case version of this string. */
  1521. const String toUpperCase() const throw();
  1522. /** Returns an lower-case version of this string. */
  1523. const String toLowerCase() const throw();
  1524. /** Replaces a sub-section of the string with another string.
  1525. This will return a copy of this string, with a set of characters
  1526. from startIndex to startIndex + numCharsToReplace removed, and with
  1527. a new string inserted in their place.
  1528. Note that this is a const method, and won't alter the string itself.
  1529. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1530. it will be constrained to a valid range.
  1531. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1532. characters will be taken out.
  1533. @param stringToInsert the new string to insert at startIndex after the characters have been
  1534. removed.
  1535. */
  1536. const String replaceSection (int startIndex,
  1537. int numCharactersToReplace,
  1538. const tchar* const stringToInsert) const throw();
  1539. /** Replaces all occurrences of a substring with another string.
  1540. Returns a copy of this string, with any occurrences of stringToReplace
  1541. swapped for stringToInsertInstead.
  1542. Note that this is a const method, and won't alter the string itself.
  1543. */
  1544. const String replace (const tchar* const stringToReplace,
  1545. const tchar* const stringToInsertInstead,
  1546. const bool ignoreCase = false) const throw();
  1547. /** Returns a string with all occurrences of a character replaced with a different one. */
  1548. const String replaceCharacter (const tchar characterToReplace,
  1549. const tchar characterToInsertInstead) const throw();
  1550. /** Replaces a set of characters with another set.
  1551. Returns a string in which each character from charactersToReplace has been replaced
  1552. by the character at the equivalent position in newCharacters (so the two strings
  1553. passed in must be the same length).
  1554. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1555. Note that this is a const method, and won't affect the string itself.
  1556. */
  1557. const String replaceCharacters (const String& charactersToReplace,
  1558. const tchar* const charactersToInsertInstead) const throw();
  1559. /** Returns a version of this string that only retains a fixed set of characters.
  1560. This will return a copy of this string, omitting any characters which are not
  1561. found in the string passed-in.
  1562. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1563. Note that this is a const method, and won't alter the string itself.
  1564. */
  1565. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1566. /** Returns a version of this string with a set of characters removed.
  1567. This will return a copy of this string, omitting any characters which are
  1568. found in the string passed-in.
  1569. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1570. Note that this is a const method, and won't alter the string itself.
  1571. */
  1572. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1573. /** Returns a section from the start of the string that only contains a certain set of characters.
  1574. This returns the leftmost section of the string, up to (and not including) the
  1575. first character that doesn't appear in the string passed in.
  1576. */
  1577. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1578. /** Returns a section from the start of the string that only contains a certain set of characters.
  1579. This returns the leftmost section of the string, up to (and not including) the
  1580. first character that occurs in the string passed in.
  1581. */
  1582. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1583. /** Checks whether the string might be in quotation marks.
  1584. @returns true if the string begins with a quote character (either a double or single quote).
  1585. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1586. @see unquoted, quoted
  1587. */
  1588. bool isQuotedString() const throw();
  1589. /** Removes quotation marks from around the string, (if there are any).
  1590. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1591. at the ends of the string are not affected. If there aren't any quotes, the original string
  1592. is returned.
  1593. Note that this is a const method, and won't alter the string itself.
  1594. @see isQuotedString, quoted
  1595. */
  1596. const String unquoted() const throw();
  1597. /** Adds quotation marks around a string.
  1598. This will return a copy of the string with a quote at the start and end, (but won't
  1599. add the quote if there's already one there, so it's safe to call this on strings that
  1600. may already have quotes around them).
  1601. Note that this is a const method, and won't alter the string itself.
  1602. @param quoteCharacter the character to add at the start and end
  1603. @see isQuotedString, unquoted
  1604. */
  1605. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1606. /** Writes text into this string, using printf style-arguments.
  1607. This will replace the contents of the string with the output of this
  1608. formatted printf.
  1609. Note that using the %s token with a juce string is probably a bad idea, as
  1610. this may expect differect encodings on different platforms.
  1611. @see formatted
  1612. */
  1613. void printf (const tchar* const format, ...) throw();
  1614. /** Returns a string, created using arguments in the style of printf.
  1615. This will return a string which is the result of a sprintf using the
  1616. arguments passed-in.
  1617. Note that using the %s token with a juce string is probably a bad idea, as
  1618. this may expect differect encodings on different platforms.
  1619. @see printf, vprintf
  1620. */
  1621. static const String formatted (const tchar* const format, ...) throw();
  1622. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1623. This will replace the contents of the string with the output of this
  1624. formatted printf. Used by other methods, this is public in case it's
  1625. useful for other purposes where you want to pass a va_list through directly.
  1626. Note that using the %s token with a juce string is probably a bad idea, as
  1627. this may expect differect encodings on different platforms.
  1628. @see printf, formatted
  1629. */
  1630. void vprintf (const tchar* const format, va_list& args) throw();
  1631. /** Creates a string which is a version of a string repeated and joined together.
  1632. @param stringToRepeat the string to repeat
  1633. @param numberOfTimesToRepeat how many times to repeat it
  1634. */
  1635. static const String repeatedString (const tchar* const stringToRepeat,
  1636. int numberOfTimesToRepeat) throw();
  1637. /** Creates a string from data in an unknown format.
  1638. This looks at some binary data and tries to guess whether it's Unicode
  1639. or 8-bit characters, then returns a string that represents it correctly.
  1640. Should be able to handle Unicode endianness correctly, by looking at
  1641. the first two bytes.
  1642. */
  1643. static const String createStringFromData (const void* const data,
  1644. const int size) throw();
  1645. // Numeric conversions..
  1646. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1647. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1648. */
  1649. explicit String (const int decimalInteger) throw();
  1650. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1651. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1652. */
  1653. explicit String (const unsigned int decimalInteger) throw();
  1654. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1655. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1656. */
  1657. explicit String (const short decimalInteger) throw();
  1658. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1659. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1660. */
  1661. explicit String (const unsigned short decimalInteger) throw();
  1662. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1663. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1664. */
  1665. explicit String (const int64 largeIntegerValue) throw();
  1666. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1667. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1668. */
  1669. explicit String (const uint64 largeIntegerValue) throw();
  1670. /** Creates a string representing this floating-point number.
  1671. @param floatValue the value to convert to a string
  1672. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1673. decimal places, and will not use exponent notation. If 0 or
  1674. less, it will use exponent notation if necessary.
  1675. @see getDoubleValue, getIntValue
  1676. */
  1677. explicit String (const float floatValue,
  1678. const int numberOfDecimalPlaces = 0) throw();
  1679. /** Creates a string representing this floating-point number.
  1680. @param doubleValue the value to convert to a string
  1681. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1682. decimal places, and will not use exponent notation. If 0 or
  1683. less, it will use exponent notation if necessary.
  1684. @see getFloatValue, getIntValue
  1685. */
  1686. explicit String (const double doubleValue,
  1687. const int numberOfDecimalPlaces = 0) throw();
  1688. /** Parses this string to find its numerical value (up to 32 bits in size).
  1689. @returns the value of the string as a 32 bit signed base-10 integer.
  1690. @see getTrailingIntValue, getHexValue32, getHexValue64
  1691. */
  1692. int getIntValue() const throw();
  1693. /** Parses this string to find its numerical value (up to 64 bits in size).
  1694. @returns the value of the string as a 64 bit signed base-10 integer.
  1695. */
  1696. int64 getLargeIntValue() const throw();
  1697. /** Parses a decimal number from the end of the string.
  1698. This will look for a value at the end of the string.
  1699. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1700. Negative numbers are not handled, so "xyz-5" returns 5.
  1701. @see getIntValue
  1702. */
  1703. int getTrailingIntValue() const throw();
  1704. /** Parses this string as a floating point number.
  1705. @returns the value of the string as a 32-bit floating point value.
  1706. @see getDoubleValue
  1707. */
  1708. float getFloatValue() const throw();
  1709. /** Parses this string as a floating point number.
  1710. @returns the value of the string as a 64-bit floating point value.
  1711. @see getFloatValue
  1712. */
  1713. double getDoubleValue() const throw();
  1714. /** Parses the string as a hexadecimal number.
  1715. Non-hexadecimal characters in the string are ignored.
  1716. If the string contains too many characters, then the lowest significant
  1717. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1718. @returns a 32-bit number which is the value of the string in hex.
  1719. */
  1720. int getHexValue32() const throw();
  1721. /** Parses the string as a hexadecimal number.
  1722. Non-hexadecimal characters in the string are ignored.
  1723. If the string contains too many characters, then the lowest significant
  1724. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1725. @returns a 64-bit number which is the value of the string in hex.
  1726. */
  1727. int64 getHexValue64() const throw();
  1728. /** Creates a string representing this 32-bit value in hexadecimal. */
  1729. static const String toHexString (const int number) throw();
  1730. /** Creates a string representing this 64-bit value in hexadecimal. */
  1731. static const String toHexString (const int64 number) throw();
  1732. /** Creates a string representing this 16-bit value in hexadecimal. */
  1733. static const String toHexString (const short number) throw();
  1734. /** Creates a string containing a hex dump of a block of binary data.
  1735. @param data the binary data to use as input
  1736. @param size how many bytes of data to use
  1737. @param groupSize how many bytes are grouped together before inserting a
  1738. space into the output. e.g. group size 0 has no spaces,
  1739. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1740. like "bea1 c2ff".
  1741. */
  1742. static const String toHexString (const unsigned char* data,
  1743. const int size,
  1744. const int groupSize = 1) throw();
  1745. // Casting to character arrays..
  1746. #if JUCE_STRINGS_ARE_UNICODE
  1747. /** Returns a version of this string using the default 8-bit system encoding.
  1748. Because it returns a reference to the string's internal data, the pointer
  1749. that is returned must not be stored anywhere, as it can be deleted whenever the
  1750. string changes.
  1751. */
  1752. operator const char*() const throw();
  1753. /** Returns a unicode version of this string.
  1754. Because it returns a reference to the string's internal data, the pointer
  1755. that is returned must not be stored anywhere, as it can be deleted whenever the
  1756. string changes.
  1757. */
  1758. inline operator const juce_wchar*() const throw() { return text->text; }
  1759. #else
  1760. /** Returns a version of this string using the default 8-bit system encoding.
  1761. Because it returns a reference to the string's internal data, the pointer
  1762. that is returned must not be stored anywhere, as it can be deleted whenever the
  1763. string changes.
  1764. */
  1765. inline operator const char*() const throw() { return text->text; }
  1766. /** Returns a unicode version of this string.
  1767. Because it returns a reference to the string's internal data, the pointer
  1768. that is returned must not be stored anywhere, as it can be deleted whenever the
  1769. string changes.
  1770. */
  1771. operator const juce_wchar*() const throw();
  1772. #endif
  1773. /** Copies the string to a buffer.
  1774. @param destBuffer the place to copy it to
  1775. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1776. not including the tailing zero, so this shouldn't be
  1777. larger than the size of your destination buffer - 1
  1778. */
  1779. void copyToBuffer (char* const destBuffer,
  1780. const int maxCharsToCopy) const throw();
  1781. /** Copies the string to a unicode buffer.
  1782. @param destBuffer the place to copy it to
  1783. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1784. not including the tailing zero, so this shouldn't be
  1785. larger than the size of your destination buffer - 1
  1786. */
  1787. void copyToBuffer (juce_wchar* const destBuffer,
  1788. const int maxCharsToCopy) const throw();
  1789. /** Copies the string to a buffer as UTF-8 characters.
  1790. Returns the number of bytes copied to the buffer, including the terminating null
  1791. character.
  1792. @param destBuffer the place to copy it to; if this is a null pointer,
  1793. the method just returns the number of bytes required
  1794. (including the terminating null character).
  1795. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1796. string won't fit, it'll put in as many as it can while
  1797. still allowing for a terminating null char at the end,
  1798. and will return the number of bytes that were actually
  1799. used. If this value is < 0, no limit is used.
  1800. */
  1801. int copyToUTF8 (uint8* const destBuffer, const int maxBufferSizeBytes = 0x7fffffff) const throw();
  1802. /** Returns a pointer to a UTF-8 version of this string.
  1803. Because it returns a reference to the string's internal data, the pointer
  1804. that is returned must not be stored anywhere, as it can be deleted whenever the
  1805. string changes.
  1806. */
  1807. const char* toUTF8() const throw();
  1808. /** Creates a String from a UTF-8 encoded buffer.
  1809. If the size is < 0, it'll keep reading until it hits a zero.
  1810. */
  1811. static const String fromUTF8 (const uint8* const utf8buffer,
  1812. int bufferSizeBytes = -1) throw();
  1813. /** Increases the string's internally allocated storage.
  1814. Although the string's contents won't be affected by this call, it will
  1815. increase the amount of memory allocated internally for the string to grow into.
  1816. If you're about to make a large number of calls to methods such
  1817. as += or <<, it's more efficient to preallocate enough extra space
  1818. beforehand, so that these methods won't have to keep resizing the string
  1819. to append the extra characters.
  1820. @param numCharsNeeded the number of characters to allocate storage for. If this
  1821. value is less than the currently allocated size, it will
  1822. have no effect.
  1823. */
  1824. void preallocateStorage (const int numCharsNeeded) throw();
  1825. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1826. private:
  1827. struct InternalRefCountedStringHolder
  1828. {
  1829. int refCount;
  1830. int allocatedNumChars;
  1831. #if JUCE_STRINGS_ARE_UNICODE
  1832. wchar_t text[1];
  1833. #else
  1834. char text[1];
  1835. #endif
  1836. };
  1837. InternalRefCountedStringHolder* text;
  1838. static InternalRefCountedStringHolder emptyString;
  1839. // internal constructor that preallocates a certain amount of memory
  1840. String (const int numChars, const int dummyVariable) throw();
  1841. void deleteInternal() throw();
  1842. void createInternal (const int numChars) throw();
  1843. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1844. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1845. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1846. void dupeInternalIfMultiplyReferenced() throw();
  1847. };
  1848. /** Global operator to allow a String to be appended to a string literal.
  1849. This allows the use of expressions such as "abc" + String (x)
  1850. @see String
  1851. */
  1852. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1853. const String& string2) throw();
  1854. /** Global operator to allow a String to be appended to a string literal.
  1855. This allows the use of expressions such as "abc" + String (x)
  1856. @see String
  1857. */
  1858. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1859. const String& string2) throw();
  1860. #endif // __JUCE_STRING_JUCEHEADER__
  1861. /********* End of inlined file: juce_String.h *********/
  1862. /**
  1863. Acts as an application-wide logging class.
  1864. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1865. method and this will then be used by all calls to writeToLog.
  1866. The logger class also contains methods for writing messages to the debugger's
  1867. output stream.
  1868. @see FileLogger
  1869. */
  1870. class JUCE_API Logger
  1871. {
  1872. public:
  1873. /** Destructor. */
  1874. virtual ~Logger();
  1875. /** Sets the current logging class to use.
  1876. Note that the object passed in won't be deleted when no longer needed.
  1877. A null pointer can be passed-in to disable any logging.
  1878. If deleteOldLogger is set to true, the existing logger will be
  1879. deleted (if there is one).
  1880. */
  1881. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1882. const bool deleteOldLogger = false);
  1883. /** Writes a string to the current logger.
  1884. This will pass the string to the logger's logMessage() method if a logger
  1885. has been set.
  1886. @see logMessage
  1887. */
  1888. static void JUCE_CALLTYPE writeToLog (const String& message);
  1889. /** Writes a message to the standard error stream.
  1890. This can be called directly, or by using the DBG() macro in
  1891. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1892. */
  1893. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1894. /** Writes a message to the standard error stream.
  1895. This can be called directly, or by using the DBG_PRINTF() macro in
  1896. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1897. */
  1898. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1899. protected:
  1900. Logger();
  1901. /** This is overloaded by subclasses to implement custom logging behaviour.
  1902. @see setCurrentLogger
  1903. */
  1904. virtual void logMessage (const String& message) = 0;
  1905. };
  1906. #endif // __JUCE_LOGGER_JUCEHEADER__
  1907. /********* End of inlined file: juce_Logger.h *********/
  1908. END_JUCE_NAMESPACE
  1909. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1910. /********* End of inlined file: juce_StandardHeader.h *********/
  1911. BEGIN_JUCE_NAMESPACE
  1912. #if JUCE_MSVC
  1913. // this is set explicitly in case the app is using a different packing size.
  1914. #pragma pack (push, 8)
  1915. #pragma warning (push)
  1916. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1917. #endif
  1918. #if JUCE_MAC
  1919. #pragma align=natural
  1920. #endif
  1921. #define JUCE_PUBLIC_INCLUDES
  1922. // this is where all the class header files get brought in..
  1923. /********* Start of inlined file: juce_core_includes.h *********/
  1924. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1925. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1926. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  1927. /********* Start of inlined file: juce_Initialisation.h *********/
  1928. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  1929. #define __JUCE_INITIALISATION_JUCEHEADER__
  1930. /** Initialises Juce's GUI classes.
  1931. If you're embedding Juce into an application that uses its own event-loop rather
  1932. than using the START_JUCE_APPLICATION macro, call this function before making any
  1933. Juce calls, to make sure things are initialised correctly.
  1934. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  1935. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  1936. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  1937. */
  1938. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  1939. /** Clears up any static data being used by Juce's GUI classes.
  1940. If you're embedding Juce into an application that uses its own event-loop rather
  1941. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  1942. code to clean up any juce objects that might be lying around.
  1943. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  1944. */
  1945. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  1946. /** Initialises the core parts of Juce.
  1947. If you're embedding Juce into either a command-line program, call this function
  1948. at the start of your main() function to make sure that Juce is initialised correctly.
  1949. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  1950. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  1951. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  1952. */
  1953. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  1954. /** Clears up any static data being used by Juce's non-gui core classes.
  1955. If you're embedding Juce into either a command-line program, call this function
  1956. at the end of your main() function if you want to make sure any Juce objects are
  1957. cleaned up correctly.
  1958. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  1959. */
  1960. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  1961. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  1962. /********* End of inlined file: juce_Initialisation.h *********/
  1963. #endif
  1964. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1965. #endif
  1966. #ifndef __JUCE_MEMORY_JUCEHEADER__
  1967. #endif
  1968. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  1969. #endif
  1970. #ifndef __JUCE_RANDOM_JUCEHEADER__
  1971. /********* Start of inlined file: juce_Random.h *********/
  1972. #ifndef __JUCE_RANDOM_JUCEHEADER__
  1973. #define __JUCE_RANDOM_JUCEHEADER__
  1974. /********* Start of inlined file: juce_BitArray.h *********/
  1975. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  1976. #define __JUCE_BITARRAY_JUCEHEADER__
  1977. /********* Start of inlined file: juce_Array.h *********/
  1978. #ifndef __JUCE_ARRAY_JUCEHEADER__
  1979. #define __JUCE_ARRAY_JUCEHEADER__
  1980. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  1981. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  1982. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  1983. /** The default size of chunk in which arrays increase their storage.
  1984. Used by ArrayAllocationBase and its subclasses.
  1985. */
  1986. const int juceDefaultArrayGranularity = 8;
  1987. /**
  1988. Implements some basic array storage allocation functions.
  1989. This class isn't really for public use - it's used by the other
  1990. array classes, but might come in handy for some purposes.
  1991. @see Array, OwnedArray, ReferenceCountedArray
  1992. */
  1993. template <class ElementType>
  1994. class ArrayAllocationBase
  1995. {
  1996. protected:
  1997. /** Creates an empty array.
  1998. @param granularity_ this is the size of increment by which the internal storage
  1999. will be increased.
  2000. */
  2001. ArrayAllocationBase (const int granularity_) throw()
  2002. : elements (0),
  2003. numAllocated (0),
  2004. granularity (granularity_)
  2005. {
  2006. jassert (granularity > 0);
  2007. }
  2008. /** Destructor. */
  2009. ~ArrayAllocationBase() throw()
  2010. {
  2011. delete[] elements;
  2012. }
  2013. /** Changes the amount of storage allocated.
  2014. This will retain any data currently held in the array, and either add or
  2015. remove extra space at the end.
  2016. @param numElements the number of elements that are needed
  2017. */
  2018. void setAllocatedSize (const int numElements) throw()
  2019. {
  2020. if (numAllocated != numElements)
  2021. {
  2022. if (numElements > 0)
  2023. {
  2024. ElementType* const newElements = new ElementType [numElements];
  2025. const int itemsToRetain = jmin (numElements, numAllocated);
  2026. for (int i = 0; i < itemsToRetain; ++i)
  2027. newElements[i] = elements[i];
  2028. delete[] elements;
  2029. elements = newElements;
  2030. }
  2031. else if (elements != 0)
  2032. {
  2033. delete[] elements;
  2034. elements = 0;
  2035. }
  2036. numAllocated = numElements;
  2037. }
  2038. }
  2039. /** Increases the amount of storage allocated if it is less than a given amount.
  2040. This will retain any data currently held in the array, but will add
  2041. extra space at the end to make sure there it's at least as big as the size
  2042. passed in. If it's already bigger, no action is taken.
  2043. @param minNumElements the minimum number of elements that are needed
  2044. */
  2045. void ensureAllocatedSize (int minNumElements) throw()
  2046. {
  2047. if (minNumElements > numAllocated)
  2048. {
  2049. // for arrays with small granularity that get big, start
  2050. // increasing the size in bigger jumps
  2051. if (minNumElements > (granularity << 6))
  2052. {
  2053. minNumElements += (minNumElements / granularity);
  2054. if (minNumElements > (granularity << 8))
  2055. minNumElements += granularity << 6;
  2056. else
  2057. minNumElements += granularity << 5;
  2058. }
  2059. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2060. }
  2061. }
  2062. ElementType* elements;
  2063. int numAllocated, granularity;
  2064. private:
  2065. ArrayAllocationBase (const ArrayAllocationBase&);
  2066. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2067. };
  2068. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2069. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2070. /********* Start of inlined file: juce_ElementComparator.h *********/
  2071. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2072. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2073. /**
  2074. Sorts a range of elements in an array.
  2075. The comparator object that is passed-in must define a public method with the following
  2076. signature:
  2077. @code
  2078. int compareElements (ElementType first, ElementType second);
  2079. @endcode
  2080. ..and this method must return:
  2081. - a value of < 0 if the first comes before the second
  2082. - a value of 0 if the two objects are equivalent
  2083. - a value of > 0 if the second comes before the first
  2084. To improve performance, the compareElements() method can be declared as static or const.
  2085. @param comparator an object which defines a compareElements() method
  2086. @param array the array to sort
  2087. @param firstElement the index of the first element of the range to be sorted
  2088. @param lastElement the index of the last element in the range that needs
  2089. sorting (this is inclusive)
  2090. @param retainOrderOfEquivalentItems if true, the order of items that the
  2091. comparator deems the same will be maintained - this will be
  2092. a slower algorithm than if they are allowed to be moved around.
  2093. @see sortArrayRetainingOrder
  2094. */
  2095. template <class ElementType, class ElementComparator>
  2096. static void sortArray (ElementComparator& comparator,
  2097. ElementType* const array,
  2098. int firstElement,
  2099. int lastElement,
  2100. const bool retainOrderOfEquivalentItems)
  2101. {
  2102. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2103. // avoids getting warning messages about the parameter being unused
  2104. if (lastElement > firstElement)
  2105. {
  2106. if (retainOrderOfEquivalentItems)
  2107. {
  2108. for (int i = firstElement; i < lastElement; ++i)
  2109. {
  2110. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2111. {
  2112. const ElementType temp = array [i];
  2113. array [i] = array[i + 1];
  2114. array [i + 1] = temp;
  2115. if (i > firstElement)
  2116. i -= 2;
  2117. }
  2118. }
  2119. }
  2120. else
  2121. {
  2122. int fromStack[30], toStack[30];
  2123. int stackIndex = 0;
  2124. for (;;)
  2125. {
  2126. const int size = (lastElement - firstElement) + 1;
  2127. if (size <= 8)
  2128. {
  2129. int j = lastElement;
  2130. int maxIndex;
  2131. while (j > firstElement)
  2132. {
  2133. maxIndex = firstElement;
  2134. for (int k = firstElement + 1; k <= j; ++k)
  2135. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2136. maxIndex = k;
  2137. const ElementType temp = array [maxIndex];
  2138. array [maxIndex] = array[j];
  2139. array [j] = temp;
  2140. --j;
  2141. }
  2142. }
  2143. else
  2144. {
  2145. const int mid = firstElement + (size >> 1);
  2146. ElementType temp = array [mid];
  2147. array [mid] = array [firstElement];
  2148. array [firstElement] = temp;
  2149. int i = firstElement;
  2150. int j = lastElement + 1;
  2151. for (;;)
  2152. {
  2153. while (++i <= lastElement
  2154. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2155. {}
  2156. while (--j > firstElement
  2157. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2158. {}
  2159. if (j < i)
  2160. break;
  2161. temp = array[i];
  2162. array[i] = array[j];
  2163. array[j] = temp;
  2164. }
  2165. temp = array [firstElement];
  2166. array [firstElement] = array[j];
  2167. array [j] = temp;
  2168. if (j - 1 - firstElement >= lastElement - i)
  2169. {
  2170. if (firstElement + 1 < j)
  2171. {
  2172. fromStack [stackIndex] = firstElement;
  2173. toStack [stackIndex] = j - 1;
  2174. ++stackIndex;
  2175. }
  2176. if (i < lastElement)
  2177. {
  2178. firstElement = i;
  2179. continue;
  2180. }
  2181. }
  2182. else
  2183. {
  2184. if (i < lastElement)
  2185. {
  2186. fromStack [stackIndex] = i;
  2187. toStack [stackIndex] = lastElement;
  2188. ++stackIndex;
  2189. }
  2190. if (firstElement + 1 < j)
  2191. {
  2192. lastElement = j - 1;
  2193. continue;
  2194. }
  2195. }
  2196. }
  2197. if (--stackIndex < 0)
  2198. break;
  2199. jassert (stackIndex < numElementsInArray (fromStack));
  2200. firstElement = fromStack [stackIndex];
  2201. lastElement = toStack [stackIndex];
  2202. }
  2203. }
  2204. }
  2205. }
  2206. /**
  2207. Searches a sorted array of elements, looking for the index at which a specified value
  2208. should be inserted for it to be in the correct order.
  2209. The comparator object that is passed-in must define a public method with the following
  2210. signature:
  2211. @code
  2212. int compareElements (ElementType first, ElementType second);
  2213. @endcode
  2214. ..and this method must return:
  2215. - a value of < 0 if the first comes before the second
  2216. - a value of 0 if the two objects are equivalent
  2217. - a value of > 0 if the second comes before the first
  2218. To improve performance, the compareElements() method can be declared as static or const.
  2219. @param comparator an object which defines a compareElements() method
  2220. @param array the array to search
  2221. @param newElement the value that is going to be inserted
  2222. @param firstElement the index of the first element to search
  2223. @param lastElement the index of the last element in the range (this is non-inclusive)
  2224. */
  2225. template <class ElementType, class ElementComparator>
  2226. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2227. ElementType* const array,
  2228. const ElementType newElement,
  2229. int firstElement,
  2230. int lastElement)
  2231. {
  2232. jassert (firstElement <= lastElement);
  2233. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2234. // avoids getting warning messages about the parameter being unused
  2235. while (firstElement < lastElement)
  2236. {
  2237. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2238. {
  2239. ++firstElement;
  2240. break;
  2241. }
  2242. else
  2243. {
  2244. const int halfway = (firstElement + lastElement) >> 1;
  2245. if (halfway == firstElement)
  2246. {
  2247. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2248. ++firstElement;
  2249. break;
  2250. }
  2251. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2252. {
  2253. firstElement = halfway;
  2254. }
  2255. else
  2256. {
  2257. lastElement = halfway;
  2258. }
  2259. }
  2260. }
  2261. return firstElement;
  2262. }
  2263. /**
  2264. A simple ElementComparator class that can be used to sort an array of
  2265. integer primitive objects.
  2266. Example: @code
  2267. Array <int> myArray;
  2268. IntegerElementComparator<int> sorter;
  2269. myArray.sort (sorter);
  2270. @endcode
  2271. For floating point values, see the FloatElementComparator class instead.
  2272. @see FloatElementComparator, ElementComparator
  2273. */
  2274. template <class ElementType>
  2275. class IntegerElementComparator
  2276. {
  2277. public:
  2278. static int compareElements (const ElementType first,
  2279. const ElementType second) throw()
  2280. {
  2281. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2282. }
  2283. };
  2284. /**
  2285. A simple ElementComparator class that can be used to sort an array of numeric
  2286. double or floating point primitive objects.
  2287. Example: @code
  2288. Array <double> myArray;
  2289. FloatElementComparator<double> sorter;
  2290. myArray.sort (sorter);
  2291. @endcode
  2292. For integer values, see the IntegerElementComparator class instead.
  2293. @see IntegerElementComparator, ElementComparator
  2294. */
  2295. template <class ElementType>
  2296. class FloatElementComparator
  2297. {
  2298. public:
  2299. static int compareElements (const ElementType first,
  2300. const ElementType second) throw()
  2301. {
  2302. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2303. }
  2304. };
  2305. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2306. /********* End of inlined file: juce_ElementComparator.h *********/
  2307. /********* Start of inlined file: juce_CriticalSection.h *********/
  2308. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2309. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2310. /**
  2311. Prevents multiple threads from accessing shared objects at the same time.
  2312. @see ScopedLock, Thread, InterProcessLock
  2313. */
  2314. class JUCE_API CriticalSection
  2315. {
  2316. public:
  2317. /**
  2318. Creates a CriticalSection object
  2319. */
  2320. CriticalSection() throw();
  2321. /** Destroys a CriticalSection object.
  2322. If the critical section is deleted whilst locked, its subsequent behaviour
  2323. is unpredictable.
  2324. */
  2325. ~CriticalSection() throw();
  2326. /** Locks this critical section.
  2327. If the lock is currently held by another thread, this will wait until it
  2328. becomes free.
  2329. If the lock is already held by the caller thread, the method returns immediately.
  2330. @see exit, ScopedLock
  2331. */
  2332. void enter() const throw();
  2333. /** Attempts to lock this critical section without blocking.
  2334. This method behaves identically to CriticalSection::enter, except that the caller thread
  2335. does not wait if the lock is currently held by another thread but returns false immediately.
  2336. @returns false if the lock is currently held by another thread, true otherwise.
  2337. @see enter
  2338. */
  2339. bool tryEnter() const throw();
  2340. /** Releases the lock.
  2341. If the caller thread hasn't got the lock, this can have unpredictable results.
  2342. If the enter() method has been called multiple times by the thread, each
  2343. call must be matched by a call to exit() before other threads will be allowed
  2344. to take over the lock.
  2345. @see enter, ScopedLock
  2346. */
  2347. void exit() const throw();
  2348. juce_UseDebuggingNewOperator
  2349. private:
  2350. #if JUCE_WIN32
  2351. #if JUCE_64BIT
  2352. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2353. // block of memory here that's big enough to be used internally as a windows critical
  2354. // section object.
  2355. uint8 internal [44];
  2356. #else
  2357. uint8 internal [24];
  2358. #endif
  2359. #else
  2360. mutable pthread_mutex_t internal;
  2361. #endif
  2362. CriticalSection (const CriticalSection&);
  2363. const CriticalSection& operator= (const CriticalSection&);
  2364. };
  2365. /**
  2366. A class that can be used in place of a real CriticalSection object.
  2367. This is currently used by some templated array classes, and should get
  2368. optimised out by the compiler.
  2369. @see Array, OwnedArray, ReferenceCountedArray
  2370. */
  2371. class JUCE_API DummyCriticalSection
  2372. {
  2373. public:
  2374. forcedinline DummyCriticalSection() throw() {}
  2375. forcedinline ~DummyCriticalSection() throw() {}
  2376. forcedinline void enter() const throw() {}
  2377. forcedinline void exit() const throw() {}
  2378. };
  2379. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2380. /********* End of inlined file: juce_CriticalSection.h *********/
  2381. /**
  2382. Holds a list of primitive objects, such as ints, doubles, or pointers.
  2383. Examples of arrays are: Array<int> or Array<MyClass*>
  2384. Note that when holding pointers to objects, the array doesn't take any ownership
  2385. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  2386. If you're using a class or struct as the element type, it must be
  2387. capable of being copied or moved with a straightforward memcpy, rather than
  2388. needing construction and destruction code.
  2389. For holding lists of strings, use the specialised class StringArray.
  2390. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2391. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2392. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2393. */
  2394. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2395. class Array : private ArrayAllocationBase <ElementType>
  2396. {
  2397. public:
  2398. /** Creates an empty array.
  2399. @param granularity this is the size of increment by which the internal storage
  2400. used by the array will grow. Only change it from the default if you know the
  2401. array is going to be very big and needs to be able to grow efficiently.
  2402. @see ArrayAllocationBase
  2403. */
  2404. Array (const int granularity = juceDefaultArrayGranularity) throw()
  2405. : ArrayAllocationBase <ElementType> (granularity),
  2406. numUsed (0)
  2407. {
  2408. }
  2409. /** Creates a copy of another array.
  2410. @param other the array to copy
  2411. */
  2412. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2413. : ArrayAllocationBase <ElementType> (other.granularity)
  2414. {
  2415. other.lockArray();
  2416. numUsed = other.numUsed;
  2417. this->setAllocatedSize (other.numUsed);
  2418. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  2419. other.unlockArray();
  2420. }
  2421. /** Initalises from a null-terminated C array of values.
  2422. @param values the array to copy from
  2423. */
  2424. Array (const ElementType* values) throw()
  2425. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  2426. numUsed (0)
  2427. {
  2428. while (*values != 0)
  2429. add (*values++);
  2430. }
  2431. /** Initalises from a C array of values.
  2432. @param values the array to copy from
  2433. @param numValues the number of values in the array
  2434. */
  2435. Array (const ElementType* values, int numValues) throw()
  2436. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  2437. numUsed (numValues)
  2438. {
  2439. this->setAllocatedSize (numValues);
  2440. memcpy (this->elements, values, numValues * sizeof (ElementType));
  2441. }
  2442. /** Destructor. */
  2443. ~Array() throw()
  2444. {
  2445. }
  2446. /** Copies another array.
  2447. @param other the array to copy
  2448. */
  2449. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2450. {
  2451. if (this != &other)
  2452. {
  2453. other.lockArray();
  2454. lock.enter();
  2455. this->granularity = other.granularity;
  2456. this->ensureAllocatedSize (other.size());
  2457. numUsed = other.numUsed;
  2458. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  2459. minimiseStorageOverheads();
  2460. lock.exit();
  2461. other.unlockArray();
  2462. }
  2463. return *this;
  2464. }
  2465. /** Compares this array to another one.
  2466. Two arrays are considered equal if they both contain the same set of
  2467. elements, in the same order.
  2468. @param other the other array to compare with
  2469. */
  2470. template <class OtherArrayType>
  2471. bool operator== (const OtherArrayType& other) const throw()
  2472. {
  2473. lock.enter();
  2474. if (this->numUsed != other.numUsed)
  2475. {
  2476. lock.exit();
  2477. return false;
  2478. }
  2479. for (int i = numUsed; --i >= 0;)
  2480. {
  2481. if (this->elements [i] != other.elements [i])
  2482. {
  2483. lock.exit();
  2484. return false;
  2485. }
  2486. }
  2487. lock.exit();
  2488. return true;
  2489. }
  2490. /** Compares this array to another one.
  2491. Two arrays are considered equal if they both contain the same set of
  2492. elements, in the same order.
  2493. @param other the other array to compare with
  2494. */
  2495. template <class OtherArrayType>
  2496. bool operator!= (const OtherArrayType& other) const throw()
  2497. {
  2498. return ! operator== (other);
  2499. }
  2500. /** Removes all elements from the array.
  2501. This will remove all the elements, and free any storage that the array is
  2502. using. To clear the array without freeing the storage, use the clearQuick()
  2503. method instead.
  2504. @see clearQuick
  2505. */
  2506. void clear() throw()
  2507. {
  2508. lock.enter();
  2509. this->setAllocatedSize (0);
  2510. numUsed = 0;
  2511. lock.exit();
  2512. }
  2513. /** Removes all elements from the array without freeing the array's allocated storage.
  2514. @see clear
  2515. */
  2516. void clearQuick() throw()
  2517. {
  2518. lock.enter();
  2519. numUsed = 0;
  2520. lock.exit();
  2521. }
  2522. /** Returns the current number of elements in the array.
  2523. */
  2524. inline int size() const throw()
  2525. {
  2526. return numUsed;
  2527. }
  2528. /** Returns one of the elements in the array.
  2529. If the index passed in is beyond the range of valid elements, this
  2530. will return zero.
  2531. If you're certain that the index will always be a valid element, you
  2532. can call getUnchecked() instead, which is faster.
  2533. @param index the index of the element being requested (0 is the first element in the array)
  2534. @see getUnchecked, getFirst, getLast
  2535. */
  2536. inline ElementType operator[] (const int index) const throw()
  2537. {
  2538. lock.enter();
  2539. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  2540. ? this->elements [index]
  2541. : ElementType();
  2542. lock.exit();
  2543. return result;
  2544. }
  2545. /** Returns one of the elements in the array, without checking the index passed in.
  2546. Unlike the operator[] method, this will try to return an element without
  2547. checking that the index is within the bounds of the array, so should only
  2548. be used when you're confident that it will always be a valid index.
  2549. @param index the index of the element being requested (0 is the first element in the array)
  2550. @see operator[], getFirst, getLast
  2551. */
  2552. inline ElementType getUnchecked (const int index) const throw()
  2553. {
  2554. lock.enter();
  2555. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2556. const ElementType result = this->elements [index];
  2557. lock.exit();
  2558. return result;
  2559. }
  2560. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2561. This is like getUnchecked, but returns a direct reference to the element, so that
  2562. you can alter it directly. Obviously this can be dangerous, so only use it when
  2563. absolutely necessary.
  2564. @param index the index of the element being requested (0 is the first element in the array)
  2565. @see operator[], getFirst, getLast
  2566. */
  2567. inline ElementType& getReference (const int index) const throw()
  2568. {
  2569. lock.enter();
  2570. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2571. ElementType& result = this->elements [index];
  2572. lock.exit();
  2573. return result;
  2574. }
  2575. /** Returns the first element in the array, or 0 if the array is empty.
  2576. @see operator[], getUnchecked, getLast
  2577. */
  2578. inline ElementType getFirst() const throw()
  2579. {
  2580. lock.enter();
  2581. const ElementType result = (numUsed > 0) ? this->elements [0]
  2582. : ElementType();
  2583. lock.exit();
  2584. return result;
  2585. }
  2586. /** Returns the last element in the array, or 0 if the array is empty.
  2587. @see operator[], getUnchecked, getFirst
  2588. */
  2589. inline ElementType getLast() const throw()
  2590. {
  2591. lock.enter();
  2592. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  2593. : ElementType();
  2594. lock.exit();
  2595. return result;
  2596. }
  2597. /** Finds the index of the first element which matches the value passed in.
  2598. This will search the array for the given object, and return the index
  2599. of its first occurrence. If the object isn't found, the method will return -1.
  2600. @param elementToLookFor the value or object to look for
  2601. @returns the index of the object, or -1 if it's not found
  2602. */
  2603. int indexOf (const ElementType elementToLookFor) const throw()
  2604. {
  2605. int result = -1;
  2606. lock.enter();
  2607. const ElementType* e = this->elements;
  2608. for (int i = numUsed; --i >= 0;)
  2609. {
  2610. if (elementToLookFor == *e)
  2611. {
  2612. result = (int) (e - this->elements);
  2613. break;
  2614. }
  2615. ++e;
  2616. }
  2617. lock.exit();
  2618. return result;
  2619. }
  2620. /** Returns true if the array contains at least one occurrence of an object.
  2621. @param elementToLookFor the value or object to look for
  2622. @returns true if the item is found
  2623. */
  2624. bool contains (const ElementType elementToLookFor) const throw()
  2625. {
  2626. lock.enter();
  2627. const ElementType* e = this->elements;
  2628. int num = numUsed;
  2629. while (num >= 4)
  2630. {
  2631. if (*e == elementToLookFor
  2632. || *++e == elementToLookFor
  2633. || *++e == elementToLookFor
  2634. || *++e == elementToLookFor)
  2635. {
  2636. lock.exit();
  2637. return true;
  2638. }
  2639. num -= 4;
  2640. ++e;
  2641. }
  2642. while (num > 0)
  2643. {
  2644. if (elementToLookFor == *e)
  2645. {
  2646. lock.exit();
  2647. return true;
  2648. }
  2649. --num;
  2650. ++e;
  2651. }
  2652. lock.exit();
  2653. return false;
  2654. }
  2655. /** Appends a new element at the end of the array.
  2656. @param newElement the new object to add to the array
  2657. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  2658. */
  2659. void add (const ElementType newElement) throw()
  2660. {
  2661. lock.enter();
  2662. this->ensureAllocatedSize (numUsed + 1);
  2663. this->elements [numUsed++] = newElement;
  2664. lock.exit();
  2665. }
  2666. /** Inserts a new element into the array at a given position.
  2667. If the index is less than 0 or greater than the size of the array, the
  2668. element will be added to the end of the array.
  2669. Otherwise, it will be inserted into the array, moving all the later elements
  2670. along to make room.
  2671. @param indexToInsertAt the index at which the new element should be
  2672. inserted (pass in -1 to add it to the end)
  2673. @param newElement the new object to add to the array
  2674. @see add, addSorted, set
  2675. */
  2676. void insert (int indexToInsertAt, const ElementType newElement) throw()
  2677. {
  2678. lock.enter();
  2679. this->ensureAllocatedSize (numUsed + 1);
  2680. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2681. {
  2682. ElementType* const insertPos = this->elements + indexToInsertAt;
  2683. const int numberToMove = numUsed - indexToInsertAt;
  2684. if (numberToMove > 0)
  2685. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2686. *insertPos = newElement;
  2687. ++numUsed;
  2688. }
  2689. else
  2690. {
  2691. this->elements [numUsed++] = newElement;
  2692. }
  2693. lock.exit();
  2694. }
  2695. /** Inserts multiple copies of an element into the array at a given position.
  2696. If the index is less than 0 or greater than the size of the array, the
  2697. element will be added to the end of the array.
  2698. Otherwise, it will be inserted into the array, moving all the later elements
  2699. along to make room.
  2700. @param indexToInsertAt the index at which the new element should be inserted
  2701. @param newElement the new object to add to the array
  2702. @param numberOfTimesToInsertIt how many copies of the value to insert
  2703. @see insert, add, addSorted, set
  2704. */
  2705. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  2706. int numberOfTimesToInsertIt) throw()
  2707. {
  2708. if (numberOfTimesToInsertIt > 0)
  2709. {
  2710. lock.enter();
  2711. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2712. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2713. {
  2714. ElementType* insertPos = this->elements + indexToInsertAt;
  2715. const int numberToMove = numUsed - indexToInsertAt;
  2716. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2717. numUsed += numberOfTimesToInsertIt;
  2718. while (--numberOfTimesToInsertIt >= 0)
  2719. *insertPos++ = newElement;
  2720. }
  2721. else
  2722. {
  2723. while (--numberOfTimesToInsertIt >= 0)
  2724. this->elements [numUsed++] = newElement;
  2725. }
  2726. lock.exit();
  2727. }
  2728. }
  2729. /** Inserts an array of values into this array at a given position.
  2730. If the index is less than 0 or greater than the size of the array, the
  2731. new elements will be added to the end of the array.
  2732. Otherwise, they will be inserted into the array, moving all the later elements
  2733. along to make room.
  2734. @param indexToInsertAt the index at which the first new element should be inserted
  2735. @param newElements the new values to add to the array
  2736. @param numberOfElements how many items are in the array
  2737. @see insert, add, addSorted, set
  2738. */
  2739. void insertArray (int indexToInsertAt,
  2740. const ElementType* newElements,
  2741. int numberOfElements) throw()
  2742. {
  2743. if (numberOfElements > 0)
  2744. {
  2745. lock.enter();
  2746. this->ensureAllocatedSize (numUsed + numberOfElements);
  2747. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2748. {
  2749. ElementType* insertPos = this->elements + indexToInsertAt;
  2750. const int numberToMove = numUsed - indexToInsertAt;
  2751. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2752. numUsed += numberOfElements;
  2753. while (--numberOfElements >= 0)
  2754. *insertPos++ = *newElements++;
  2755. }
  2756. else
  2757. {
  2758. while (--numberOfElements >= 0)
  2759. this->elements [numUsed++] = *newElements++;
  2760. }
  2761. lock.exit();
  2762. }
  2763. }
  2764. /** Appends a new element at the end of the array as long as the array doesn't
  2765. already contain it.
  2766. If the array already contains an element that matches the one passed in, nothing
  2767. will be done.
  2768. @param newElement the new object to add to the array
  2769. */
  2770. void addIfNotAlreadyThere (const ElementType newElement) throw()
  2771. {
  2772. lock.enter();
  2773. if (! contains (newElement))
  2774. add (newElement);
  2775. lock.exit();
  2776. }
  2777. /** Replaces an element with a new value.
  2778. If the index is less than zero, this method does nothing.
  2779. If the index is beyond the end of the array, the item is added to the end of the array.
  2780. @param indexToChange the index whose value you want to change
  2781. @param newValue the new value to set for this index.
  2782. @see add, insert
  2783. */
  2784. void set (const int indexToChange,
  2785. const ElementType newValue) throw()
  2786. {
  2787. jassert (indexToChange >= 0);
  2788. if (indexToChange >= 0)
  2789. {
  2790. lock.enter();
  2791. if (indexToChange < numUsed)
  2792. {
  2793. this->elements [indexToChange] = newValue;
  2794. }
  2795. else
  2796. {
  2797. this->ensureAllocatedSize (numUsed + 1);
  2798. this->elements [numUsed++] = newValue;
  2799. }
  2800. lock.exit();
  2801. }
  2802. }
  2803. /** Replaces an element with a new value without doing any bounds-checking.
  2804. This just sets a value directly in the array's internal storage, so you'd
  2805. better make sure it's in range!
  2806. @param indexToChange the index whose value you want to change
  2807. @param newValue the new value to set for this index.
  2808. @see set, getUnchecked
  2809. */
  2810. void setUnchecked (const int indexToChange,
  2811. const ElementType newValue) throw()
  2812. {
  2813. lock.enter();
  2814. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  2815. this->elements [indexToChange] = newValue;
  2816. lock.exit();
  2817. }
  2818. /** Adds elements from an array to the end of this array.
  2819. @param elementsToAdd the array of elements to add
  2820. @param numElementsToAdd how many elements are in this other array
  2821. @see add
  2822. */
  2823. void addArray (const ElementType* elementsToAdd,
  2824. int numElementsToAdd) throw()
  2825. {
  2826. lock.enter();
  2827. if (numElementsToAdd > 0)
  2828. {
  2829. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  2830. while (--numElementsToAdd >= 0)
  2831. this->elements [numUsed++] = *elementsToAdd++;
  2832. }
  2833. lock.exit();
  2834. }
  2835. /** This swaps the contents of this array with those of another array.
  2836. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2837. because it just swaps their internal pointers.
  2838. */
  2839. template <class OtherArrayType>
  2840. void swapWithArray (OtherArrayType& otherArray) throw()
  2841. {
  2842. lock.enter();
  2843. otherArray.lock.enter();
  2844. swapVariables <int> (this->numUsed, otherArray.numUsed);
  2845. swapVariables <ElementType*> (this->elements, otherArray.elements);
  2846. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  2847. otherArray.lock.exit();
  2848. lock.exit();
  2849. }
  2850. /** Adds elements from another array to the end of this array.
  2851. @param arrayToAddFrom the array from which to copy the elements
  2852. @param startIndex the first element of the other array to start copying from
  2853. @param numElementsToAdd how many elements to add from the other array. If this
  2854. value is negative or greater than the number of available elements,
  2855. all available elements will be copied.
  2856. @see add
  2857. */
  2858. template <class OtherArrayType>
  2859. void addArray (const OtherArrayType& arrayToAddFrom,
  2860. int startIndex = 0,
  2861. int numElementsToAdd = -1) throw()
  2862. {
  2863. arrayToAddFrom.lockArray();
  2864. lock.enter();
  2865. jassert (this != &arrayToAddFrom);
  2866. if (startIndex < 0)
  2867. {
  2868. jassertfalse
  2869. startIndex = 0;
  2870. }
  2871. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  2872. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  2873. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  2874. lock.exit();
  2875. arrayToAddFrom.unlockArray();
  2876. }
  2877. /** Inserts a new element into the array, assuming that the array is sorted.
  2878. This will use a comparator to find the position at which the new element
  2879. should go. If the array isn't sorted, the behaviour of this
  2880. method will be unpredictable.
  2881. @param comparator the comparator to use to compare the elements - see the sort()
  2882. method for details about the form this object should take
  2883. @param newElement the new element to insert to the array
  2884. @see add, sort
  2885. */
  2886. template <class ElementComparator>
  2887. void addSorted (ElementComparator& comparator,
  2888. const ElementType newElement) throw()
  2889. {
  2890. lock.enter();
  2891. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  2892. lock.exit();
  2893. }
  2894. /** Finds the index of an element in the array, assuming that the array is sorted.
  2895. This will use a comparator to do a binary-chop to find the index of the given
  2896. element, if it exists. If the array isn't sorted, the behaviour of this
  2897. method will be unpredictable.
  2898. @param comparator the comparator to use to compare the elements - see the sort()
  2899. method for details about the form this object should take
  2900. @param elementToLookFor the element to search for
  2901. @returns the index of the element, or -1 if it's not found
  2902. @see addSorted, sort
  2903. */
  2904. template <class ElementComparator>
  2905. int indexOfSorted (ElementComparator& comparator,
  2906. const ElementType elementToLookFor) const throw()
  2907. {
  2908. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2909. // avoids getting warning messages about the parameter being unused
  2910. lock.enter();
  2911. int start = 0;
  2912. int end = numUsed;
  2913. for (;;)
  2914. {
  2915. if (start >= end)
  2916. {
  2917. lock.exit();
  2918. return -1;
  2919. }
  2920. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  2921. {
  2922. lock.exit();
  2923. return start;
  2924. }
  2925. else
  2926. {
  2927. const int halfway = (start + end) >> 1;
  2928. if (halfway == start)
  2929. {
  2930. lock.exit();
  2931. return -1;
  2932. }
  2933. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  2934. start = halfway;
  2935. else
  2936. end = halfway;
  2937. }
  2938. }
  2939. }
  2940. /** Removes an element from the array.
  2941. This will remove the element at a given index, and move back
  2942. all the subsequent elements to close the gap.
  2943. If the index passed in is out-of-range, nothing will happen.
  2944. @param indexToRemove the index of the element to remove
  2945. @returns the element that has been removed
  2946. @see removeValue, removeRange
  2947. */
  2948. ElementType remove (const int indexToRemove) throw()
  2949. {
  2950. lock.enter();
  2951. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2952. {
  2953. --numUsed;
  2954. ElementType* const e = this->elements + indexToRemove;
  2955. ElementType const removed = *e;
  2956. const int numberToShift = numUsed - indexToRemove;
  2957. if (numberToShift > 0)
  2958. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  2959. if ((numUsed << 1) < this->numAllocated)
  2960. minimiseStorageOverheads();
  2961. lock.exit();
  2962. return removed;
  2963. }
  2964. else
  2965. {
  2966. lock.exit();
  2967. return ElementType();
  2968. }
  2969. }
  2970. /** Removes an item from the array.
  2971. This will remove the first occurrence of the given element from the array.
  2972. If the item isn't found, no action is taken.
  2973. @param valueToRemove the object to try to remove
  2974. @see remove, removeRange
  2975. */
  2976. void removeValue (const ElementType valueToRemove) throw()
  2977. {
  2978. lock.enter();
  2979. ElementType* e = this->elements;
  2980. for (int i = numUsed; --i >= 0;)
  2981. {
  2982. if (valueToRemove == *e)
  2983. {
  2984. remove ((int) (e - this->elements));
  2985. break;
  2986. }
  2987. ++e;
  2988. }
  2989. lock.exit();
  2990. }
  2991. /** Removes a range of elements from the array.
  2992. This will remove a set of elements, starting from the given index,
  2993. and move subsequent elements down to close the gap.
  2994. If the range extends beyond the bounds of the array, it will
  2995. be safely clipped to the size of the array.
  2996. @param startIndex the index of the first element to remove
  2997. @param numberToRemove how many elements should be removed
  2998. @see remove, removeValue
  2999. */
  3000. void removeRange (int startIndex,
  3001. const int numberToRemove) throw()
  3002. {
  3003. lock.enter();
  3004. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3005. startIndex = jlimit (0, numUsed, startIndex);
  3006. if (endIndex > startIndex)
  3007. {
  3008. const int rangeSize = endIndex - startIndex;
  3009. ElementType* e = this->elements + startIndex;
  3010. int numToShift = numUsed - endIndex;
  3011. numUsed -= rangeSize;
  3012. while (--numToShift >= 0)
  3013. {
  3014. *e = e [rangeSize];
  3015. ++e;
  3016. }
  3017. if ((numUsed << 1) < this->numAllocated)
  3018. minimiseStorageOverheads();
  3019. }
  3020. lock.exit();
  3021. }
  3022. /** Removes the last n elements from the array.
  3023. @param howManyToRemove how many elements to remove from the end of the array
  3024. @see remove, removeValue, removeRange
  3025. */
  3026. void removeLast (const int howManyToRemove = 1) throw()
  3027. {
  3028. lock.enter();
  3029. numUsed = jmax (0, numUsed - howManyToRemove);
  3030. if ((numUsed << 1) < this->numAllocated)
  3031. minimiseStorageOverheads();
  3032. lock.exit();
  3033. }
  3034. /** Removes any elements which are also in another array.
  3035. @param otherArray the other array in which to look for elements to remove
  3036. @see removeValuesNotIn, remove, removeValue, removeRange
  3037. */
  3038. template <class OtherArrayType>
  3039. void removeValuesIn (const OtherArrayType& otherArray) throw()
  3040. {
  3041. otherArray.lockArray();
  3042. lock.enter();
  3043. if (this == &otherArray)
  3044. {
  3045. clear();
  3046. }
  3047. else
  3048. {
  3049. if (otherArray.size() > 0)
  3050. {
  3051. for (int i = numUsed; --i >= 0;)
  3052. if (otherArray.contains (this->elements [i]))
  3053. remove (i);
  3054. }
  3055. }
  3056. lock.exit();
  3057. otherArray.unlockArray();
  3058. }
  3059. /** Removes any elements which are not found in another array.
  3060. Only elements which occur in this other array will be retained.
  3061. @param otherArray the array in which to look for elements NOT to remove
  3062. @see removeValuesIn, remove, removeValue, removeRange
  3063. */
  3064. template <class OtherArrayType>
  3065. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  3066. {
  3067. otherArray.lockArray();
  3068. lock.enter();
  3069. if (this != &otherArray)
  3070. {
  3071. if (otherArray.size() <= 0)
  3072. {
  3073. clear();
  3074. }
  3075. else
  3076. {
  3077. for (int i = numUsed; --i >= 0;)
  3078. if (! otherArray.contains (this->elements [i]))
  3079. remove (i);
  3080. }
  3081. }
  3082. lock.exit();
  3083. otherArray.unlockArray();
  3084. }
  3085. /** Swaps over two elements in the array.
  3086. This swaps over the elements found at the two indexes passed in.
  3087. If either index is out-of-range, this method will do nothing.
  3088. @param index1 index of one of the elements to swap
  3089. @param index2 index of the other element to swap
  3090. */
  3091. void swap (const int index1,
  3092. const int index2) throw()
  3093. {
  3094. lock.enter();
  3095. if (((unsigned int) index1) < (unsigned int) numUsed
  3096. && ((unsigned int) index2) < (unsigned int) numUsed)
  3097. {
  3098. swapVariables (this->elements [index1],
  3099. this->elements [index2]);
  3100. }
  3101. lock.exit();
  3102. }
  3103. /** Moves one of the values to a different position.
  3104. This will move the value to a specified index, shuffling along
  3105. any intervening elements as required.
  3106. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3107. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3108. @param currentIndex the index of the value to be moved. If this isn't a
  3109. valid index, then nothing will be done
  3110. @param newIndex the index at which you'd like this value to end up. If this
  3111. is less than zero, the value will be moved to the end
  3112. of the array
  3113. */
  3114. void move (const int currentIndex,
  3115. int newIndex) throw()
  3116. {
  3117. if (currentIndex != newIndex)
  3118. {
  3119. lock.enter();
  3120. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3121. {
  3122. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3123. newIndex = numUsed - 1;
  3124. const ElementType value = this->elements [currentIndex];
  3125. if (newIndex > currentIndex)
  3126. {
  3127. memmove (this->elements + currentIndex,
  3128. this->elements + currentIndex + 1,
  3129. (newIndex - currentIndex) * sizeof (ElementType));
  3130. }
  3131. else
  3132. {
  3133. memmove (this->elements + newIndex + 1,
  3134. this->elements + newIndex,
  3135. (currentIndex - newIndex) * sizeof (ElementType));
  3136. }
  3137. this->elements [newIndex] = value;
  3138. }
  3139. lock.exit();
  3140. }
  3141. }
  3142. /** Reduces the amount of storage being used by the array.
  3143. Arrays typically allocate slightly more storage than they need, and after
  3144. removing elements, they may have quite a lot of unused space allocated.
  3145. This method will reduce the amount of allocated storage to a minimum.
  3146. */
  3147. void minimiseStorageOverheads() throw()
  3148. {
  3149. lock.enter();
  3150. if (numUsed == 0)
  3151. {
  3152. this->setAllocatedSize (0);
  3153. }
  3154. else
  3155. {
  3156. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3157. if (newAllocation < this->numAllocated)
  3158. this->setAllocatedSize (newAllocation);
  3159. }
  3160. lock.exit();
  3161. }
  3162. /** Increases the array's internal storage to hold a minimum number of elements.
  3163. Calling this before adding a large known number of elements means that
  3164. the array won't have to keep dynamically resizing itself as the elements
  3165. are added, and it'll therefore be more efficient.
  3166. */
  3167. void ensureStorageAllocated (const int minNumElements) throw()
  3168. {
  3169. this->ensureAllocatedSize (minNumElements);
  3170. }
  3171. /** Sorts the elements in the array.
  3172. This will use a comparator object to sort the elements into order. The object
  3173. passed must have a method of the form:
  3174. @code
  3175. int compareElements (ElementType first, ElementType second);
  3176. @endcode
  3177. ..and this method must return:
  3178. - a value of < 0 if the first comes before the second
  3179. - a value of 0 if the two objects are equivalent
  3180. - a value of > 0 if the second comes before the first
  3181. To improve performance, the compareElements() method can be declared as static or const.
  3182. @param comparator the comparator to use for comparing elements.
  3183. @param retainOrderOfEquivalentItems if this is true, then items
  3184. which the comparator says are equivalent will be
  3185. kept in the order in which they currently appear
  3186. in the array. This is slower to perform, but may
  3187. be important in some cases. If it's false, a faster
  3188. algorithm is used, but equivalent elements may be
  3189. rearranged.
  3190. @see addSorted, indexOfSorted, sortArray
  3191. */
  3192. template <class ElementComparator>
  3193. void sort (ElementComparator& comparator,
  3194. const bool retainOrderOfEquivalentItems = false) const throw()
  3195. {
  3196. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3197. // avoids getting warning messages about the parameter being unused
  3198. lock.enter();
  3199. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3200. lock.exit();
  3201. }
  3202. /** Locks the array's CriticalSection.
  3203. Of course if the type of section used is a DummyCriticalSection, this won't
  3204. have any effect.
  3205. @see unlockArray
  3206. */
  3207. void lockArray() const throw()
  3208. {
  3209. lock.enter();
  3210. }
  3211. /** Unlocks the array's CriticalSection.
  3212. Of course if the type of section used is a DummyCriticalSection, this won't
  3213. have any effect.
  3214. @see lockArray
  3215. */
  3216. void unlockArray() const throw()
  3217. {
  3218. lock.exit();
  3219. }
  3220. juce_UseDebuggingNewOperator
  3221. private:
  3222. int numUsed;
  3223. TypeOfCriticalSectionToUse lock;
  3224. };
  3225. #endif // __JUCE_ARRAY_JUCEHEADER__
  3226. /********* End of inlined file: juce_Array.h *********/
  3227. class MemoryBlock;
  3228. /**
  3229. An array of on/off bits, also usable to store large binary integers.
  3230. A BitArray acts like an arbitrarily large integer whose bits can be set or
  3231. cleared, and some basic mathematical operations can be done on the number as
  3232. a whole.
  3233. */
  3234. class JUCE_API BitArray
  3235. {
  3236. public:
  3237. /** Creates an empty BitArray */
  3238. BitArray() throw();
  3239. /** Creates a BitArray containing an integer value in its low bits.
  3240. The low 32 bits of the array are initialised with this value.
  3241. */
  3242. BitArray (const unsigned int value) throw();
  3243. /** Creates a BitArray containing an integer value in its low bits.
  3244. The low 32 bits of the array are initialised with the absolute value
  3245. passed in, and its sign is set to reflect the sign of the number.
  3246. */
  3247. BitArray (const int value) throw();
  3248. /** Creates a BitArray containing an integer value in its low bits.
  3249. The low 64 bits of the array are initialised with the absolute value
  3250. passed in, and its sign is set to reflect the sign of the number.
  3251. */
  3252. BitArray (int64 value) throw();
  3253. /** Creates a copy of another BitArray. */
  3254. BitArray (const BitArray& other) throw();
  3255. /** Destructor. */
  3256. ~BitArray() throw();
  3257. /** Copies another BitArray onto this one. */
  3258. const BitArray& operator= (const BitArray& other) throw();
  3259. /** Two arrays are the same if the same bits are set. */
  3260. bool operator== (const BitArray& other) const throw();
  3261. /** Two arrays are the same if the same bits are set. */
  3262. bool operator!= (const BitArray& other) const throw();
  3263. /** Clears all bits in the BitArray to 0. */
  3264. void clear() throw();
  3265. /** Clears a particular bit in the array. */
  3266. void clearBit (const int bitNumber) throw();
  3267. /** Sets a specified bit to 1.
  3268. If the bit number is high, this will grow the array to accomodate it.
  3269. */
  3270. void setBit (const int bitNumber) throw();
  3271. /** Sets or clears a specified bit. */
  3272. void setBit (const int bitNumber,
  3273. const bool shouldBeSet) throw();
  3274. /** Sets a range of bits to be either on or off.
  3275. @param startBit the first bit to change
  3276. @param numBits the number of bits to change
  3277. @param shouldBeSet whether to turn these bits on or off
  3278. */
  3279. void setRange (int startBit,
  3280. int numBits,
  3281. const bool shouldBeSet) throw();
  3282. /** Inserts a bit an a given position, shifting up any bits above it. */
  3283. void insertBit (const int bitNumber,
  3284. const bool shouldBeSet) throw();
  3285. /** Returns the value of a specified bit in the array.
  3286. If the index is out-of-range, the result will be false.
  3287. */
  3288. bool operator[] (const int bit) const throw();
  3289. /** Returns true if no bits are set. */
  3290. bool isEmpty() const throw();
  3291. /** Returns a range of bits in the array as a new BitArray.
  3292. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3293. @see getBitRangeAsInt
  3294. */
  3295. const BitArray getBitRange (int startBit, int numBits) const throw();
  3296. /** Returns a range of bits in the array as an integer value.
  3297. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3298. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3299. getBitRange().
  3300. */
  3301. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3302. /** Sets a range of bits in the array based on an integer value.
  3303. Copies the given integer into the array, starting at startBit,
  3304. and only using up to numBits of the available bits.
  3305. */
  3306. void setBitRangeAsInt (int startBit, int numBits,
  3307. unsigned int valueToSet) throw();
  3308. /** Performs a bitwise OR with another BitArray.
  3309. The result ends up in this array.
  3310. */
  3311. void orWith (const BitArray& other) throw();
  3312. /** Performs a bitwise AND with another BitArray.
  3313. The result ends up in this array.
  3314. */
  3315. void andWith (const BitArray& other) throw();
  3316. /** Performs a bitwise XOR with another BitArray.
  3317. The result ends up in this array.
  3318. */
  3319. void xorWith (const BitArray& other) throw();
  3320. /** Adds another BitArray's value to this one.
  3321. Treating the two arrays as large positive integers, this
  3322. adds them up and puts the result in this array.
  3323. */
  3324. void add (const BitArray& other) throw();
  3325. /** Subtracts another BitArray's value from this one.
  3326. Treating the two arrays as large positive integers, this
  3327. subtracts them and puts the result in this array.
  3328. Note that if the result should be negative, this won't be
  3329. handled correctly.
  3330. */
  3331. void subtract (const BitArray& other) throw();
  3332. /** Multiplies another BitArray's value with this one.
  3333. Treating the two arrays as large positive integers, this
  3334. multiplies them and puts the result in this array.
  3335. */
  3336. void multiplyBy (const BitArray& other) throw();
  3337. /** Divides another BitArray's value into this one and also produces a remainder.
  3338. Treating the two arrays as large positive integers, this
  3339. divides this value by the other, leaving the quotient in this
  3340. array, and the remainder is copied into the other BitArray passed in.
  3341. */
  3342. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  3343. /** Returns the largest value that will divide both this value and the one
  3344. passed-in.
  3345. */
  3346. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  3347. /** Performs a modulo operation on this value.
  3348. The result is stored in this value.
  3349. */
  3350. void modulo (const BitArray& divisor) throw();
  3351. /** Performs a combined exponent and modulo operation.
  3352. This BitArray's value becomes (this ^ exponent) % modulus.
  3353. */
  3354. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  3355. /** Performs an inverse modulo on the value.
  3356. i.e. the result is (this ^ -1) mod (modulus).
  3357. */
  3358. void inverseModulo (const BitArray& modulus) throw();
  3359. /** Shifts a section of bits left or right.
  3360. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3361. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3362. */
  3363. void shiftBits (int howManyBitsLeft,
  3364. int startBit = 0) throw();
  3365. /** Does a signed comparison of two BitArrays.
  3366. Return values are:
  3367. - 0 if the numbers are the same
  3368. - < 0 if this number is smaller than the other
  3369. - > 0 if this number is bigger than the other
  3370. */
  3371. int compare (const BitArray& other) const throw();
  3372. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  3373. Return values are:
  3374. - 0 if the numbers are the same
  3375. - < 0 if this number is smaller than the other
  3376. - > 0 if this number is bigger than the other
  3377. */
  3378. int compareAbsolute (const BitArray& other) const throw();
  3379. /** Returns true if the value is less than zero.
  3380. @see setNegative, negate
  3381. */
  3382. bool isNegative() const throw();
  3383. /** Changes the sign of the number to be positive or negative.
  3384. @see isNegative, negate
  3385. */
  3386. void setNegative (const bool shouldBeNegative) throw();
  3387. /** Inverts the sign of the number.
  3388. @see isNegative, setNegative
  3389. */
  3390. void negate() throw();
  3391. /** Counts the total number of set bits in the array. */
  3392. int countNumberOfSetBits() const throw();
  3393. /** Looks for the index of the next set bit after a given starting point.
  3394. searches from startIndex (inclusive) upwards for the first set bit,
  3395. and returns its index.
  3396. If no set bits are found, it returns -1.
  3397. */
  3398. int findNextSetBit (int startIndex = 0) const throw();
  3399. /** Looks for the index of the next clear bit after a given starting point.
  3400. searches from startIndex (inclusive) upwards for the first clear bit,
  3401. and returns its index.
  3402. */
  3403. int findNextClearBit (int startIndex = 0) const throw();
  3404. /** Returns the index of the highest set bit in the array.
  3405. If the array is empty, this will return -1.
  3406. */
  3407. int getHighestBit() const throw();
  3408. /** Converts the array to a number string.
  3409. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3410. If minuimumNumCharacters is greater than 0, the returned string will be
  3411. padded with leading zeros to reach at least that length.
  3412. */
  3413. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  3414. /** Converts a number string to an array.
  3415. Any non-valid characters will be ignored.
  3416. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3417. */
  3418. void parseString (const String& text,
  3419. const int base) throw();
  3420. /** Turns the array into a block of binary data.
  3421. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3422. of the array, and so on.
  3423. @see loadFromMemoryBlock
  3424. */
  3425. const MemoryBlock toMemoryBlock() const throw();
  3426. /** Copies a block of raw data onto this array.
  3427. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3428. of the array, and so on.
  3429. @see toMemoryBlock
  3430. */
  3431. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  3432. juce_UseDebuggingNewOperator
  3433. private:
  3434. void ensureSize (const int numVals) throw();
  3435. unsigned int* values;
  3436. int numValues, highestBit;
  3437. bool negative;
  3438. };
  3439. #endif // __JUCE_BITARRAY_JUCEHEADER__
  3440. /********* End of inlined file: juce_BitArray.h *********/
  3441. /**
  3442. A simple pseudo-random number generator.
  3443. */
  3444. class JUCE_API Random
  3445. {
  3446. public:
  3447. /** Creates a Random object based on a seed value.
  3448. For a given seed value, the subsequent numbers generated by this object
  3449. will be predictable, so a good idea is to set this value based
  3450. on the time, e.g.
  3451. new Random (Time::currentTimeMillis())
  3452. */
  3453. Random (const int64 seedValue) throw();
  3454. /** Destructor. */
  3455. ~Random() throw();
  3456. /** Returns the next random 32 bit integer.
  3457. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  3458. */
  3459. int nextInt() throw();
  3460. /** Returns the next random number, limited to a given range.
  3461. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  3462. */
  3463. int nextInt (const int maxValue) throw();
  3464. /** Returns the next 64-bit random number.
  3465. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  3466. */
  3467. int64 nextInt64() throw();
  3468. /** Returns the next random floating-point number.
  3469. @returns a random value in the range 0 to 1.0
  3470. */
  3471. float nextFloat() throw();
  3472. /** Returns the next random floating-point number.
  3473. @returns a random value in the range 0 to 1.0
  3474. */
  3475. double nextDouble() throw();
  3476. /** Returns the next random boolean value.
  3477. */
  3478. bool nextBool() throw();
  3479. /** Returns a BitArray containing a random number.
  3480. @returns a random value in the range 0 to (maximumValue - 1).
  3481. */
  3482. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  3483. /** Sets a range of bits in a BitArray to random values. */
  3484. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  3485. /** To avoid the overhead of having to create a new Random object whenever
  3486. you need a number, this is a shared application-wide object that
  3487. can be used.
  3488. It's not thread-safe though, so threads should use their own Random object.
  3489. */
  3490. static Random& getSystemRandom() throw();
  3491. /** Resets this Random object to a given seed value. */
  3492. void setSeed (const int64 newSeed) throw();
  3493. /** Reseeds this generator using a value generated from various semi-random system
  3494. properties like the current time, etc.
  3495. Because this function convolves the time with the last seed value, calling
  3496. it repeatedly will increase the randomness of the final result.
  3497. */
  3498. void setSeedRandomly();
  3499. juce_UseDebuggingNewOperator
  3500. private:
  3501. int64 seed;
  3502. };
  3503. #endif // __JUCE_RANDOM_JUCEHEADER__
  3504. /********* End of inlined file: juce_Random.h *********/
  3505. #endif
  3506. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3507. /********* Start of inlined file: juce_RelativeTime.h *********/
  3508. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3509. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3510. /** A relative measure of time.
  3511. The time is stored as a number of seconds, at double-precision floating
  3512. point accuracy, and may be positive or negative.
  3513. If you need an absolute time, (i.e. a date + time), see the Time class.
  3514. */
  3515. class JUCE_API RelativeTime
  3516. {
  3517. public:
  3518. /** Creates a RelativeTime.
  3519. @param seconds the number of seconds, which may be +ve or -ve.
  3520. @see milliseconds, minutes, hours, days, weeks
  3521. */
  3522. explicit RelativeTime (const double seconds = 0.0) throw();
  3523. /** Copies another relative time. */
  3524. RelativeTime (const RelativeTime& other) throw();
  3525. /** Copies another relative time. */
  3526. const RelativeTime& operator= (const RelativeTime& other) throw();
  3527. /** Destructor. */
  3528. ~RelativeTime() throw();
  3529. /** Creates a new RelativeTime object representing a number of milliseconds.
  3530. @see minutes, hours, days, weeks
  3531. */
  3532. static const RelativeTime milliseconds (const int milliseconds) throw();
  3533. /** Creates a new RelativeTime object representing a number of milliseconds.
  3534. @see minutes, hours, days, weeks
  3535. */
  3536. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3537. /** Creates a new RelativeTime object representing a number of minutes.
  3538. @see milliseconds, hours, days, weeks
  3539. */
  3540. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3541. /** Creates a new RelativeTime object representing a number of hours.
  3542. @see milliseconds, minutes, days, weeks
  3543. */
  3544. static const RelativeTime hours (const double numberOfHours) throw();
  3545. /** Creates a new RelativeTime object representing a number of days.
  3546. @see milliseconds, minutes, hours, weeks
  3547. */
  3548. static const RelativeTime days (const double numberOfDays) throw();
  3549. /** Creates a new RelativeTime object representing a number of weeks.
  3550. @see milliseconds, minutes, hours, days
  3551. */
  3552. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3553. /** Returns the number of milliseconds this time represents.
  3554. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3555. */
  3556. int64 inMilliseconds() const throw();
  3557. /** Returns the number of seconds this time represents.
  3558. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3559. */
  3560. double inSeconds() const throw() { return seconds; }
  3561. /** Returns the number of minutes this time represents.
  3562. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3563. */
  3564. double inMinutes() const throw();
  3565. /** Returns the number of hours this time represents.
  3566. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3567. */
  3568. double inHours() const throw();
  3569. /** Returns the number of days this time represents.
  3570. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3571. */
  3572. double inDays() const throw();
  3573. /** Returns the number of weeks this time represents.
  3574. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3575. */
  3576. double inWeeks() const throw();
  3577. /** Returns a readable textual description of the time.
  3578. The exact format of the string returned will depend on
  3579. the magnitude of the time - e.g.
  3580. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3581. so that only the two most significant units are printed.
  3582. The returnValueForZeroTime value is the result that is returned if the
  3583. length is zero. Depending on your application you might want to use this
  3584. to return something more relevant like "empty" or "0 secs", etc.
  3585. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3586. */
  3587. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3588. /** Compares two RelativeTimes. */
  3589. bool operator== (const RelativeTime& other) const throw();
  3590. /** Compares two RelativeTimes. */
  3591. bool operator!= (const RelativeTime& other) const throw();
  3592. /** Compares two RelativeTimes. */
  3593. bool operator> (const RelativeTime& other) const throw();
  3594. /** Compares two RelativeTimes. */
  3595. bool operator< (const RelativeTime& other) const throw();
  3596. /** Compares two RelativeTimes. */
  3597. bool operator>= (const RelativeTime& other) const throw();
  3598. /** Compares two RelativeTimes. */
  3599. bool operator<= (const RelativeTime& other) const throw();
  3600. /** Adds another RelativeTime to this one and returns the result. */
  3601. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3602. /** Subtracts another RelativeTime from this one and returns the result. */
  3603. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3604. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3605. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3606. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3607. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3608. /** Adds another RelativeTime to this one. */
  3609. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3610. /** Subtracts another RelativeTime from this one. */
  3611. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3612. /** Adds a number of seconds to this time. */
  3613. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3614. /** Subtracts a number of seconds from this time. */
  3615. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3616. juce_UseDebuggingNewOperator
  3617. private:
  3618. double seconds;
  3619. };
  3620. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3621. /********* End of inlined file: juce_RelativeTime.h *********/
  3622. #endif
  3623. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  3624. /********* Start of inlined file: juce_Singleton.h *********/
  3625. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  3626. #define __JUCE_SINGLETON_JUCEHEADER__
  3627. /********* Start of inlined file: juce_ScopedLock.h *********/
  3628. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  3629. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  3630. /**
  3631. Automatically locks and unlocks a CriticalSection object.
  3632. Use one of these as a local variable to control access to a CriticalSection.
  3633. e.g. @code
  3634. CriticalSection myCriticalSection;
  3635. for (;;)
  3636. {
  3637. const ScopedLock myScopedLock (myCriticalSection);
  3638. // myCriticalSection is now locked
  3639. ...do some stuff...
  3640. // myCriticalSection gets unlocked here.
  3641. }
  3642. @endcode
  3643. @see CriticalSection, ScopedUnlock
  3644. */
  3645. class JUCE_API ScopedLock
  3646. {
  3647. public:
  3648. /** Creates a ScopedLock.
  3649. As soon as it is created, this will lock the CriticalSection, and
  3650. when the ScopedLock object is deleted, the CriticalSection will
  3651. be unlocked.
  3652. Make sure this object is created and deleted by the same thread,
  3653. otherwise there are no guarantees what will happen! Best just to use it
  3654. as a local stack object, rather than creating one with the new() operator.
  3655. */
  3656. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  3657. /** Destructor.
  3658. The CriticalSection will be unlocked when the destructor is called.
  3659. Make sure this object is created and deleted by the same thread,
  3660. otherwise there are no guarantees what will happen!
  3661. */
  3662. inline ~ScopedLock() throw() { lock_.exit(); }
  3663. private:
  3664. const CriticalSection& lock_;
  3665. ScopedLock (const ScopedLock&);
  3666. const ScopedLock& operator= (const ScopedLock&);
  3667. };
  3668. /**
  3669. Automatically unlocks and re-locks a CriticalSection object.
  3670. This is the reverse of a ScopedLock object - instead of locking the critical
  3671. section for the lifetime of this object, it unlocks it.
  3672. Make sure you don't try to unlock critical sections that aren't actually locked!
  3673. e.g. @code
  3674. CriticalSection myCriticalSection;
  3675. for (;;)
  3676. {
  3677. const ScopedLock myScopedLock (myCriticalSection);
  3678. // myCriticalSection is now locked
  3679. ... do some stuff with it locked ..
  3680. while (xyz)
  3681. {
  3682. ... do some stuff with it locked ..
  3683. const ScopedUnlock unlocker (myCriticalSection);
  3684. // myCriticalSection is now unlocked for the remainder of this block,
  3685. // and re-locked at the end.
  3686. ...do some stuff with it unlocked ...
  3687. }
  3688. // myCriticalSection gets unlocked here.
  3689. }
  3690. @endcode
  3691. @see CriticalSection, ScopedLock
  3692. */
  3693. class ScopedUnlock
  3694. {
  3695. public:
  3696. /** Creates a ScopedUnlock.
  3697. As soon as it is created, this will unlock the CriticalSection, and
  3698. when the ScopedLock object is deleted, the CriticalSection will
  3699. be re-locked.
  3700. Make sure this object is created and deleted by the same thread,
  3701. otherwise there are no guarantees what will happen! Best just to use it
  3702. as a local stack object, rather than creating one with the new() operator.
  3703. */
  3704. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  3705. /** Destructor.
  3706. The CriticalSection will be unlocked when the destructor is called.
  3707. Make sure this object is created and deleted by the same thread,
  3708. otherwise there are no guarantees what will happen!
  3709. */
  3710. inline ~ScopedUnlock() throw() { lock_.enter(); }
  3711. private:
  3712. const CriticalSection& lock_;
  3713. ScopedUnlock (const ScopedLock&);
  3714. const ScopedUnlock& operator= (const ScopedUnlock&);
  3715. };
  3716. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  3717. /********* End of inlined file: juce_ScopedLock.h *********/
  3718. /**
  3719. Macro to declare member variables and methods for a singleton class.
  3720. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  3721. to the class's definition.
  3722. If allowOnlyOneInstance == true, it won't allow the object to be created
  3723. more than once in the process's lifetime.
  3724. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  3725. implementation code.
  3726. Clients can then call the static MyClass::getInstance() to get a pointer to the
  3727. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  3728. is currently extant
  3729. it's a very good idea to also add the call clearSingletonInstance() to the
  3730. destructor of the class, in case it is deleted by other means than deleteInstance()
  3731. e.g. @code
  3732. class MySingleton
  3733. {
  3734. public:
  3735. MySingleton()
  3736. {
  3737. }
  3738. ~MySingleton()
  3739. {
  3740. // this ensures that no dangling pointers are left when the
  3741. // singleton is deleted.
  3742. clearSingletonInstance();
  3743. }
  3744. juce_DeclareSingleton (MySingleton, false)
  3745. };
  3746. juce_ImplementSingleton (MySingleton)
  3747. // example of usage:
  3748. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  3749. ...
  3750. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  3751. @endcode
  3752. If you know that your object will only be created and deleted by a single thread, you
  3753. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  3754. of this one.
  3755. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  3756. */
  3757. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  3758. \
  3759. static classname* _singletonInstance; \
  3760. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  3761. \
  3762. static classname* getInstance() \
  3763. { \
  3764. if (_singletonInstance == 0) \
  3765. {\
  3766. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  3767. \
  3768. if (_singletonInstance == 0) \
  3769. { \
  3770. static bool alreadyInside = false; \
  3771. static bool createdOnceAlready = false; \
  3772. \
  3773. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  3774. jassert (! problem); \
  3775. if (! problem) \
  3776. { \
  3777. createdOnceAlready = true; \
  3778. alreadyInside = true; \
  3779. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  3780. alreadyInside = false; \
  3781. \
  3782. _singletonInstance = newObject; \
  3783. } \
  3784. } \
  3785. } \
  3786. \
  3787. return _singletonInstance; \
  3788. } \
  3789. \
  3790. static inline classname* getInstanceWithoutCreating() throw() \
  3791. { \
  3792. return _singletonInstance; \
  3793. } \
  3794. \
  3795. static void deleteInstance() \
  3796. { \
  3797. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  3798. if (_singletonInstance != 0) \
  3799. { \
  3800. classname* const old = _singletonInstance; \
  3801. _singletonInstance = 0; \
  3802. delete old; \
  3803. } \
  3804. } \
  3805. \
  3806. void clearSingletonInstance() throw() \
  3807. { \
  3808. if (_singletonInstance == this) \
  3809. _singletonInstance = 0; \
  3810. }
  3811. /** This is a counterpart to the juce_DeclareSingleton macro.
  3812. After adding the juce_DeclareSingleton to the class definition, this macro has
  3813. to be used in the cpp file.
  3814. */
  3815. #define juce_ImplementSingleton(classname) \
  3816. \
  3817. classname* classname::_singletonInstance = 0; \
  3818. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  3819. /**
  3820. Macro to declare member variables and methods for a singleton class.
  3821. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  3822. section to make access to it thread-safe. If you know that your object will
  3823. only ever be created or deleted by a single thread, then this is a
  3824. more efficient version to use.
  3825. See the documentation for juce_DeclareSingleton for more information about
  3826. how to use it, the only difference being that you have to use
  3827. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  3828. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  3829. */
  3830. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  3831. \
  3832. static classname* _singletonInstance; \
  3833. \
  3834. static classname* getInstance() \
  3835. { \
  3836. if (_singletonInstance == 0) \
  3837. { \
  3838. static bool alreadyInside = false; \
  3839. static bool createdOnceAlready = false; \
  3840. \
  3841. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  3842. jassert (! problem); \
  3843. if (! problem) \
  3844. { \
  3845. createdOnceAlready = true; \
  3846. alreadyInside = true; \
  3847. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  3848. alreadyInside = false; \
  3849. \
  3850. _singletonInstance = newObject; \
  3851. } \
  3852. } \
  3853. \
  3854. return _singletonInstance; \
  3855. } \
  3856. \
  3857. static inline classname* getInstanceWithoutCreating() throw() \
  3858. { \
  3859. return _singletonInstance; \
  3860. } \
  3861. \
  3862. static void deleteInstance() \
  3863. { \
  3864. if (_singletonInstance != 0) \
  3865. { \
  3866. classname* const old = _singletonInstance; \
  3867. _singletonInstance = 0; \
  3868. delete old; \
  3869. } \
  3870. } \
  3871. \
  3872. void clearSingletonInstance() throw() \
  3873. { \
  3874. if (_singletonInstance == this) \
  3875. _singletonInstance = 0; \
  3876. }
  3877. /**
  3878. Macro to declare member variables and methods for a singleton class.
  3879. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  3880. for recursion or repeated instantiation. It's intended for use as a lightweight
  3881. version of a singleton, where you're using it in very straightforward
  3882. circumstances and don't need the extra checking.
  3883. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  3884. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  3885. See the documentation for juce_DeclareSingleton for more information about
  3886. how to use it, the only difference being that you have to use
  3887. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  3888. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  3889. */
  3890. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  3891. \
  3892. static classname* _singletonInstance; \
  3893. \
  3894. static classname* getInstance() \
  3895. { \
  3896. if (_singletonInstance == 0) \
  3897. _singletonInstance = new classname(); \
  3898. \
  3899. return _singletonInstance; \
  3900. } \
  3901. \
  3902. static inline classname* getInstanceWithoutCreating() throw() \
  3903. { \
  3904. return _singletonInstance; \
  3905. } \
  3906. \
  3907. static void deleteInstance() \
  3908. { \
  3909. if (_singletonInstance != 0) \
  3910. { \
  3911. classname* const old = _singletonInstance; \
  3912. _singletonInstance = 0; \
  3913. delete old; \
  3914. } \
  3915. } \
  3916. \
  3917. void clearSingletonInstance() throw() \
  3918. { \
  3919. if (_singletonInstance == this) \
  3920. _singletonInstance = 0; \
  3921. }
  3922. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  3923. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  3924. to the class definition, this macro has to be used somewhere in the cpp file.
  3925. */
  3926. #define juce_ImplementSingleton_SingleThreaded(classname) \
  3927. \
  3928. classname* classname::_singletonInstance = 0;
  3929. #endif // __JUCE_SINGLETON_JUCEHEADER__
  3930. /********* End of inlined file: juce_Singleton.h *********/
  3931. #endif
  3932. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  3933. #endif
  3934. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  3935. /********* Start of inlined file: juce_SystemStats.h *********/
  3936. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  3937. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  3938. /**
  3939. Contains methods for finding out about the current hardware and OS configuration.
  3940. */
  3941. class JUCE_API SystemStats
  3942. {
  3943. public:
  3944. /** Returns the current version of JUCE,
  3945. (just in case you didn't already know at compile-time.)
  3946. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  3947. */
  3948. static const String getJUCEVersion() throw();
  3949. /** The set of possible results of the getOperatingSystemType() method.
  3950. */
  3951. enum OperatingSystemType
  3952. {
  3953. UnknownOS = 0,
  3954. MacOSX = 0x1000,
  3955. Linux = 0x2000,
  3956. Win95 = 0x4001,
  3957. Win98 = 0x4002,
  3958. WinNT351 = 0x4103,
  3959. WinNT40 = 0x4104,
  3960. Win2000 = 0x4105,
  3961. WinXP = 0x4106,
  3962. WinVista = 0x4107,
  3963. Windows = 0x4000, /**< To test whether any version of Windows is running,
  3964. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  3965. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  3966. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  3967. };
  3968. /** Returns the type of operating system we're running on.
  3969. @returns one of the values from the OperatingSystemType enum.
  3970. @see getOperatingSystemName
  3971. */
  3972. static OperatingSystemType getOperatingSystemType() throw();
  3973. /** Returns the name of the type of operating system we're running on.
  3974. @returns a string describing the OS type.
  3975. @see getOperatingSystemType
  3976. */
  3977. static const String getOperatingSystemName() throw();
  3978. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  3979. */
  3980. static bool isOperatingSystem64Bit() throw();
  3981. // CPU and memory information..
  3982. /** Returns the approximate CPU speed.
  3983. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  3984. what year you're reading this...)
  3985. */
  3986. static int getCpuSpeedInMegaherz() throw();
  3987. /** Returns a string to indicate the CPU vendor.
  3988. Might not be known on some systems.
  3989. */
  3990. static const String getCpuVendor() throw();
  3991. /** Checks whether Intel MMX instructions are available. */
  3992. static bool hasMMX() throw();
  3993. /** Checks whether Intel SSE instructions are available. */
  3994. static bool hasSSE() throw();
  3995. /** Checks whether Intel SSE2 instructions are available. */
  3996. static bool hasSSE2() throw();
  3997. /** Checks whether AMD 3DNOW instructions are available. */
  3998. static bool has3DNow() throw();
  3999. /** Returns the number of CPUs.
  4000. */
  4001. static int getNumCpus() throw();
  4002. /** Returns a clock-cycle tick counter, if available.
  4003. If the machine can do it, this will return a tick-count
  4004. where each tick is one cpu clock cycle - used for profiling
  4005. code.
  4006. @returns the tick count, or zero if not available.
  4007. */
  4008. static int64 getClockCycleCounter() throw();
  4009. /** Finds out how much RAM is in the machine.
  4010. @returns the approximate number of megabytes of memory, or zero if
  4011. something goes wrong when finding out.
  4012. */
  4013. static int getMemorySizeInMegabytes() throw();
  4014. /** Returns the system page-size.
  4015. This is only used by programmers with beards.
  4016. */
  4017. static int getPageSize() throw();
  4018. /** Returns a list of MAC addresses found on this machine.
  4019. @param addresses an array into which the MAC addresses should be copied
  4020. @param maxNum the number of elements in this array
  4021. @param littleEndian the endianness of the numbers to return. Note that
  4022. the default values of this parameter are different on
  4023. Mac/PC to avoid breaking old software that was written
  4024. before this parameter was added (when the two systems
  4025. defaulted to using different endiannesses). In newer
  4026. software you probably want to specify an explicit value
  4027. for this.
  4028. @returns the number of MAC addresses that were found
  4029. */
  4030. static int getMACAddresses (int64* addresses, int maxNum,
  4031. #if JUCE_MAC
  4032. const bool littleEndian = true) throw();
  4033. #else
  4034. const bool littleEndian = false) throw();
  4035. #endif
  4036. // not-for-public-use platform-specific method gets called at startup to initialise things.
  4037. static void initialiseStats() throw();
  4038. };
  4039. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  4040. /********* End of inlined file: juce_SystemStats.h *********/
  4041. #endif
  4042. #ifndef __JUCE_TIME_JUCEHEADER__
  4043. /********* Start of inlined file: juce_Time.h *********/
  4044. #ifndef __JUCE_TIME_JUCEHEADER__
  4045. #define __JUCE_TIME_JUCEHEADER__
  4046. /**
  4047. Holds an absolute date and time.
  4048. Internally, the time is stored at millisecond precision.
  4049. @see RelativeTime
  4050. */
  4051. class JUCE_API Time
  4052. {
  4053. public:
  4054. /** Creates a Time object.
  4055. This default constructor creates a time of 1st January 1970, (which is
  4056. represented internally as 0ms).
  4057. To create a time object representing the current time, use getCurrentTime().
  4058. @see getCurrentTime
  4059. */
  4060. Time() throw();
  4061. /** Creates a copy of another Time object. */
  4062. Time (const Time& other) throw();
  4063. /** Creates a time based on a number of milliseconds.
  4064. The internal millisecond count is set to 0 (1st January 1970). To create a
  4065. time object set to the current time, use getCurrentTime().
  4066. @param millisecondsSinceEpoch the number of milliseconds since the unix
  4067. 'epoch' (midnight Jan 1st 1970).
  4068. @see getCurrentTime, currentTimeMillis
  4069. */
  4070. Time (const int64 millisecondsSinceEpoch) throw();
  4071. /** Creates a time from a set of date components.
  4072. The timezone is assumed to be whatever the system is using as its locale.
  4073. @param year the year, in 4-digit format, e.g. 2004
  4074. @param month the month, in the range 0 to 11
  4075. @param day the day of the month, in the range 1 to 31
  4076. @param hours hours in 24-hour clock format, 0 to 23
  4077. @param minutes minutes 0 to 59
  4078. @param seconds seconds 0 to 59
  4079. @param milliseconds milliseconds 0 to 999
  4080. @param useLocalTime if true, encode using the current machine's local time; if
  4081. false, it will always work in GMT.
  4082. */
  4083. Time (const int year,
  4084. const int month,
  4085. const int day,
  4086. const int hours,
  4087. const int minutes,
  4088. const int seconds = 0,
  4089. const int milliseconds = 0,
  4090. const bool useLocalTime = true) throw();
  4091. /** Destructor. */
  4092. ~Time() throw();
  4093. /** Copies this time from another one. */
  4094. const Time& operator= (const Time& other) throw();
  4095. /** Returns a Time object that is set to the current system time.
  4096. @see currentTimeMillis
  4097. */
  4098. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  4099. /** Returns the time as a number of milliseconds.
  4100. @returns the number of milliseconds this Time object represents, since
  4101. midnight jan 1st 1970.
  4102. @see getMilliseconds
  4103. */
  4104. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  4105. /** Returns the year.
  4106. A 4-digit format is used, e.g. 2004.
  4107. */
  4108. int getYear() const throw();
  4109. /** Returns the number of the month.
  4110. The value returned is in the range 0 to 11.
  4111. @see getMonthName
  4112. */
  4113. int getMonth() const throw();
  4114. /** Returns the name of the month.
  4115. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  4116. it'll return the long form, e.g. "January"
  4117. @see getMonth
  4118. */
  4119. const String getMonthName (const bool threeLetterVersion) const throw();
  4120. /** Returns the day of the month.
  4121. The value returned is in the range 1 to 31.
  4122. */
  4123. int getDayOfMonth() const throw();
  4124. /** Returns the number of the day of the week.
  4125. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  4126. */
  4127. int getDayOfWeek() const throw();
  4128. /** Returns the name of the weekday.
  4129. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  4130. false, it'll return the full version, e.g. "Tuesday".
  4131. */
  4132. const String getWeekdayName (const bool threeLetterVersion) const throw();
  4133. /** Returns the number of hours since midnight.
  4134. This is in 24-hour clock format, in the range 0 to 23.
  4135. @see getHoursInAmPmFormat, isAfternoon
  4136. */
  4137. int getHours() const throw();
  4138. /** Returns true if the time is in the afternoon.
  4139. So it returns true for "PM", false for "AM".
  4140. @see getHoursInAmPmFormat, getHours
  4141. */
  4142. bool isAfternoon() const throw();
  4143. /** Returns the hours in 12-hour clock format.
  4144. This will return a value 1 to 12 - use isAfternoon() to find out
  4145. whether this is in the afternoon or morning.
  4146. @see getHours, isAfternoon
  4147. */
  4148. int getHoursInAmPmFormat() const throw();
  4149. /** Returns the number of minutes, 0 to 59. */
  4150. int getMinutes() const throw();
  4151. /** Returns the number of seconds, 0 to 59. */
  4152. int getSeconds() const throw();
  4153. /** Returns the number of milliseconds, 0 to 999.
  4154. Unlike toMilliseconds(), this just returns the position within the
  4155. current second rather than the total number since the epoch.
  4156. @see toMilliseconds
  4157. */
  4158. int getMilliseconds() const throw();
  4159. /** Returns true if the local timezone uses a daylight saving correction. */
  4160. bool isDaylightSavingTime() const throw();
  4161. /** Returns a 3-character string to indicate the local timezone. */
  4162. const String getTimeZone() const throw();
  4163. /** Quick way of getting a string version of a date and time.
  4164. For a more powerful way of formatting the date and time, see the formatted() method.
  4165. @param includeDate whether to include the date in the string
  4166. @param includeTime whether to include the time in the string
  4167. @param includeSeconds if the time is being included, this provides an option not to include
  4168. the seconds in it
  4169. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  4170. hour notation.
  4171. @see formatted
  4172. */
  4173. const String toString (const bool includeDate,
  4174. const bool includeTime,
  4175. const bool includeSeconds = true,
  4176. const bool use24HourClock = false) const throw();
  4177. /** Converts this date/time to a string with a user-defined format.
  4178. This uses the C strftime() function to format this time as a string. To save you
  4179. looking it up, these are the escape codes that strftime uses (other codes might
  4180. work on some platforms and not others, but these are the common ones):
  4181. %a is replaced by the locale's abbreviated weekday name.
  4182. %A is replaced by the locale's full weekday name.
  4183. %b is replaced by the locale's abbreviated month name.
  4184. %B is replaced by the locale's full month name.
  4185. %c is replaced by the locale's appropriate date and time representation.
  4186. %d is replaced by the day of the month as a decimal number [01,31].
  4187. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  4188. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  4189. %j is replaced by the day of the year as a decimal number [001,366].
  4190. %m is replaced by the month as a decimal number [01,12].
  4191. %M is replaced by the minute as a decimal number [00,59].
  4192. %p is replaced by the locale's equivalent of either a.m. or p.m.
  4193. %S is replaced by the second as a decimal number [00,61].
  4194. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  4195. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  4196. %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.
  4197. %x is replaced by the locale's appropriate date representation.
  4198. %X is replaced by the locale's appropriate time representation.
  4199. %y is replaced by the year without century as a decimal number [00,99].
  4200. %Y is replaced by the year with century as a decimal number.
  4201. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  4202. %% is replaced by %.
  4203. @see toString
  4204. */
  4205. const String formatted (const tchar* const format) const throw();
  4206. /** Adds a RelativeTime to this time and returns the result. */
  4207. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  4208. /** Subtracts a RelativeTime from this time and returns the result. */
  4209. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  4210. /** Returns the relative time difference between this time and another one. */
  4211. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  4212. /** Compares two Time objects. */
  4213. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  4214. /** Compares two Time objects. */
  4215. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  4216. /** Compares two Time objects. */
  4217. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  4218. /** Compares two Time objects. */
  4219. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  4220. /** Compares two Time objects. */
  4221. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  4222. /** Compares two Time objects. */
  4223. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  4224. /** Tries to set the computer's clock.
  4225. @returns true if this succeeds, although depending on the system, the
  4226. application might not have sufficient privileges to do this.
  4227. */
  4228. bool setSystemTimeToThisTime() const throw();
  4229. /** Returns the name of a day of the week.
  4230. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  4231. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  4232. false, it'll return the full version, e.g. "Tuesday".
  4233. */
  4234. static const String getWeekdayName (int dayNumber,
  4235. const bool threeLetterVersion) throw();
  4236. /** Returns the name of one of the months.
  4237. @param monthNumber the month, 0 to 11
  4238. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  4239. it'll return the long form, e.g. "January"
  4240. */
  4241. static const String getMonthName (int monthNumber,
  4242. const bool threeLetterVersion) throw();
  4243. // Static methods for getting system timers directly..
  4244. /** Returns the current system time.
  4245. Returns the number of milliseconds since midnight jan 1st 1970.
  4246. Should be accurate to within a few millisecs, depending on platform,
  4247. hardware, etc.
  4248. */
  4249. static int64 currentTimeMillis() throw();
  4250. /** Returns the number of millisecs since system startup.
  4251. Should be accurate to within a few millisecs, depending on platform,
  4252. hardware, etc.
  4253. @see getApproximateMillisecondCounter
  4254. */
  4255. static uint32 getMillisecondCounter() throw();
  4256. /** Returns the number of millisecs since system startup.
  4257. Same as getMillisecondCounter(), but returns a more accurate value, using
  4258. the high-res timer.
  4259. @see getMillisecondCounter
  4260. */
  4261. static double getMillisecondCounterHiRes() throw();
  4262. /** Waits until the getMillisecondCounter() reaches a given value.
  4263. This will make the thread sleep as efficiently as it can while it's waiting.
  4264. */
  4265. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  4266. /** Less-accurate but faster version of getMillisecondCounter().
  4267. This will return the last value that getMillisecondCounter() returned, so doesn't
  4268. need to make a system call, but is less accurate - it shouldn't be more than
  4269. 100ms away from the correct time, though, so is still accurate enough for a
  4270. lot of purposes.
  4271. @see getMillisecondCounter
  4272. */
  4273. static uint32 getApproximateMillisecondCounter() throw();
  4274. // High-resolution timers..
  4275. /** Returns the current high-resolution counter's tick-count.
  4276. This is a similar idea to getMillisecondCounter(), but with a higher
  4277. resolution.
  4278. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  4279. secondsToHighResolutionTicks
  4280. */
  4281. static int64 getHighResolutionTicks() throw();
  4282. /** Returns the resolution of the high-resolution counter in ticks per second.
  4283. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  4284. secondsToHighResolutionTicks
  4285. */
  4286. static int64 getHighResolutionTicksPerSecond() throw();
  4287. /** Converts a number of high-resolution ticks into seconds.
  4288. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  4289. secondsToHighResolutionTicks
  4290. */
  4291. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  4292. /** Converts a number seconds into high-resolution ticks.
  4293. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  4294. highResolutionTicksToSeconds
  4295. */
  4296. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  4297. private:
  4298. int64 millisSinceEpoch;
  4299. };
  4300. #endif // __JUCE_TIME_JUCEHEADER__
  4301. /********* End of inlined file: juce_Time.h *********/
  4302. #endif
  4303. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4304. /********* Start of inlined file: juce_Atomic.h *********/
  4305. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4306. #define __JUCE_ATOMIC_JUCEHEADER__
  4307. // Atomic increment/decrement operations..
  4308. #if JUCE_MAC && ! DOXYGEN
  4309. #if ! MACOS_10_3_OR_EARLIER
  4310. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  4311. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  4312. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  4313. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  4314. #else
  4315. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  4316. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  4317. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  4318. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  4319. #endif
  4320. #elif JUCE_GCC
  4321. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  4322. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  4323. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  4324. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  4325. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  4326. #else
  4327. /** Increments an integer in a thread-safe way. */
  4328. forcedinline void atomicIncrement (int& variable) throw()
  4329. {
  4330. __asm__ __volatile__ (
  4331. #if JUCE_64BIT
  4332. "lock incl (%%rax)"
  4333. :
  4334. : "a" (&variable)
  4335. : "cc", "memory");
  4336. #else
  4337. "lock incl %0"
  4338. : "=m" (variable)
  4339. : "m" (variable));
  4340. #endif
  4341. }
  4342. /** Increments an integer in a thread-safe way and returns the incremented value. */
  4343. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  4344. {
  4345. int result;
  4346. __asm__ __volatile__ (
  4347. #if JUCE_64BIT
  4348. "lock xaddl %%ebx, (%%rax) \n\
  4349. incl %%ebx"
  4350. : "=b" (result)
  4351. : "a" (&variable), "b" (1)
  4352. : "cc", "memory");
  4353. #else
  4354. "lock xaddl %%eax, (%%ecx) \n\
  4355. incl %%eax"
  4356. : "=a" (result)
  4357. : "c" (&variable), "a" (1)
  4358. : "memory");
  4359. #endif
  4360. return result;
  4361. }
  4362. /** Decrememts an integer in a thread-safe way. */
  4363. forcedinline void atomicDecrement (int& variable) throw()
  4364. {
  4365. __asm__ __volatile__ (
  4366. #if JUCE_64BIT
  4367. "lock decl (%%rax)"
  4368. :
  4369. : "a" (&variable)
  4370. : "cc", "memory");
  4371. #else
  4372. "lock decl %0"
  4373. : "=m" (variable)
  4374. : "m" (variable));
  4375. #endif
  4376. }
  4377. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  4378. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  4379. {
  4380. int result;
  4381. __asm__ __volatile__ (
  4382. #if JUCE_64BIT
  4383. "lock xaddl %%ebx, (%%rax) \n\
  4384. decl %%ebx"
  4385. : "=b" (result)
  4386. : "a" (&variable), "b" (-1)
  4387. : "cc", "memory");
  4388. #else
  4389. "lock xaddl %%eax, (%%ecx) \n\
  4390. decl %%eax"
  4391. : "=a" (result)
  4392. : "c" (&variable), "a" (-1)
  4393. : "memory");
  4394. #endif
  4395. return result;
  4396. }
  4397. #endif
  4398. #elif JUCE_USE_INTRINSICS
  4399. #pragma intrinsic (_InterlockedIncrement)
  4400. #pragma intrinsic (_InterlockedDecrement)
  4401. /** Increments an integer in a thread-safe way. */
  4402. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  4403. {
  4404. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  4405. }
  4406. /** Increments an integer in a thread-safe way and returns the incremented value. */
  4407. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  4408. {
  4409. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  4410. }
  4411. /** Decrememts an integer in a thread-safe way. */
  4412. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  4413. {
  4414. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  4415. }
  4416. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  4417. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  4418. {
  4419. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  4420. }
  4421. #else
  4422. /** Increments an integer in a thread-safe way. */
  4423. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  4424. {
  4425. __asm {
  4426. mov ecx, dword ptr [variable]
  4427. lock inc dword ptr [ecx]
  4428. }
  4429. }
  4430. /** Increments an integer in a thread-safe way and returns the incremented value. */
  4431. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  4432. {
  4433. int result;
  4434. __asm {
  4435. mov ecx, dword ptr [variable]
  4436. mov eax, 1
  4437. lock xadd dword ptr [ecx], eax
  4438. inc eax
  4439. mov result, eax
  4440. }
  4441. return result;
  4442. }
  4443. /** Decrememts an integer in a thread-safe way. */
  4444. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  4445. {
  4446. __asm {
  4447. mov ecx, dword ptr [variable]
  4448. lock dec dword ptr [ecx]
  4449. }
  4450. }
  4451. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  4452. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  4453. {
  4454. int result;
  4455. __asm {
  4456. mov ecx, dword ptr [variable]
  4457. mov eax, -1
  4458. lock xadd dword ptr [ecx], eax
  4459. dec eax
  4460. mov result, eax
  4461. }
  4462. return result;
  4463. }
  4464. #endif
  4465. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4466. /********* End of inlined file: juce_Atomic.h *********/
  4467. #endif
  4468. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  4469. #endif
  4470. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  4471. /********* Start of inlined file: juce_FileLogger.h *********/
  4472. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  4473. #define __JUCE_FILELOGGER_JUCEHEADER__
  4474. /********* Start of inlined file: juce_File.h *********/
  4475. #ifndef __JUCE_FILE_JUCEHEADER__
  4476. #define __JUCE_FILE_JUCEHEADER__
  4477. /********* Start of inlined file: juce_OwnedArray.h *********/
  4478. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4479. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4480. /** An array designed for holding objects.
  4481. This holds a list of pointers to objects, and will automatically
  4482. delete the objects when they are removed from the array, or when the
  4483. array is itself deleted.
  4484. Declare it in the form: OwnedArray<MyObjectClass>
  4485. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  4486. After adding objects, they are 'owned' by the array and will be deleted when
  4487. removed or replaced.
  4488. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  4489. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  4490. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  4491. */
  4492. template <class ObjectClass,
  4493. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  4494. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  4495. {
  4496. public:
  4497. /** Creates an empty array.
  4498. @param granularity this is the size of increment by which the internal storage
  4499. used by the array will grow. Only change it from the default if you know the
  4500. array is going to be very big and needs to be able to grow efficiently.
  4501. @see ArrayAllocationBase
  4502. */
  4503. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  4504. : ArrayAllocationBase <ObjectClass*> (granularity),
  4505. numUsed (0)
  4506. {
  4507. }
  4508. /** Deletes the array and also deletes any objects inside it.
  4509. To get rid of the array without deleting its objects, use its
  4510. clear (false) method before deleting it.
  4511. */
  4512. ~OwnedArray()
  4513. {
  4514. clear (true);
  4515. }
  4516. /** Clears the array, optionally deleting the objects inside it first. */
  4517. void clear (const bool deleteObjects = true)
  4518. {
  4519. lock.enter();
  4520. if (deleteObjects)
  4521. {
  4522. while (numUsed > 0)
  4523. delete this->elements [--numUsed];
  4524. }
  4525. this->setAllocatedSize (0);
  4526. numUsed = 0;
  4527. lock.exit();
  4528. }
  4529. /** Returns the number of items currently in the array.
  4530. @see operator[]
  4531. */
  4532. inline int size() const throw()
  4533. {
  4534. return numUsed;
  4535. }
  4536. /** Returns a pointer to the object at this index in the array.
  4537. If the index is out-of-range, this will return a null pointer, (and
  4538. it could be null anyway, because it's ok for the array to hold null
  4539. pointers as well as objects).
  4540. @see getUnchecked
  4541. */
  4542. inline ObjectClass* operator[] (const int index) const throw()
  4543. {
  4544. lock.enter();
  4545. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  4546. ? this->elements [index]
  4547. : (ObjectClass*) 0;
  4548. lock.exit();
  4549. return result;
  4550. }
  4551. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  4552. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  4553. it can be used when you're sure the index if always going to be legal.
  4554. */
  4555. inline ObjectClass* getUnchecked (const int index) const throw()
  4556. {
  4557. lock.enter();
  4558. jassert (((unsigned int) index) < (unsigned int) numUsed);
  4559. ObjectClass* const result = this->elements [index];
  4560. lock.exit();
  4561. return result;
  4562. }
  4563. /** Returns a pointer to the first object in the array.
  4564. This will return a null pointer if the array's empty.
  4565. @see getLast
  4566. */
  4567. inline ObjectClass* getFirst() const throw()
  4568. {
  4569. lock.enter();
  4570. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  4571. : (ObjectClass*) 0;
  4572. lock.exit();
  4573. return result;
  4574. }
  4575. /** Returns a pointer to the last object in the array.
  4576. This will return a null pointer if the array's empty.
  4577. @see getFirst
  4578. */
  4579. inline ObjectClass* getLast() const throw()
  4580. {
  4581. lock.enter();
  4582. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  4583. : (ObjectClass*) 0;
  4584. lock.exit();
  4585. return result;
  4586. }
  4587. /** Finds the index of an object which might be in the array.
  4588. @param objectToLookFor the object to look for
  4589. @returns the index at which the object was found, or -1 if it's not found
  4590. */
  4591. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  4592. {
  4593. int result = -1;
  4594. lock.enter();
  4595. ObjectClass* const* e = this->elements;
  4596. for (int i = numUsed; --i >= 0;)
  4597. {
  4598. if (objectToLookFor == *e)
  4599. {
  4600. result = (int) (e - this->elements);
  4601. break;
  4602. }
  4603. ++e;
  4604. }
  4605. lock.exit();
  4606. return result;
  4607. }
  4608. /** Returns true if the array contains a specified object.
  4609. @param objectToLookFor the object to look for
  4610. @returns true if the object is in the array
  4611. */
  4612. bool contains (const ObjectClass* const objectToLookFor) const throw()
  4613. {
  4614. lock.enter();
  4615. ObjectClass* const* e = this->elements;
  4616. int i = numUsed;
  4617. while (i >= 4)
  4618. {
  4619. if (objectToLookFor == *e
  4620. || objectToLookFor == *++e
  4621. || objectToLookFor == *++e
  4622. || objectToLookFor == *++e)
  4623. {
  4624. lock.exit();
  4625. return true;
  4626. }
  4627. i -= 4;
  4628. ++e;
  4629. }
  4630. while (i > 0)
  4631. {
  4632. if (objectToLookFor == *e)
  4633. {
  4634. lock.exit();
  4635. return true;
  4636. }
  4637. --i;
  4638. ++e;
  4639. }
  4640. lock.exit();
  4641. return false;
  4642. }
  4643. /** Appends a new object to the end of the array.
  4644. Note that the this object will be deleted by the OwnedArray when it
  4645. is removed, so be careful not to delete it somewhere else.
  4646. Also be careful not to add the same object to the array more than once,
  4647. as this will obviously cause deletion of dangling pointers.
  4648. @param newObject the new object to add to the array
  4649. @see set, insert, addIfNotAlreadyThere, addSorted
  4650. */
  4651. void add (const ObjectClass* const newObject) throw()
  4652. {
  4653. lock.enter();
  4654. this->ensureAllocatedSize (numUsed + 1);
  4655. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  4656. lock.exit();
  4657. }
  4658. /** Inserts a new object into the array at the given index.
  4659. Note that the this object will be deleted by the OwnedArray when it
  4660. is removed, so be careful not to delete it somewhere else.
  4661. If the index is less than 0 or greater than the size of the array, the
  4662. element will be added to the end of the array.
  4663. Otherwise, it will be inserted into the array, moving all the later elements
  4664. along to make room.
  4665. Be careful not to add the same object to the array more than once,
  4666. as this will obviously cause deletion of dangling pointers.
  4667. @param indexToInsertAt the index at which the new element should be inserted
  4668. @param newObject the new object to add to the array
  4669. @see add, addSorted, addIfNotAlreadyThere, set
  4670. */
  4671. void insert (int indexToInsertAt,
  4672. const ObjectClass* const newObject) throw()
  4673. {
  4674. if (indexToInsertAt >= 0)
  4675. {
  4676. lock.enter();
  4677. if (indexToInsertAt > numUsed)
  4678. indexToInsertAt = numUsed;
  4679. this->ensureAllocatedSize (numUsed + 1);
  4680. ObjectClass** const e = this->elements + indexToInsertAt;
  4681. const int numToMove = numUsed - indexToInsertAt;
  4682. if (numToMove > 0)
  4683. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  4684. *e = const_cast <ObjectClass*> (newObject);
  4685. ++numUsed;
  4686. lock.exit();
  4687. }
  4688. else
  4689. {
  4690. add (newObject);
  4691. }
  4692. }
  4693. /** Appends a new object at the end of the array as long as the array doesn't
  4694. already contain it.
  4695. If the array already contains a matching object, nothing will be done.
  4696. @param newObject the new object to add to the array
  4697. */
  4698. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  4699. {
  4700. lock.enter();
  4701. if (! contains (newObject))
  4702. add (newObject);
  4703. lock.exit();
  4704. }
  4705. /** Replaces an object in the array with a different one.
  4706. If the index is less than zero, this method does nothing.
  4707. If the index is beyond the end of the array, the new object is added to the end of the array.
  4708. Be careful not to add the same object to the array more than once,
  4709. as this will obviously cause deletion of dangling pointers.
  4710. @param indexToChange the index whose value you want to change
  4711. @param newObject the new value to set for this index.
  4712. @param deleteOldElement whether to delete the object that's being replaced with the new one
  4713. @see add, insert, remove
  4714. */
  4715. void set (const int indexToChange,
  4716. const ObjectClass* const newObject,
  4717. const bool deleteOldElement = true)
  4718. {
  4719. if (indexToChange >= 0)
  4720. {
  4721. ObjectClass* toDelete = 0;
  4722. lock.enter();
  4723. if (indexToChange < numUsed)
  4724. {
  4725. if (deleteOldElement)
  4726. toDelete = this->elements [indexToChange];
  4727. if (toDelete == newObject)
  4728. toDelete = 0;
  4729. else
  4730. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  4731. }
  4732. else
  4733. {
  4734. this->ensureAllocatedSize (numUsed + 1);
  4735. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  4736. }
  4737. lock.exit();
  4738. delete toDelete;
  4739. }
  4740. }
  4741. /** Inserts a new object into the array assuming that the array is sorted.
  4742. This will use a comparator to find the position at which the new object
  4743. should go. If the array isn't sorted, the behaviour of this
  4744. method will be unpredictable.
  4745. @param comparator the comparator to use to compare the elements - see the sort method
  4746. for details about this object's structure
  4747. @param newObject the new object to insert to the array
  4748. @see add, sort, indexOfSorted
  4749. */
  4750. template <class ElementComparator>
  4751. void addSorted (ElementComparator& comparator,
  4752. ObjectClass* const newObject) throw()
  4753. {
  4754. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4755. // avoids getting warning messages about the parameter being unused
  4756. lock.enter();
  4757. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  4758. lock.exit();
  4759. }
  4760. /** Finds the index of an object in the array, assuming that the array is sorted.
  4761. This will use a comparator to do a binary-chop to find the index of the given
  4762. element, if it exists. If the array isn't sorted, the behaviour of this
  4763. method will be unpredictable.
  4764. @param comparator the comparator to use to compare the elements - see the sort()
  4765. method for details about the form this object should take
  4766. @param objectToLookFor the object to search for
  4767. @returns the index of the element, or -1 if it's not found
  4768. @see addSorted, sort
  4769. */
  4770. template <class ElementComparator>
  4771. int indexOfSorted (ElementComparator& comparator,
  4772. const ObjectClass* const objectToLookFor) const throw()
  4773. {
  4774. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4775. // avoids getting warning messages about the parameter being unused
  4776. lock.enter();
  4777. int start = 0;
  4778. int end = numUsed;
  4779. for (;;)
  4780. {
  4781. if (start >= end)
  4782. {
  4783. lock.exit();
  4784. return -1;
  4785. }
  4786. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  4787. {
  4788. lock.exit();
  4789. return start;
  4790. }
  4791. else
  4792. {
  4793. const int halfway = (start + end) >> 1;
  4794. if (halfway == start)
  4795. {
  4796. lock.exit();
  4797. return -1;
  4798. }
  4799. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  4800. start = halfway;
  4801. else
  4802. end = halfway;
  4803. }
  4804. }
  4805. }
  4806. /** Removes an object from the array.
  4807. This will remove the object at a given index (optionally also
  4808. deleting it) and move back all the subsequent objects to close the gap.
  4809. If the index passed in is out-of-range, nothing will happen.
  4810. @param indexToRemove the index of the element to remove
  4811. @param deleteObject whether to delete the object that is removed
  4812. @see removeObject, removeRange
  4813. */
  4814. void remove (const int indexToRemove,
  4815. const bool deleteObject = true)
  4816. {
  4817. lock.enter();
  4818. ObjectClass* toDelete = 0;
  4819. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4820. {
  4821. ObjectClass** const e = this->elements + indexToRemove;
  4822. if (deleteObject)
  4823. toDelete = *e;
  4824. --numUsed;
  4825. const int numToShift = numUsed - indexToRemove;
  4826. if (numToShift > 0)
  4827. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  4828. if ((numUsed << 1) < this->numAllocated)
  4829. minimiseStorageOverheads();
  4830. }
  4831. lock.exit();
  4832. delete toDelete;
  4833. }
  4834. /** Removes a specified object from the array.
  4835. If the item isn't found, no action is taken.
  4836. @param objectToRemove the object to try to remove
  4837. @param deleteObject whether to delete the object (if it's found)
  4838. @see remove, removeRange
  4839. */
  4840. void removeObject (const ObjectClass* const objectToRemove,
  4841. const bool deleteObject = true)
  4842. {
  4843. lock.enter();
  4844. ObjectClass** e = this->elements;
  4845. for (int i = numUsed; --i >= 0;)
  4846. {
  4847. if (objectToRemove == *e)
  4848. {
  4849. remove ((int) (e - this->elements), deleteObject);
  4850. break;
  4851. }
  4852. ++e;
  4853. }
  4854. lock.exit();
  4855. }
  4856. /** Removes a range of objects from the array.
  4857. This will remove a set of objects, starting from the given index,
  4858. and move any subsequent elements down to close the gap.
  4859. If the range extends beyond the bounds of the array, it will
  4860. be safely clipped to the size of the array.
  4861. @param startIndex the index of the first object to remove
  4862. @param numberToRemove how many objects should be removed
  4863. @param deleteObjects whether to delete the objects that get removed
  4864. @see remove, removeObject
  4865. */
  4866. void removeRange (int startIndex,
  4867. const int numberToRemove,
  4868. const bool deleteObjects = true)
  4869. {
  4870. lock.enter();
  4871. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4872. startIndex = jlimit (0, numUsed, startIndex);
  4873. if (endIndex > startIndex)
  4874. {
  4875. if (deleteObjects)
  4876. {
  4877. for (int i = startIndex; i < endIndex; ++i)
  4878. {
  4879. delete this->elements [i];
  4880. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  4881. }
  4882. }
  4883. const int rangeSize = endIndex - startIndex;
  4884. ObjectClass** e = this->elements + startIndex;
  4885. int numToShift = numUsed - endIndex;
  4886. numUsed -= rangeSize;
  4887. while (--numToShift >= 0)
  4888. {
  4889. *e = e [rangeSize];
  4890. ++e;
  4891. }
  4892. if ((numUsed << 1) < this->numAllocated)
  4893. minimiseStorageOverheads();
  4894. }
  4895. lock.exit();
  4896. }
  4897. /** Removes the last n objects from the array.
  4898. @param howManyToRemove how many objects to remove from the end of the array
  4899. @param deleteObjects whether to also delete the objects that are removed
  4900. @see remove, removeObject, removeRange
  4901. */
  4902. void removeLast (int howManyToRemove = 1,
  4903. const bool deleteObjects = true)
  4904. {
  4905. lock.enter();
  4906. if (howManyToRemove >= numUsed)
  4907. {
  4908. clear (deleteObjects);
  4909. }
  4910. else
  4911. {
  4912. while (--howManyToRemove >= 0)
  4913. remove (numUsed - 1, deleteObjects);
  4914. }
  4915. lock.exit();
  4916. }
  4917. /** Swaps a pair of objects in the array.
  4918. If either of the indexes passed in is out-of-range, nothing will happen,
  4919. otherwise the two objects at these positions will be exchanged.
  4920. */
  4921. void swap (const int index1,
  4922. const int index2) throw()
  4923. {
  4924. lock.enter();
  4925. if (((unsigned int) index1) < (unsigned int) numUsed
  4926. && ((unsigned int) index2) < (unsigned int) numUsed)
  4927. {
  4928. swapVariables (this->elements [index1],
  4929. this->elements [index2]);
  4930. }
  4931. lock.exit();
  4932. }
  4933. /** Moves one of the objects to a different position.
  4934. This will move the object to a specified index, shuffling along
  4935. any intervening elements as required.
  4936. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4937. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4938. @param currentIndex the index of the object to be moved. If this isn't a
  4939. valid index, then nothing will be done
  4940. @param newIndex the index at which you'd like this object to end up. If this
  4941. is less than zero, it will be moved to the end of the array
  4942. */
  4943. void move (const int currentIndex,
  4944. int newIndex) throw()
  4945. {
  4946. if (currentIndex != newIndex)
  4947. {
  4948. lock.enter();
  4949. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4950. {
  4951. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4952. newIndex = numUsed - 1;
  4953. ObjectClass* const value = this->elements [currentIndex];
  4954. if (newIndex > currentIndex)
  4955. {
  4956. memmove (this->elements + currentIndex,
  4957. this->elements + currentIndex + 1,
  4958. (newIndex - currentIndex) * sizeof (ObjectClass*));
  4959. }
  4960. else
  4961. {
  4962. memmove (this->elements + newIndex + 1,
  4963. this->elements + newIndex,
  4964. (currentIndex - newIndex) * sizeof (ObjectClass*));
  4965. }
  4966. this->elements [newIndex] = value;
  4967. }
  4968. lock.exit();
  4969. }
  4970. }
  4971. /** This swaps the contents of this array with those of another array.
  4972. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  4973. because it just swaps their internal pointers.
  4974. */
  4975. template <class OtherArrayType>
  4976. void swapWithArray (OtherArrayType& otherArray) throw()
  4977. {
  4978. lock.enter();
  4979. otherArray.lock.enter();
  4980. swapVariables <int> (this->numUsed, otherArray.numUsed);
  4981. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  4982. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  4983. otherArray.lock.exit();
  4984. lock.exit();
  4985. }
  4986. /** Reduces the amount of storage being used by the array.
  4987. Arrays typically allocate slightly more storage than they need, and after
  4988. removing elements, they may have quite a lot of unused space allocated.
  4989. This method will reduce the amount of allocated storage to a minimum.
  4990. */
  4991. void minimiseStorageOverheads() throw()
  4992. {
  4993. lock.enter();
  4994. if (numUsed == 0)
  4995. {
  4996. this->setAllocatedSize (0);
  4997. }
  4998. else
  4999. {
  5000. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  5001. if (newAllocation < this->numAllocated)
  5002. this->setAllocatedSize (newAllocation);
  5003. }
  5004. lock.exit();
  5005. }
  5006. /** Increases the array's internal storage to hold a minimum number of elements.
  5007. Calling this before adding a large known number of elements means that
  5008. the array won't have to keep dynamically resizing itself as the elements
  5009. are added, and it'll therefore be more efficient.
  5010. */
  5011. void ensureStorageAllocated (const int minNumElements) throw()
  5012. {
  5013. this->ensureAllocatedSize (minNumElements);
  5014. }
  5015. /** Sorts the elements in the array.
  5016. This will use a comparator object to sort the elements into order. The object
  5017. passed must have a method of the form:
  5018. @code
  5019. int compareElements (ElementType first, ElementType second);
  5020. @endcode
  5021. ..and this method must return:
  5022. - a value of < 0 if the first comes before the second
  5023. - a value of 0 if the two objects are equivalent
  5024. - a value of > 0 if the second comes before the first
  5025. To improve performance, the compareElements() method can be declared as static or const.
  5026. @param comparator the comparator to use for comparing elements.
  5027. @param retainOrderOfEquivalentItems if this is true, then items
  5028. which the comparator says are equivalent will be
  5029. kept in the order in which they currently appear
  5030. in the array. This is slower to perform, but may
  5031. be important in some cases. If it's false, a faster
  5032. algorithm is used, but equivalent elements may be
  5033. rearranged.
  5034. @see sortArray, indexOfSorted
  5035. */
  5036. template <class ElementComparator>
  5037. void sort (ElementComparator& comparator,
  5038. const bool retainOrderOfEquivalentItems = false) const throw()
  5039. {
  5040. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5041. // avoids getting warning messages about the parameter being unused
  5042. lock.enter();
  5043. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  5044. lock.exit();
  5045. }
  5046. /** Locks the array's CriticalSection.
  5047. Of course if the type of section used is a DummyCriticalSection, this won't
  5048. have any effect.
  5049. @see unlockArray
  5050. */
  5051. void lockArray() const throw()
  5052. {
  5053. lock.enter();
  5054. }
  5055. /** Unlocks the array's CriticalSection.
  5056. Of course if the type of section used is a DummyCriticalSection, this won't
  5057. have any effect.
  5058. @see lockArray
  5059. */
  5060. void unlockArray() const throw()
  5061. {
  5062. lock.exit();
  5063. }
  5064. juce_UseDebuggingNewOperator
  5065. private:
  5066. int numUsed;
  5067. TypeOfCriticalSectionToUse lock;
  5068. // disallow copy constructor and assignment
  5069. OwnedArray (const OwnedArray&);
  5070. const OwnedArray& operator= (const OwnedArray&);
  5071. };
  5072. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5073. /********* End of inlined file: juce_OwnedArray.h *********/
  5074. /********* Start of inlined file: juce_StringArray.h *********/
  5075. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5076. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5077. /********* Start of inlined file: juce_VoidArray.h *********/
  5078. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  5079. #define __JUCE_VOIDARRAY_JUCEHEADER__
  5080. /**
  5081. A typedef for an Array of void*'s.
  5082. VoidArrays are used in various places throughout the library instead of
  5083. more strongly-typed arrays, to keep code-size low.
  5084. */
  5085. typedef Array <void*> VoidArray;
  5086. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  5087. /********* End of inlined file: juce_VoidArray.h *********/
  5088. #ifndef DOXYGEN
  5089. // (used in StringArray::appendNumbersToDuplicates)
  5090. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  5091. static const tchar* const defaultPostNumberString = JUCE_T(")");
  5092. #endif
  5093. /**
  5094. A special array for holding a list of strings.
  5095. @see String, StringPairArray
  5096. */
  5097. class JUCE_API StringArray
  5098. {
  5099. public:
  5100. /** Creates an empty string array */
  5101. StringArray() throw();
  5102. /** Creates a copy of another string array */
  5103. StringArray (const StringArray& other) throw();
  5104. /** Creates a copy of an array of string literals.
  5105. @param strings an array of strings to add. Null pointers in the array will be
  5106. treated as empty strings
  5107. @param numberOfStrings how many items there are in the array
  5108. */
  5109. StringArray (const juce_wchar** const strings,
  5110. const int numberOfStrings) throw();
  5111. /** Creates a copy of an array of string literals.
  5112. @param strings an array of strings to add. Null pointers in the array will be
  5113. treated as empty strings
  5114. @param numberOfStrings how many items there are in the array
  5115. */
  5116. StringArray (const char** const strings,
  5117. const int numberOfStrings) throw();
  5118. /** Creates a copy of a null-terminated array of string literals.
  5119. Each item from the array passed-in is added, until it encounters a null pointer,
  5120. at which point it stops.
  5121. */
  5122. StringArray (const juce_wchar** const strings) throw();
  5123. /** Creates a copy of a null-terminated array of string literals.
  5124. Each item from the array passed-in is added, until it encounters a null pointer,
  5125. at which point it stops.
  5126. */
  5127. StringArray (const char** const strings) throw();
  5128. /** Destructor. */
  5129. virtual ~StringArray() throw();
  5130. /** Copies the contents of another string array into this one */
  5131. const StringArray& operator= (const StringArray& other) throw();
  5132. /** Compares two arrays.
  5133. Comparisons are case-sensitive.
  5134. @returns true only if the other array contains exactly the same strings in the same order
  5135. */
  5136. bool operator== (const StringArray& other) const throw();
  5137. /** Compares two arrays.
  5138. Comparisons are case-sensitive.
  5139. @returns false if the other array contains exactly the same strings in the same order
  5140. */
  5141. bool operator!= (const StringArray& other) const throw();
  5142. /** Returns the number of strings in the array */
  5143. inline int size() const throw() { return strings.size(); };
  5144. /** Returns one of the strings from the array.
  5145. If the index is out-of-range, an empty string is returned.
  5146. Obviously the reference returned shouldn't be stored for later use, as the
  5147. string it refers to may disappear when the array changes.
  5148. */
  5149. const String& operator[] (const int index) const throw();
  5150. /** Searches for a string in the array.
  5151. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5152. @returns true if the string is found inside the array
  5153. */
  5154. bool contains (const String& stringToLookFor,
  5155. const bool ignoreCase = false) const throw();
  5156. /** Searches for a string in the array.
  5157. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5158. @param stringToLookFor the string to try to find
  5159. @param ignoreCase whether the comparison should be case-insensitive
  5160. @param startIndex the first index to start searching from
  5161. @returns the index of the first occurrence of the string in this array,
  5162. or -1 if it isn't found.
  5163. */
  5164. int indexOf (const String& stringToLookFor,
  5165. const bool ignoreCase = false,
  5166. int startIndex = 0) const throw();
  5167. /** Appends a string at the end of the array. */
  5168. void add (const String& stringToAdd) throw();
  5169. /** Inserts a string into the array.
  5170. This will insert a string into the array at the given index, moving
  5171. up the other elements to make room for it.
  5172. If the index is less than zero or greater than the size of the array,
  5173. the new string will be added to the end of the array.
  5174. */
  5175. void insert (const int index,
  5176. const String& stringToAdd) throw();
  5177. /** Adds a string to the array as long as it's not already in there.
  5178. The search can optionally be case-insensitive.
  5179. */
  5180. void addIfNotAlreadyThere (const String& stringToAdd,
  5181. const bool ignoreCase = false) throw();
  5182. /** Replaces one of the strings in the array with another one.
  5183. If the index is higher than the array's size, the new string will be
  5184. added to the end of the array; if it's less than zero nothing happens.
  5185. */
  5186. void set (const int index,
  5187. const String& newString) throw();
  5188. /** Appends some strings from another array to the end of this one.
  5189. @param other the array to add
  5190. @param startIndex the first element of the other array to add
  5191. @param numElementsToAdd the maximum number of elements to add (if this is
  5192. less than zero, they are all added)
  5193. */
  5194. void addArray (const StringArray& other,
  5195. int startIndex = 0,
  5196. int numElementsToAdd = -1) throw();
  5197. /** Breaks up a string into tokens and adds them to this array.
  5198. This will tokenise the given string using whitespace characters as the
  5199. token delimiters, and will add these tokens to the end of the array.
  5200. @returns the number of tokens added
  5201. */
  5202. int addTokens (const tchar* const stringToTokenise,
  5203. const bool preserveQuotedStrings) throw();
  5204. /** Breaks up a string into tokens and adds them to this array.
  5205. This will tokenise the given string (using the string passed in to define the
  5206. token delimiters), and will add these tokens to the end of the array.
  5207. @param stringToTokenise the string to tokenise
  5208. @param breakCharacters a string of characters, any of which will be considered
  5209. to be a token delimiter.
  5210. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5211. which are treated as quotes. Any text occurring
  5212. between quotes is not broken up into tokens.
  5213. @returns the number of tokens added
  5214. */
  5215. int addTokens (const tchar* const stringToTokenise,
  5216. const tchar* breakCharacters,
  5217. const tchar* quoteCharacters) throw();
  5218. /** Breaks up a string into lines and adds them to this array.
  5219. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5220. to the array. Line-break characters are omitted from the strings that are added to
  5221. the array.
  5222. */
  5223. int addLines (const tchar* stringToBreakUp) throw();
  5224. /** Removes all elements from the array. */
  5225. void clear() throw();
  5226. /** Removes a string from the array.
  5227. If the index is out-of-range, no action will be taken.
  5228. */
  5229. void remove (const int index) throw();
  5230. /** Finds a string in the array and removes it.
  5231. This will remove the first occurrence of the given string from the array. The
  5232. comparison may be case-insensitive depending on the ignoreCase parameter.
  5233. */
  5234. void removeString (const String& stringToRemove,
  5235. const bool ignoreCase = false) throw();
  5236. /** Removes any duplicated elements from the array.
  5237. If any string appears in the array more than once, only the first occurrence of
  5238. it will be retained.
  5239. @param ignoreCase whether to use a case-insensitive comparison
  5240. */
  5241. void removeDuplicates (const bool ignoreCase) throw();
  5242. /** Removes empty strings from the array.
  5243. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5244. characters will also be removed
  5245. */
  5246. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  5247. /** Moves one of the strings to a different position.
  5248. This will move the string to a specified index, shuffling along
  5249. any intervening elements as required.
  5250. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5251. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5252. @param currentIndex the index of the value to be moved. If this isn't a
  5253. valid index, then nothing will be done
  5254. @param newIndex the index at which you'd like this value to end up. If this
  5255. is less than zero, the value will be moved to the end
  5256. of the array
  5257. */
  5258. void move (const int currentIndex, int newIndex) throw();
  5259. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5260. void trim() throw();
  5261. /** Adds numbers to the strings in the array, to make each string unique.
  5262. This will add numbers to the ends of groups of similar strings.
  5263. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5264. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5265. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5266. also has a number appended to it.
  5267. @param preNumberString when adding a number, this string is added before the number
  5268. @param postNumberString this string is appended after any numbers that are added
  5269. */
  5270. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  5271. const bool appendNumberToFirstInstance,
  5272. const tchar* const preNumberString = defaultPreNumberString,
  5273. const tchar* const postNumberString = defaultPostNumberString) throw();
  5274. /** Joins the strings in the array together into one string.
  5275. This will join a range of elements from the array into a string, separating
  5276. them with a given string.
  5277. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5278. @param separatorString the string to insert between all the strings
  5279. @param startIndex the first element to join
  5280. @param numberOfElements how many elements to join together. If this is less
  5281. than zero, all available elements will be used.
  5282. */
  5283. const String joinIntoString (const String& separatorString,
  5284. int startIndex = 0,
  5285. int numberOfElements = -1) const throw();
  5286. /** Sorts the array into alphabetical order.
  5287. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5288. */
  5289. void sort (const bool ignoreCase) throw();
  5290. /** Reduces the amount of storage being used by the array.
  5291. Arrays typically allocate slightly more storage than they need, and after
  5292. removing elements, they may have quite a lot of unused space allocated.
  5293. This method will reduce the amount of allocated storage to a minimum.
  5294. */
  5295. void minimiseStorageOverheads() throw();
  5296. juce_UseDebuggingNewOperator
  5297. private:
  5298. VoidArray strings;
  5299. };
  5300. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5301. /********* End of inlined file: juce_StringArray.h *********/
  5302. /********* Start of inlined file: juce_MemoryBlock.h *********/
  5303. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  5304. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  5305. /**
  5306. A class to hold a resizable block of raw data.
  5307. */
  5308. class JUCE_API MemoryBlock
  5309. {
  5310. public:
  5311. /** Create an uninitialised block with 0 size. */
  5312. MemoryBlock() throw();
  5313. /** Creates a memory block with a given initial size.
  5314. @param initialSize the size of block to create
  5315. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  5316. */
  5317. MemoryBlock (const int initialSize,
  5318. const bool initialiseToZero = false) throw();
  5319. /** Creates a copy of another memory block. */
  5320. MemoryBlock (const MemoryBlock& other) throw();
  5321. /** Creates a memory block using a copy of a block of data.
  5322. @param dataToInitialiseFrom some data to copy into this block
  5323. @param sizeInBytes how much space to use
  5324. */
  5325. MemoryBlock (const void* const dataToInitialiseFrom,
  5326. const int sizeInBytes) throw();
  5327. /** Destructor. */
  5328. ~MemoryBlock() throw();
  5329. /** Copies another memory block onto this one.
  5330. This block will be resized and copied to exactly match the other one.
  5331. */
  5332. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  5333. /** Compares two memory blocks.
  5334. @returns true only if the two blocks are the same size and have identical contents.
  5335. */
  5336. bool operator== (const MemoryBlock& other) const throw();
  5337. /** Compares two memory blocks.
  5338. @returns true if the two blocks are different sizes or have different contents.
  5339. */
  5340. bool operator!= (const MemoryBlock& other) const throw();
  5341. /** Returns a pointer to the data, casting it to any type of primitive data required.
  5342. Note that the pointer returned will probably become invalid when the
  5343. block is resized.
  5344. */
  5345. template <class DataType>
  5346. operator DataType*() const throw() { return (DataType*) data; }
  5347. /** Returns a void pointer to the data.
  5348. Note that the pointer returned will probably become invalid when the
  5349. block is resized.
  5350. */
  5351. void* getData() const throw() { return data; }
  5352. /** Returns a byte from the memory block.
  5353. This returns a reference, so you can also use it to set a byte.
  5354. */
  5355. char& operator[] (const int offset) const throw() { return data [offset]; }
  5356. /** Returns the block's current allocated size, in bytes. */
  5357. int getSize() const throw() { return size; }
  5358. /** Resizes the memory block.
  5359. This will try to keep as much of the block's current content as it can,
  5360. and can optionally be made to clear any new space that gets allocated at
  5361. the end of the block.
  5362. @param newSize the new desired size for the block
  5363. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  5364. whether to clear the new section or just leave it
  5365. uninitialised
  5366. @see ensureSize
  5367. */
  5368. void setSize (const int newSize,
  5369. const bool initialiseNewSpaceToZero = false) throw();
  5370. /** Increases the block's size only if it's smaller than a given size.
  5371. @param minimumSize if the block is already bigger than this size, no action
  5372. will be taken; otherwise it will be increased to this size
  5373. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  5374. whether to clear the new section or just leave it
  5375. uninitialised
  5376. @see setSize
  5377. */
  5378. void ensureSize (const int minimumSize,
  5379. const bool initialiseNewSpaceToZero = false) throw();
  5380. /** Fills the entire memory block with a repeated byte value.
  5381. This is handy for clearing a block of memory to zero.
  5382. */
  5383. void fillWith (const uint8 valueToUse) throw();
  5384. /** Adds another block of data to the end of this one.
  5385. This block's size will be increased accordingly.
  5386. */
  5387. void append (const void* const data,
  5388. const int numBytes) throw();
  5389. /** Copies data into this MemoryBlock from a memory address.
  5390. @param srcData the memory location of the data to copy into this block
  5391. @param destinationOffset the offset in this block at which the data being copied should begin
  5392. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  5393. it will be clipped so not to do anything nasty)
  5394. */
  5395. void copyFrom (const void* srcData,
  5396. int destinationOffset,
  5397. int numBytes) throw();
  5398. /** Copies data from this MemoryBlock to a memory address.
  5399. @param destData the memory location to write to
  5400. @param sourceOffset the offset within this block from which the copied data will be read
  5401. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  5402. zeros will be used for that portion of the data)
  5403. */
  5404. void copyTo (void* destData,
  5405. int sourceOffset,
  5406. int numBytes) const throw();
  5407. /** Chops out a section of the block.
  5408. This will remove a section of the memory block and close the gap around it,
  5409. shifting any subsequent data downwards and reducing the size of the block.
  5410. If the range specified goes beyond the size of the block, it will be clipped.
  5411. */
  5412. void removeSection (int startByte, int numBytesToRemove) throw();
  5413. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  5414. characters in the system's default encoding. */
  5415. const String toString() const throw();
  5416. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  5417. The block will be resized to the number of valid bytes read from the string.
  5418. Non-hex characters in the string will be ignored.
  5419. @see String::toHexString()
  5420. */
  5421. void loadFromHexString (const String& sourceHexString) throw();
  5422. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  5423. void setBitRange (int bitRangeStart,
  5424. int numBits,
  5425. int binaryNumberToApply) throw();
  5426. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  5427. int getBitRange (int bitRangeStart,
  5428. int numBitsToRead) const throw();
  5429. /** Returns a string of characters that represent the binary contents of this block.
  5430. Uses a 64-bit encoding system to allow binary data to be turned into a string
  5431. of simple non-extended characters, e.g. for storage in XML.
  5432. @see fromBase64Encoding
  5433. */
  5434. const String toBase64Encoding() const throw();
  5435. /** Takes a string of encoded characters and turns it into binary data.
  5436. The string passed in must have been created by to64BitEncoding(), and this
  5437. block will be resized to recreate the original data block.
  5438. @see toBase64Encoding
  5439. */
  5440. bool fromBase64Encoding (const String& encodedString) throw();
  5441. juce_UseDebuggingNewOperator
  5442. private:
  5443. char* data;
  5444. int size;
  5445. };
  5446. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  5447. /********* End of inlined file: juce_MemoryBlock.h *********/
  5448. class FileInputStream;
  5449. class FileOutputStream;
  5450. /**
  5451. Represents a local file or directory.
  5452. This class encapsulates the absolute pathname of a file or directory, and
  5453. has methods for finding out about the file and changing its properties.
  5454. To read or write to the file, there are methods for returning an input or
  5455. output stream.
  5456. @see FileInputStream, FileOutputStream
  5457. */
  5458. class JUCE_API File
  5459. {
  5460. public:
  5461. /** Creates an (invalid) file object.
  5462. The file is initially set to an empty path, so getFullPath() will return
  5463. an empty string, and comparing the file to File::nonexistent will return
  5464. true.
  5465. You can use its operator= method to point it at a proper file.
  5466. */
  5467. File() throw() {}
  5468. /** Creates a file from an absolute path.
  5469. If the path supplied is a relative path, it is taken to be relative
  5470. to the current working directory (see File::getCurrentWorkingDirectory()),
  5471. but this isn't a recommended way of creating a file, because you
  5472. never know what the CWD is going to be.
  5473. On the Mac/Linux, the path can include "~" notation for referring to
  5474. user home directories.
  5475. */
  5476. File (const String& path) throw();
  5477. /** Creates a copy of another file object. */
  5478. File (const File& other) throw();
  5479. /** Destructor. */
  5480. ~File() throw() {}
  5481. /** Sets the file based on an absolute pathname.
  5482. If the path supplied is a relative path, it is taken to be relative
  5483. to the current working directory (see File::getCurrentWorkingDirectory()),
  5484. but this isn't a recommended way of creating a file, because you
  5485. never know what the CWD is going to be.
  5486. On the Mac/Linux, the path can include "~" notation for referring to
  5487. user home directories.
  5488. */
  5489. const File& operator= (const String& newFilePath) throw();
  5490. /** Copies from another file object. */
  5491. const File& operator= (const File& otherFile) throw();
  5492. /** This static constant is used for referring to an 'invalid' file. */
  5493. static const File nonexistent;
  5494. /** Checks whether the file actually exists.
  5495. @returns true if the file exists, either as a file or a directory.
  5496. @see existsAsFile, isDirectory
  5497. */
  5498. bool exists() const throw();
  5499. /** Checks whether the file exists and is a file rather than a directory.
  5500. @returns true only if this is a real file, false if it's a directory
  5501. or doesn't exist
  5502. @see exists, isDirectory
  5503. */
  5504. bool existsAsFile() const throw();
  5505. /** Checks whether the file is a directory that exists.
  5506. @returns true only if the file is a directory which actually exists, so
  5507. false if it's a file or doesn't exist at all
  5508. @see exists, existsAsFile
  5509. */
  5510. bool isDirectory() const throw();
  5511. /** Returns the size of the file in bytes.
  5512. @returns the number of bytes in the file, or 0 if it doesn't exist.
  5513. */
  5514. int64 getSize() const throw();
  5515. /** Utility function to convert a file size in bytes to a neat string description.
  5516. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  5517. 2000000 would produce "2 MB", etc.
  5518. */
  5519. static const String descriptionOfSizeInBytes (const int64 bytes);
  5520. /** Returns the complete, absolute path of this file.
  5521. This includes the filename and all its parent folders. On Windows it'll
  5522. also include the drive letter prefix; on Mac or Linux it'll be a complete
  5523. path starting from the root folder.
  5524. If you just want the file's name, you should use getFileName() or
  5525. getFileNameWithoutExtension().
  5526. @see getFileName, getRelativePathFrom
  5527. */
  5528. const String& getFullPathName() const throw() { return fullPath; }
  5529. /** Returns the last section of the pathname.
  5530. Returns just the final part of the path - e.g. if the whole path
  5531. is "/moose/fish/foo.txt" this will return "foo.txt".
  5532. For a directory, it returns the final part of the path - e.g. for the
  5533. directory "/moose/fish" it'll return "fish".
  5534. If the filename begins with a dot, it'll return the whole filename, e.g. for
  5535. "/moose/.fish", it'll return ".fish"
  5536. @see getFullPathName, getFileNameWithoutExtension
  5537. */
  5538. const String getFileName() const throw();
  5539. /** Creates a relative path that refers to a file relatively to a given directory.
  5540. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  5541. would return "../../foo.txt".
  5542. If it's not possible to navigate from one file to the other, an absolute
  5543. path is returned. If the paths are invalid, an empty string may also be
  5544. returned.
  5545. @param directoryToBeRelativeTo the directory which the resultant string will
  5546. be relative to. If this is actually a file rather than
  5547. a directory, its parent directory will be used instead.
  5548. If it doesn't exist, it's assumed to be a directory.
  5549. @see getChildFile, isAbsolutePath
  5550. */
  5551. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  5552. /** Returns the file's extension.
  5553. Returns the file extension of this file, also including the dot.
  5554. e.g. "/moose/fish/foo.txt" would return ".txt"
  5555. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  5556. */
  5557. const String getFileExtension() const throw();
  5558. /** Checks whether the file has a given extension.
  5559. @param extensionToTest the extension to look for - it doesn't matter whether or
  5560. not this string has a dot at the start, so ".wav" and "wav"
  5561. will have the same effect. The comparison used is
  5562. case-insensitve.
  5563. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  5564. */
  5565. bool hasFileExtension (const String& extensionToTest) const throw();
  5566. /** Returns a version of this file with a different file extension.
  5567. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  5568. @param newExtension the new extension, either with or without a dot at the start (this
  5569. doesn't make any difference). To get remove a file's extension altogether,
  5570. pass an empty string into this function.
  5571. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  5572. */
  5573. const File withFileExtension (const String& newExtension) const throw();
  5574. /** Returns the last part of the filename, without its file extension.
  5575. e.g. for "/moose/fish/foo.txt" this will return "foo".
  5576. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  5577. */
  5578. const String getFileNameWithoutExtension() const throw();
  5579. /** Returns a 32-bit hash-code that identifies this file.
  5580. This is based on the filename. Obviously it's possible, although unlikely, that
  5581. two files will have the same hash-code.
  5582. */
  5583. int hashCode() const throw();
  5584. /** Returns a 64-bit hash-code that identifies this file.
  5585. This is based on the filename. Obviously it's possible, although unlikely, that
  5586. two files will have the same hash-code.
  5587. */
  5588. int64 hashCode64() const throw();
  5589. /** Returns a file based on a relative path.
  5590. This will find a child file or directory of the current object.
  5591. e.g.
  5592. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  5593. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  5594. If the string is actually an absolute path, it will be treated as such, e.g.
  5595. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  5596. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  5597. */
  5598. const File getChildFile (String relativePath) const throw();
  5599. /** Returns a file which is in the same directory as this one.
  5600. This is equivalent to getParentDirectory().getChildFile (name).
  5601. @see getChildFile, getParentDirectory
  5602. */
  5603. const File getSiblingFile (const String& siblingFileName) const throw();
  5604. /** Returns the directory that contains this file or directory.
  5605. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  5606. */
  5607. const File getParentDirectory() const throw();
  5608. /** Checks whether a file is somewhere inside a directory.
  5609. Returns true if this file is somewhere inside a subdirectory of the directory
  5610. that is passed in. Neither file actually has to exist, because the function
  5611. just checks the paths for similarities.
  5612. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  5613. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  5614. */
  5615. bool isAChildOf (const File& potentialParentDirectory) const throw();
  5616. /** Chooses a filename relative to this one that doesn't already exist.
  5617. If this file is a directory, this will return a child file of this
  5618. directory that doesn't exist, by adding numbers to a prefix and suffix until
  5619. it finds one that isn't already there.
  5620. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  5621. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  5622. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  5623. @param prefix the string to use for the filename before the number
  5624. @param suffix the string to add to the filename after the number
  5625. @param putNumbersInBrackets if true, this will create filenames in the
  5626. format "prefix(number)suffix", if false, it will leave the
  5627. brackets out.
  5628. */
  5629. const File getNonexistentChildFile (const String& prefix,
  5630. const String& suffix,
  5631. bool putNumbersInBrackets = true) const throw();
  5632. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  5633. If this file doesn't exist, this will just return itself, otherwise it
  5634. will return an appropriate sibling that doesn't exist, e.g. if a file
  5635. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  5636. @param putNumbersInBrackets whether to add brackets around the numbers that
  5637. get appended to the new filename.
  5638. */
  5639. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  5640. /** Compares the pathnames for two files. */
  5641. bool operator== (const File& otherFile) const throw();
  5642. /** Compares the pathnames for two files. */
  5643. bool operator!= (const File& otherFile) const throw();
  5644. /** Checks whether a file can be created or written to.
  5645. @returns true if it's possible to create and write to this file. If the file
  5646. doesn't already exist, this will check its parent directory to
  5647. see if writing is allowed.
  5648. @see setReadOnly
  5649. */
  5650. bool hasWriteAccess() const throw();
  5651. /** Changes the write-permission of a file or directory.
  5652. @param shouldBeReadOnly whether to add or remove write-permission
  5653. @param applyRecursively if the file is a directory and this is true, it will
  5654. recurse through all the subfolders changing the permissions
  5655. of all files
  5656. @returns true if it manages to change the file's permissions.
  5657. @see hasWriteAccess
  5658. */
  5659. bool setReadOnly (const bool shouldBeReadOnly,
  5660. const bool applyRecursively = false) const throw();
  5661. /** Returns true if this file is a hidden or system file.
  5662. The criteria for deciding whether a file is hidden are platform-dependent.
  5663. */
  5664. bool isHidden() const throw();
  5665. /** If this file is a link, this returns the file that it points to.
  5666. If this file isn't actually link, it'll just return itself.
  5667. */
  5668. const File getLinkedTarget() const throw();
  5669. /** Returns the last modification time of this file.
  5670. @returns the time, or an invalid time if the file doesn't exist.
  5671. @see setLastModificationTime, getLastAccessTime, getCreationTime
  5672. */
  5673. const Time getLastModificationTime() const throw();
  5674. /** Returns the last time this file was accessed.
  5675. @returns the time, or an invalid time if the file doesn't exist.
  5676. @see setLastAccessTime, getLastModificationTime, getCreationTime
  5677. */
  5678. const Time getLastAccessTime() const throw();
  5679. /** Returns the time that this file was created.
  5680. @returns the time, or an invalid time if the file doesn't exist.
  5681. @see getLastModificationTime, getLastAccessTime
  5682. */
  5683. const Time getCreationTime() const throw();
  5684. /** Changes the modification time for this file.
  5685. @param newTime the time to apply to the file
  5686. @returns true if it manages to change the file's time.
  5687. @see getLastModificationTime, setLastAccessTime, setCreationTime
  5688. */
  5689. bool setLastModificationTime (const Time& newTime) const throw();
  5690. /** Changes the last-access time for this file.
  5691. @param newTime the time to apply to the file
  5692. @returns true if it manages to change the file's time.
  5693. @see getLastAccessTime, setLastModificationTime, setCreationTime
  5694. */
  5695. bool setLastAccessTime (const Time& newTime) const throw();
  5696. /** Changes the creation date for this file.
  5697. @param newTime the time to apply to the file
  5698. @returns true if it manages to change the file's time.
  5699. @see getCreationTime, setLastModificationTime, setLastAccessTime
  5700. */
  5701. bool setCreationTime (const Time& newTime) const throw();
  5702. /** If possible, this will try to create a version string for the given file.
  5703. The OS may be able to look at the file and give a version for it - e.g. with
  5704. executables, bundles, dlls, etc. If no version is available, this will
  5705. return an empty string.
  5706. */
  5707. const String getVersion() const throw();
  5708. /** Creates an empty file if it doesn't already exist.
  5709. If the file that this object refers to doesn't exist, this will create a file
  5710. of zero size.
  5711. If it already exists or is a directory, this method will do nothing.
  5712. @returns true if the file has been created (or if it already existed).
  5713. @see createDirectory
  5714. */
  5715. bool create() const throw();
  5716. /** Creates a new directory for this filename.
  5717. This will try to create the file as a directory, and fill also create
  5718. any parent directories it needs in order to complete the operation.
  5719. @returns true if the directory has been created successfully, (or if it
  5720. already existed beforehand).
  5721. @see create
  5722. */
  5723. bool createDirectory() const throw();
  5724. /** Deletes a file.
  5725. If this file is actually a directory, it may not be deleted correctly if it
  5726. contains files. See deleteRecursively() as a better way of deleting directories.
  5727. @returns true if the file has been successfully deleted (or if it didn't exist to
  5728. begin with).
  5729. @see deleteRecursively
  5730. */
  5731. bool deleteFile() const throw();
  5732. /** Deletes a file or directory and all its subdirectories.
  5733. If this file is a directory, this will try to delete it and all its subfolders. If
  5734. it's just a file, it will just try to delete the file.
  5735. @returns true if the file and all its subfolders have been successfully deleted
  5736. (or if it didn't exist to begin with).
  5737. @see deleteFile
  5738. */
  5739. bool deleteRecursively() const throw();
  5740. /** Moves this file or folder to the trash.
  5741. @returns true if the operation succeeded. It could fail if the trash is full, or
  5742. if the file is write-protected, so you should check the return value
  5743. and act appropriately.
  5744. */
  5745. bool moveToTrash() const throw();
  5746. /** Moves or renames a file.
  5747. Tries to move a file to a different location.
  5748. If the target file already exists, this will attempt to delete it first, and
  5749. will fail if this can't be done.
  5750. Note that the destination file isn't the directory to put it in, it's the actual
  5751. filename that you want the new file to have.
  5752. @returns true if the operation succeeds
  5753. */
  5754. bool moveFileTo (const File& targetLocation) const throw();
  5755. /** Copies a file.
  5756. Tries to copy a file to a different location.
  5757. If the target file already exists, this will attempt to delete it first, and
  5758. will fail if this can't be done.
  5759. @returns true if the operation succeeds
  5760. */
  5761. bool copyFileTo (const File& targetLocation) const throw();
  5762. /** Copies a directory.
  5763. Tries to copy an entire directory, recursively.
  5764. If this file isn't a directory or if any target files can't be created, this
  5765. will return false.
  5766. @param newDirectory the directory that this one should be copied to. Note that this
  5767. is the name of the actual directory to create, not the directory
  5768. into which the new one should be placed, so there must be enough
  5769. write privileges to create it if it doesn't exist. Any files inside
  5770. it will be overwritten by similarly named ones that are copied.
  5771. */
  5772. bool copyDirectoryTo (const File& newDirectory) const throw();
  5773. /** Used in file searching, to specify whether to return files, directories, or both.
  5774. */
  5775. enum TypesOfFileToFind
  5776. {
  5777. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5778. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5779. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5780. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5781. };
  5782. /** Searches inside a directory for files matching a wildcard pattern.
  5783. Assuming that this file is a directory, this method will search it
  5784. for either files or subdirectories whose names match a filename pattern.
  5785. @param results an array to which File objects will be added for the
  5786. files that the search comes up with
  5787. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5788. return files, directories, or both. If the ignoreHiddenFiles flag
  5789. is also added to this value, hidden files won't be returned
  5790. @param searchRecursively if true, all subdirectories will be recursed into to do
  5791. an exhaustive search
  5792. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5793. @returns the number of results that have been found
  5794. @see getNumberOfChildFiles, DirectoryIterator
  5795. */
  5796. int findChildFiles (OwnedArray<File>& results,
  5797. const int whatToLookFor,
  5798. const bool searchRecursively,
  5799. const String& wildCardPattern = JUCE_T("*")) const throw();
  5800. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5801. Assuming that this file is a directory, this method will search it
  5802. for either files or subdirectories whose names match a filename pattern,
  5803. and will return the number of matches found.
  5804. This isn't a recursive call, and will only search this directory, not
  5805. its children.
  5806. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5807. count files, directories, or both. If the ignoreHiddenFiles flag
  5808. is also added to this value, hidden files won't be counted
  5809. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5810. @returns the number of matches found
  5811. @see findChildFiles, DirectoryIterator
  5812. */
  5813. int getNumberOfChildFiles (const int whatToLookFor,
  5814. const String& wildCardPattern = JUCE_T("*")) const throw();
  5815. /** Returns true if this file is a directory that contains one or more subdirectories.
  5816. @see isDirectory, findChildFiles
  5817. */
  5818. bool containsSubDirectories() const throw();
  5819. /** Creates a stream to read from this file.
  5820. @returns a stream that will read from this file (initially positioned at the
  5821. start of the file), or 0 if the file can't be opened for some reason
  5822. @see createOutputStream, loadFileAsData
  5823. */
  5824. FileInputStream* createInputStream() const throw();
  5825. /** Creates a stream to write to this file.
  5826. If the file exists, the stream that is returned will be positioned ready for
  5827. writing at the end of the file, so you might want to use deleteFile() first
  5828. to write to an empty file.
  5829. @returns a stream that will write to this file (initially positioned at the
  5830. end of the file), or 0 if the file can't be opened for some reason
  5831. @see createInputStream, printf, appendData, appendText
  5832. */
  5833. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5834. /** Loads a file's contents into memory as a block of binary data.
  5835. Of course, trying to load a very large file into memory will blow up, so
  5836. it's better to check first.
  5837. @param result the data block to which the file's contents should be appended - note
  5838. that if the memory block might already contain some data, you
  5839. might want to clear it first
  5840. @returns true if the file could all be read into memory
  5841. */
  5842. bool loadFileAsData (MemoryBlock& result) const throw();
  5843. /** Reads a file into memory as a string.
  5844. Attempts to load the entire file as a zero-terminated string.
  5845. This makes use of InputStream::readEntireStreamAsString, which should
  5846. automatically cope with unicode/acsii file formats.
  5847. */
  5848. const String loadFileAsString() const throw();
  5849. /** Writes text to the end of the file.
  5850. This will try to do a printf to the file.
  5851. @returns false if it can't write to the file for some reason
  5852. */
  5853. bool printf (const tchar* format, ...) const throw();
  5854. /** Appends a block of binary data to the end of the file.
  5855. This will try to write the given buffer to the end of the file.
  5856. @returns false if it can't write to the file for some reason
  5857. */
  5858. bool appendData (const void* const dataToAppend,
  5859. const int numberOfBytes) const throw();
  5860. /** Replaces this file's contents with a given block of data.
  5861. This will delete the file and replace it with the given data.
  5862. A nice feature of this method is that it's safe - instead of deleting
  5863. the file first and then re-writing it, it creates a new temporary file,
  5864. writes the data to that, and then moves the new file to replace the existing
  5865. file. This means that if the power gets pulled out or something crashes,
  5866. you're a lot less likely to end up with an empty file..
  5867. Returns true if the operation succeeds, or false if it fails.
  5868. @see appendText
  5869. */
  5870. bool replaceWithData (const void* const dataToWrite,
  5871. const int numberOfBytes) const throw();
  5872. /** Appends a string to the end of the file.
  5873. This will try to append a text string to the file, as either 16-bit unicode
  5874. or 8-bit characters in the default system encoding.
  5875. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5876. the endianness of the file.
  5877. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5878. @see replaceWithText
  5879. */
  5880. bool appendText (const String& textToAppend,
  5881. const bool asUnicode = false,
  5882. const bool writeUnicodeHeaderBytes = false) const throw();
  5883. /** Replaces this file's contents with a given text string.
  5884. This will delete the file and replace it with the given text.
  5885. A nice feature of this method is that it's safe - instead of deleting
  5886. the file first and then re-writing it, it creates a new temporary file,
  5887. writes the text to that, and then moves the new file to replace the existing
  5888. file. This means that if the power gets pulled out or something crashes,
  5889. you're a lot less likely to end up with an empty file..
  5890. For an explanation of the parameters here, see the appendText() method.
  5891. Returns true if the operation succeeds, or false if it fails.
  5892. @see appendText
  5893. */
  5894. bool replaceWithText (const String& textToWrite,
  5895. const bool asUnicode = false,
  5896. const bool writeUnicodeHeaderBytes = false) const throw();
  5897. /** Creates a set of files to represent each file root.
  5898. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5899. to which ones are available. On the Mac/Linux, this will probably
  5900. just add a single entry for "/".
  5901. */
  5902. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5903. /** Finds the name of the drive on which this file lives.
  5904. @returns the volume label of the drive, or an empty string if this isn't possible
  5905. */
  5906. const String getVolumeLabel() const throw();
  5907. /** Returns the serial number of the volume on which this file lives.
  5908. @returns the serial number, or zero if there's a problem doing this
  5909. */
  5910. int getVolumeSerialNumber() const throw();
  5911. /** Returns the number of bytes free on the drive that this file lives on.
  5912. @returns the number of bytes free, or 0 if there's a problem finding this out
  5913. */
  5914. int64 getBytesFreeOnVolume() const throw();
  5915. /** Returns true if this file is on a CD or DVD drive. */
  5916. bool isOnCDRomDrive() const throw();
  5917. /** Returns true if this file is on a hard disk.
  5918. This will fail if it's a network drive, but will still be true for
  5919. removable hard-disks.
  5920. */
  5921. bool isOnHardDisk() const throw();
  5922. /** Returns true if this file is on a removable disk drive.
  5923. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5924. */
  5925. bool isOnRemovableDrive() const throw();
  5926. /** Launches the file as a process.
  5927. - if the file is executable, this will run it.
  5928. - if it's a document of some kind, it will launch the document with its
  5929. default viewer application.
  5930. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5931. */
  5932. bool startAsProcess (const String& parameters = String::empty) const throw();
  5933. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5934. */
  5935. enum SpecialLocationType
  5936. {
  5937. /** The user's home folder. This is the same as using File ("~"). */
  5938. userHomeDirectory,
  5939. /** The user's default documents folder. On Windows, this might be the user's
  5940. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5941. doesn't tend to have one of these, so it might just return their home folder.
  5942. */
  5943. userDocumentsDirectory,
  5944. /** The folder that contains the user's desktop objects. */
  5945. userDesktopDirectory,
  5946. /** The folder in which applications store their persistent user-specific settings.
  5947. On Windows, this might be "\Documents and Settings\username\Application Data".
  5948. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5949. always create your own sub-folder to put them in, to avoid making a mess.
  5950. */
  5951. userApplicationDataDirectory,
  5952. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5953. of the computer, rather than just the current user.
  5954. On the Mac it'll be "/Library", on Windows, it could be something like
  5955. "\Documents and Settings\All Users\Application Data".
  5956. Depending on the setup, this folder may be read-only.
  5957. */
  5958. commonApplicationDataDirectory,
  5959. /** The folder that should be used for temporary files.
  5960. Always delete them when you're finished, to keep the user's computer tidy!
  5961. */
  5962. tempDirectory,
  5963. /** Returns this application's executable file.
  5964. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5965. host app.
  5966. On the mac this will return the unix binary, not the package folder - see
  5967. currentApplicationFile for that.
  5968. */
  5969. currentExecutableFile,
  5970. /** Returns this application's location.
  5971. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5972. host app.
  5973. On the mac this will return the package folder (if it's in one), not the unix binary
  5974. that's inside it - compare with currentExecutableFile.
  5975. */
  5976. currentApplicationFile,
  5977. /** The directory in which applications normally get installed.
  5978. So on windows, this would be something like "c:\program files", on the
  5979. Mac "/Applications", or "/usr" on linux.
  5980. */
  5981. globalApplicationsDirectory,
  5982. /** The most likely place where a user might store their music files.
  5983. */
  5984. userMusicDirectory,
  5985. /** The most likely place where a user might store their movie files.
  5986. */
  5987. userMoviesDirectory,
  5988. };
  5989. /** Finds the location of a special type of file or directory, such as a home folder or
  5990. documents folder.
  5991. @see SpecialLocationType
  5992. */
  5993. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5994. /** Returns a temporary file in the system's temp directory.
  5995. This will try to return the name of a non-existent temp file.
  5996. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5997. */
  5998. static const File createTempFile (const String& fileNameEnding) throw();
  5999. /** Returns the current working directory.
  6000. @see setAsCurrentWorkingDirectory
  6001. */
  6002. static const File getCurrentWorkingDirectory() throw();
  6003. /** Sets the current working directory to be this file.
  6004. For this to work the file must point to a valid directory.
  6005. @returns true if the current directory has been changed.
  6006. @see getCurrentWorkingDirectory
  6007. */
  6008. bool setAsCurrentWorkingDirectory() const throw();
  6009. /** The system-specific file separator character.
  6010. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6011. */
  6012. static const tchar separator;
  6013. /** The system-specific file separator character, as a string.
  6014. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6015. */
  6016. static const tchar* separatorString;
  6017. /** Removes illegal characters from a filename.
  6018. This will return a copy of the given string after removing characters
  6019. that are not allowed in a legal filename, and possibly shortening the
  6020. string if it's too long.
  6021. Because this will remove slashes, don't use it on an absolute pathname.
  6022. @see createLegalPathName
  6023. */
  6024. static const String createLegalFileName (const String& fileNameToFix) throw();
  6025. /** Removes illegal characters from a pathname.
  6026. Similar to createLegalFileName(), but this won't remove slashes, so can
  6027. be used on a complete pathname.
  6028. @see createLegalFileName
  6029. */
  6030. static const String createLegalPathName (const String& pathNameToFix) throw();
  6031. /** Indicates whether filenames are case-sensitive on the current operating system.
  6032. */
  6033. static bool areFileNamesCaseSensitive();
  6034. /** Returns true if the string seems to be a fully-specified absolute path.
  6035. */
  6036. static bool isAbsolutePath (const String& path) throw();
  6037. juce_UseDebuggingNewOperator
  6038. private:
  6039. String fullPath;
  6040. // internal way of contructing a file without checking the path
  6041. friend class DirectoryIterator;
  6042. File (const String&, int) throw();
  6043. const String getPathUpToLastSlash() const throw();
  6044. };
  6045. #endif // __JUCE_FILE_JUCEHEADER__
  6046. /********* End of inlined file: juce_File.h *********/
  6047. /**
  6048. A simple implemenation of a Logger that writes to a file.
  6049. @see Logger
  6050. */
  6051. class JUCE_API FileLogger : public Logger
  6052. {
  6053. public:
  6054. /** Creates a FileLogger for a given file.
  6055. @param fileToWriteTo the file that to use - new messages will be appended
  6056. to the file. If the file doesn't exist, it will be created,
  6057. along with any parent directories that are needed.
  6058. @param welcomeMessage when opened, the logger will write a header to the log, along
  6059. with the current date and time, and this welcome message
  6060. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  6061. but is larger than this number of bytes, then the start of the
  6062. file will be truncated to keep the size down. This prevents a log
  6063. file getting ridiculously large over time. The file will be truncated
  6064. at a new-line boundary. If this value is less than zero, no size limit
  6065. will be imposed; if it's zero, the file will always be deleted. Note that
  6066. the size is only checked once when this object is created - any logging
  6067. that is done later will be appended without any checking
  6068. */
  6069. FileLogger (const File& fileToWriteTo,
  6070. const String& welcomeMessage,
  6071. const int maxInitialFileSizeBytes = 128 * 1024);
  6072. /** Destructor. */
  6073. ~FileLogger();
  6074. void logMessage (const String& message);
  6075. /** Helper function to create a log file in the correct place for this platform.
  6076. On Windows this will return a logger with a path such as:
  6077. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  6078. On the Mac it'll create something like:
  6079. ~/Library/Logs/[logFileName]
  6080. The method might return 0 if the file can't be created for some reason.
  6081. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  6082. it's best to use the something like the name of your application here.
  6083. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  6084. call it "log.txt" because if it goes in a directory with logs
  6085. from other applications (as it will do on the Mac) then no-one
  6086. will know which one is yours!
  6087. @param welcomeMessage a message that will be written to the log when it's opened.
  6088. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  6089. */
  6090. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  6091. const String& logFileName,
  6092. const String& welcomeMessage,
  6093. const int maxInitialFileSizeBytes = 128 * 1024);
  6094. juce_UseDebuggingNewOperator
  6095. private:
  6096. File logFile;
  6097. CriticalSection logLock;
  6098. FileOutputStream* logStream;
  6099. void trimFileSize (int maxFileSizeBytes) const;
  6100. FileLogger (const FileLogger&);
  6101. const FileLogger& operator= (const FileLogger&);
  6102. };
  6103. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  6104. /********* End of inlined file: juce_FileLogger.h *********/
  6105. #endif
  6106. #ifndef __JUCE_LOGGER_JUCEHEADER__
  6107. #endif
  6108. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6109. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  6110. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6111. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6112. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  6113. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6114. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6115. /**
  6116. Adds reference-counting to an object.
  6117. To add reference-counting to a class, derive it from this class, and
  6118. use the ReferenceCountedObjectPtr class to point to it.
  6119. e.g. @code
  6120. class MyClass : public ReferenceCountedObject
  6121. {
  6122. void foo();
  6123. // This is a neat way of declaring a typedef for a pointer class,
  6124. // rather than typing out the full templated name each time..
  6125. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  6126. };
  6127. MyClass::Ptr p = new MyClass();
  6128. MyClass::Ptr p2 = p;
  6129. p = 0;
  6130. p2->foo();
  6131. @endcode
  6132. Once a new ReferenceCountedObject has been assigned to a pointer, be
  6133. careful not to delete the object manually.
  6134. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  6135. */
  6136. class JUCE_API ReferenceCountedObject
  6137. {
  6138. public:
  6139. /** Increments the object's reference count.
  6140. This is done automatically by the smart pointer, but is public just
  6141. in case it's needed for nefarious purposes.
  6142. */
  6143. inline void incReferenceCount() throw()
  6144. {
  6145. atomicIncrement (refCounts);
  6146. jassert (refCounts > 0);
  6147. }
  6148. /** Decreases the object's reference count.
  6149. If the count gets to zero, the object will be deleted.
  6150. */
  6151. inline void decReferenceCount() throw()
  6152. {
  6153. jassert (refCounts > 0);
  6154. if (atomicDecrementAndReturn (refCounts) == 0)
  6155. delete this;
  6156. }
  6157. /** Returns the object's current reference count. */
  6158. inline int getReferenceCount() const throw()
  6159. {
  6160. return refCounts;
  6161. }
  6162. protected:
  6163. /** Creates the reference-counted object (with an initial ref count of zero). */
  6164. ReferenceCountedObject()
  6165. : refCounts (0)
  6166. {
  6167. }
  6168. /** Destructor. */
  6169. virtual ~ReferenceCountedObject()
  6170. {
  6171. // it's dangerous to delete an object that's still referenced by something else!
  6172. jassert (refCounts == 0);
  6173. }
  6174. private:
  6175. int refCounts;
  6176. };
  6177. /**
  6178. Used to point to an object of type ReferenceCountedObject.
  6179. It's wise to use a typedef instead of typing out the templated name
  6180. each time - e.g.
  6181. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  6182. @see ReferenceCountedObject, ReferenceCountedObjectArray
  6183. */
  6184. template <class ReferenceCountedObjectClass>
  6185. class ReferenceCountedObjectPtr
  6186. {
  6187. public:
  6188. /** Creates a pointer to a null object. */
  6189. inline ReferenceCountedObjectPtr() throw()
  6190. : referencedObject (0)
  6191. {
  6192. }
  6193. /** Creates a pointer to an object.
  6194. This will increment the object's reference-count if it is non-null.
  6195. */
  6196. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  6197. : referencedObject (refCountedObject)
  6198. {
  6199. if (refCountedObject != 0)
  6200. refCountedObject->incReferenceCount();
  6201. }
  6202. /** Copies another pointer.
  6203. This will increment the object's reference-count (if it is non-null).
  6204. */
  6205. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  6206. : referencedObject (other.referencedObject)
  6207. {
  6208. if (referencedObject != 0)
  6209. referencedObject->incReferenceCount();
  6210. }
  6211. /** Changes this pointer to point at a different object.
  6212. The reference count of the old object is decremented, and it might be
  6213. deleted if it hits zero. The new object's count is incremented.
  6214. */
  6215. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  6216. {
  6217. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  6218. if (newObject != referencedObject)
  6219. {
  6220. if (newObject != 0)
  6221. newObject->incReferenceCount();
  6222. ReferenceCountedObjectClass* const oldObject = referencedObject;
  6223. referencedObject = newObject;
  6224. if (oldObject != 0)
  6225. oldObject->decReferenceCount();
  6226. }
  6227. return *this;
  6228. }
  6229. /** Changes this pointer to point at a different object.
  6230. The reference count of the old object is decremented, and it might be
  6231. deleted if it hits zero. The new object's count is incremented.
  6232. */
  6233. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  6234. {
  6235. if (referencedObject != newObject)
  6236. {
  6237. if (newObject != 0)
  6238. newObject->incReferenceCount();
  6239. ReferenceCountedObjectClass* const oldObject = referencedObject;
  6240. referencedObject = newObject;
  6241. if (oldObject != 0)
  6242. oldObject->decReferenceCount();
  6243. }
  6244. return *this;
  6245. }
  6246. /** Destructor.
  6247. This will decrement the object's reference-count, and may delete it if it
  6248. gets to zero.
  6249. */
  6250. inline ~ReferenceCountedObjectPtr()
  6251. {
  6252. if (referencedObject != 0)
  6253. referencedObject->decReferenceCount();
  6254. }
  6255. /** Returns the object that this pointer references.
  6256. The pointer returned may be zero, of course.
  6257. */
  6258. inline operator ReferenceCountedObjectClass*() const throw()
  6259. {
  6260. return referencedObject;
  6261. }
  6262. /** Returns true if this pointer refers to the given object. */
  6263. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  6264. {
  6265. return referencedObject == object;
  6266. }
  6267. /** Returns true if this pointer doesn't refer to the given object. */
  6268. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  6269. {
  6270. return referencedObject != object;
  6271. }
  6272. // the -> operator is called on the referenced object
  6273. inline ReferenceCountedObjectClass* operator->() const throw()
  6274. {
  6275. return referencedObject;
  6276. }
  6277. private:
  6278. ReferenceCountedObjectClass* referencedObject;
  6279. };
  6280. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6281. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  6282. /**
  6283. Holds a list of objects derived from ReferenceCountedObject.
  6284. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  6285. and takes care of incrementing and decrementing their ref counts when they
  6286. are added and removed from the array.
  6287. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  6288. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  6289. @see Array, OwnedArray, StringArray
  6290. */
  6291. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  6292. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  6293. {
  6294. public:
  6295. /** Creates an empty array.
  6296. @param granularity this is the size of increment by which the internal storage
  6297. used by the array will grow. Only change it from the default if you know the
  6298. array is going to be very big and needs to be able to grow efficiently.
  6299. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  6300. */
  6301. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  6302. : ArrayAllocationBase <ObjectClass*> (granularity),
  6303. numUsed (0)
  6304. {
  6305. }
  6306. /** Creates a copy of another array */
  6307. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  6308. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  6309. numUsed (other.numUsed)
  6310. {
  6311. other.lockArray();
  6312. this->setAllocatedSize (numUsed);
  6313. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  6314. for (int i = numUsed; --i >= 0;)
  6315. if (this->elements[i] != 0)
  6316. this->elements[i]->incReferenceCount();
  6317. other.unlockArray();
  6318. }
  6319. /** Copies another array into this one.
  6320. Any existing objects in this array will first be released.
  6321. */
  6322. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  6323. {
  6324. if (this != &other)
  6325. {
  6326. other.lockArray();
  6327. lock.enter();
  6328. clear();
  6329. this->granularity = other.granularity;
  6330. this->ensureAllocatedSize (other.numUsed);
  6331. numUsed = other.numUsed;
  6332. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  6333. minimiseStorageOverheads();
  6334. for (int i = numUsed; --i >= 0;)
  6335. if (this->elements[i] != 0)
  6336. this->elements[i]->incReferenceCount();
  6337. lock.exit();
  6338. other.unlockArray();
  6339. }
  6340. return *this;
  6341. }
  6342. /** Destructor.
  6343. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  6344. */
  6345. ~ReferenceCountedArray()
  6346. {
  6347. clear();
  6348. }
  6349. /** Removes all objects from the array.
  6350. Any objects in the array that are not referenced from elsewhere will be deleted.
  6351. */
  6352. void clear()
  6353. {
  6354. lock.enter();
  6355. while (numUsed > 0)
  6356. if (this->elements [--numUsed] != 0)
  6357. this->elements [numUsed]->decReferenceCount();
  6358. jassert (numUsed == 0);
  6359. this->setAllocatedSize (0);
  6360. lock.exit();
  6361. }
  6362. /** Returns the current number of objects in the array. */
  6363. inline int size() const throw()
  6364. {
  6365. return numUsed;
  6366. }
  6367. /** Returns a pointer to the object at this index in the array.
  6368. If the index is out-of-range, this will return a null pointer, (and
  6369. it could be null anyway, because it's ok for the array to hold null
  6370. pointers as well as objects).
  6371. @see getUnchecked
  6372. */
  6373. inline ObjectClass* operator[] (const int index) const throw()
  6374. {
  6375. lock.enter();
  6376. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  6377. ? this->elements [index]
  6378. : (ObjectClass*) 0;
  6379. lock.exit();
  6380. return result;
  6381. }
  6382. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  6383. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  6384. it can be used when you're sure the index if always going to be legal.
  6385. */
  6386. inline ObjectClass* getUnchecked (const int index) const throw()
  6387. {
  6388. lock.enter();
  6389. jassert (((unsigned int) index) < (unsigned int) numUsed);
  6390. ObjectClass* const result = this->elements [index];
  6391. lock.exit();
  6392. return result;
  6393. }
  6394. /** Returns a pointer to the first object in the array.
  6395. This will return a null pointer if the array's empty.
  6396. @see getLast
  6397. */
  6398. inline ObjectClass* getFirst() const throw()
  6399. {
  6400. lock.enter();
  6401. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  6402. : (ObjectClass*) 0;
  6403. lock.exit();
  6404. return result;
  6405. }
  6406. /** Returns a pointer to the last object in the array.
  6407. This will return a null pointer if the array's empty.
  6408. @see getFirst
  6409. */
  6410. inline ObjectClass* getLast() const throw()
  6411. {
  6412. lock.enter();
  6413. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  6414. : (ObjectClass*) 0;
  6415. lock.exit();
  6416. return result;
  6417. }
  6418. /** Finds the index of the first occurrence of an object in the array.
  6419. @param objectToLookFor the object to look for
  6420. @returns the index at which the object was found, or -1 if it's not found
  6421. */
  6422. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  6423. {
  6424. int result = -1;
  6425. lock.enter();
  6426. ObjectClass** e = this->elements;
  6427. for (int i = numUsed; --i >= 0;)
  6428. {
  6429. if (objectToLookFor == *e)
  6430. {
  6431. result = (int) (e - this->elements);
  6432. break;
  6433. }
  6434. ++e;
  6435. }
  6436. lock.exit();
  6437. return result;
  6438. }
  6439. /** Returns true if the array contains a specified object.
  6440. @param objectToLookFor the object to look for
  6441. @returns true if the object is in the array
  6442. */
  6443. bool contains (const ObjectClass* const objectToLookFor) const throw()
  6444. {
  6445. lock.enter();
  6446. ObjectClass** e = this->elements;
  6447. for (int i = numUsed; --i >= 0;)
  6448. {
  6449. if (objectToLookFor == *e)
  6450. {
  6451. lock.exit();
  6452. return true;
  6453. }
  6454. ++e;
  6455. }
  6456. lock.exit();
  6457. return false;
  6458. }
  6459. /** Appends a new object to the end of the array.
  6460. This will increase the new object's reference count.
  6461. @param newObject the new object to add to the array
  6462. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  6463. */
  6464. void add (ObjectClass* const newObject) throw()
  6465. {
  6466. lock.enter();
  6467. this->ensureAllocatedSize (numUsed + 1);
  6468. this->elements [numUsed++] = newObject;
  6469. if (newObject != 0)
  6470. newObject->incReferenceCount();
  6471. lock.exit();
  6472. }
  6473. /** Inserts a new object into the array at the given index.
  6474. If the index is less than 0 or greater than the size of the array, the
  6475. element will be added to the end of the array.
  6476. Otherwise, it will be inserted into the array, moving all the later elements
  6477. along to make room.
  6478. This will increase the new object's reference count.
  6479. @param indexToInsertAt the index at which the new element should be inserted
  6480. @param newObject the new object to add to the array
  6481. @see add, addSorted, addIfNotAlreadyThere, set
  6482. */
  6483. void insert (int indexToInsertAt,
  6484. ObjectClass* const newObject) throw()
  6485. {
  6486. if (indexToInsertAt >= 0)
  6487. {
  6488. lock.enter();
  6489. if (indexToInsertAt > numUsed)
  6490. indexToInsertAt = numUsed;
  6491. this->ensureAllocatedSize (numUsed + 1);
  6492. ObjectClass** const e = this->elements + indexToInsertAt;
  6493. const int numToMove = numUsed - indexToInsertAt;
  6494. if (numToMove > 0)
  6495. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  6496. *e = newObject;
  6497. if (newObject != 0)
  6498. newObject->incReferenceCount();
  6499. ++numUsed;
  6500. lock.exit();
  6501. }
  6502. else
  6503. {
  6504. add (newObject);
  6505. }
  6506. }
  6507. /** Appends a new object at the end of the array as long as the array doesn't
  6508. already contain it.
  6509. If the array already contains a matching object, nothing will be done.
  6510. @param newObject the new object to add to the array
  6511. */
  6512. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  6513. {
  6514. lock.enter();
  6515. if (! contains (newObject))
  6516. add (newObject);
  6517. lock.exit();
  6518. }
  6519. /** Replaces an object in the array with a different one.
  6520. If the index is less than zero, this method does nothing.
  6521. If the index is beyond the end of the array, the new object is added to the end of the array.
  6522. The object being added has its reference count increased, and if it's replacing
  6523. another object, then that one has its reference count decreased, and may be deleted.
  6524. @param indexToChange the index whose value you want to change
  6525. @param newObject the new value to set for this index.
  6526. @see add, insert, remove
  6527. */
  6528. void set (const int indexToChange,
  6529. ObjectClass* const newObject)
  6530. {
  6531. if (indexToChange >= 0)
  6532. {
  6533. lock.enter();
  6534. if (newObject != 0)
  6535. newObject->incReferenceCount();
  6536. if (indexToChange < numUsed)
  6537. {
  6538. if (this->elements [indexToChange] != 0)
  6539. this->elements [indexToChange]->decReferenceCount();
  6540. this->elements [indexToChange] = newObject;
  6541. }
  6542. else
  6543. {
  6544. this->ensureAllocatedSize (numUsed + 1);
  6545. this->elements [numUsed++] = newObject;
  6546. }
  6547. lock.exit();
  6548. }
  6549. }
  6550. /** Adds elements from another array to the end of this array.
  6551. @param arrayToAddFrom the array from which to copy the elements
  6552. @param startIndex the first element of the other array to start copying from
  6553. @param numElementsToAdd how many elements to add from the other array. If this
  6554. value is negative or greater than the number of available elements,
  6555. all available elements will be copied.
  6556. @see add
  6557. */
  6558. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  6559. int startIndex = 0,
  6560. int numElementsToAdd = -1) throw()
  6561. {
  6562. arrayToAddFrom.lockArray();
  6563. lock.enter();
  6564. if (startIndex < 0)
  6565. {
  6566. jassertfalse
  6567. startIndex = 0;
  6568. }
  6569. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  6570. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  6571. if (numElementsToAdd > 0)
  6572. {
  6573. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  6574. while (--numElementsToAdd >= 0)
  6575. add (arrayToAddFrom.getUnchecked (startIndex++));
  6576. }
  6577. lock.exit();
  6578. arrayToAddFrom.unlockArray();
  6579. }
  6580. /** Inserts a new object into the array assuming that the array is sorted.
  6581. This will use a comparator to find the position at which the new object
  6582. should go. If the array isn't sorted, the behaviour of this
  6583. method will be unpredictable.
  6584. @param comparator the comparator object to use to compare the elements - see the
  6585. sort() method for details about this object's form
  6586. @param newObject the new object to insert to the array
  6587. @see add, sort
  6588. */
  6589. template <class ElementComparator>
  6590. void addSorted (ElementComparator& comparator,
  6591. ObjectClass* newObject) throw()
  6592. {
  6593. lock.enter();
  6594. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  6595. lock.exit();
  6596. }
  6597. /** Removes an object from the array.
  6598. This will remove the object at a given index and move back all the
  6599. subsequent objects to close the gap.
  6600. If the index passed in is out-of-range, nothing will happen.
  6601. The object that is removed will have its reference count decreased,
  6602. and may be deleted if not referenced from elsewhere.
  6603. @param indexToRemove the index of the element to remove
  6604. @see removeObject, removeRange
  6605. */
  6606. void remove (const int indexToRemove)
  6607. {
  6608. lock.enter();
  6609. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  6610. {
  6611. ObjectClass** const e = this->elements + indexToRemove;
  6612. if (*e != 0)
  6613. (*e)->decReferenceCount();
  6614. --numUsed;
  6615. const int numberToShift = numUsed - indexToRemove;
  6616. if (numberToShift > 0)
  6617. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  6618. if ((numUsed << 1) < this->numAllocated)
  6619. minimiseStorageOverheads();
  6620. }
  6621. lock.exit();
  6622. }
  6623. /** Removes the first occurrence of a specified object from the array.
  6624. If the item isn't found, no action is taken. If it is found, it is
  6625. removed and has its reference count decreased.
  6626. @param objectToRemove the object to try to remove
  6627. @see remove, removeRange
  6628. */
  6629. void removeObject (ObjectClass* const objectToRemove)
  6630. {
  6631. lock.enter();
  6632. remove (indexOf (objectToRemove));
  6633. lock.exit();
  6634. }
  6635. /** Removes a range of objects from the array.
  6636. This will remove a set of objects, starting from the given index,
  6637. and move any subsequent elements down to close the gap.
  6638. If the range extends beyond the bounds of the array, it will
  6639. be safely clipped to the size of the array.
  6640. The objects that are removed will have their reference counts decreased,
  6641. and may be deleted if not referenced from elsewhere.
  6642. @param startIndex the index of the first object to remove
  6643. @param numberToRemove how many objects should be removed
  6644. @see remove, removeObject
  6645. */
  6646. void removeRange (const int startIndex,
  6647. const int numberToRemove)
  6648. {
  6649. lock.enter();
  6650. const int start = jlimit (0, numUsed, startIndex);
  6651. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  6652. if (end > start)
  6653. {
  6654. int i;
  6655. for (i = start; i < end; ++i)
  6656. {
  6657. if (this->elements[i] != 0)
  6658. {
  6659. this->elements[i]->decReferenceCount();
  6660. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  6661. }
  6662. }
  6663. const int rangeSize = end - start;
  6664. ObjectClass** e = this->elements + start;
  6665. i = numUsed - end;
  6666. numUsed -= rangeSize;
  6667. while (--i >= 0)
  6668. {
  6669. *e = e [rangeSize];
  6670. ++e;
  6671. }
  6672. if ((numUsed << 1) < this->numAllocated)
  6673. minimiseStorageOverheads();
  6674. }
  6675. lock.exit();
  6676. }
  6677. /** Removes the last n objects from the array.
  6678. The objects that are removed will have their reference counts decreased,
  6679. and may be deleted if not referenced from elsewhere.
  6680. @param howManyToRemove how many objects to remove from the end of the array
  6681. @see remove, removeObject, removeRange
  6682. */
  6683. void removeLast (int howManyToRemove = 1)
  6684. {
  6685. lock.enter();
  6686. if (howManyToRemove > numUsed)
  6687. howManyToRemove = numUsed;
  6688. while (--howManyToRemove >= 0)
  6689. remove (numUsed - 1);
  6690. lock.exit();
  6691. }
  6692. /** Swaps a pair of objects in the array.
  6693. If either of the indexes passed in is out-of-range, nothing will happen,
  6694. otherwise the two objects at these positions will be exchanged.
  6695. */
  6696. void swap (const int index1,
  6697. const int index2) throw()
  6698. {
  6699. lock.enter();
  6700. if (((unsigned int) index1) < (unsigned int) numUsed
  6701. && ((unsigned int) index2) < (unsigned int) numUsed)
  6702. {
  6703. swapVariables (this->elements [index1],
  6704. this->elements [index2]);
  6705. }
  6706. lock.exit();
  6707. }
  6708. /** Moves one of the objects to a different position.
  6709. This will move the object to a specified index, shuffling along
  6710. any intervening elements as required.
  6711. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6712. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6713. @param currentIndex the index of the object to be moved. If this isn't a
  6714. valid index, then nothing will be done
  6715. @param newIndex the index at which you'd like this object to end up. If this
  6716. is less than zero, it will be moved to the end of the array
  6717. */
  6718. void move (const int currentIndex,
  6719. int newIndex) throw()
  6720. {
  6721. if (currentIndex != newIndex)
  6722. {
  6723. lock.enter();
  6724. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  6725. {
  6726. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  6727. newIndex = numUsed - 1;
  6728. ObjectClass* const value = this->elements [currentIndex];
  6729. if (newIndex > currentIndex)
  6730. {
  6731. memmove (this->elements + currentIndex,
  6732. this->elements + currentIndex + 1,
  6733. (newIndex - currentIndex) * sizeof (ObjectClass*));
  6734. }
  6735. else
  6736. {
  6737. memmove (this->elements + newIndex + 1,
  6738. this->elements + newIndex,
  6739. (currentIndex - newIndex) * sizeof (ObjectClass*));
  6740. }
  6741. this->elements [newIndex] = value;
  6742. }
  6743. lock.exit();
  6744. }
  6745. }
  6746. /** Compares this array to another one.
  6747. @returns true only if the other array contains the same objects in the same order
  6748. */
  6749. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  6750. {
  6751. other.lockArray();
  6752. lock.enter();
  6753. bool result = numUsed == other.numUsed;
  6754. if (result)
  6755. {
  6756. for (int i = numUsed; --i >= 0;)
  6757. {
  6758. if (this->elements [i] != other.elements [i])
  6759. {
  6760. result = false;
  6761. break;
  6762. }
  6763. }
  6764. }
  6765. lock.exit();
  6766. other.unlockArray();
  6767. return result;
  6768. }
  6769. /** Compares this array to another one.
  6770. @see operator==
  6771. */
  6772. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  6773. {
  6774. return ! operator== (other);
  6775. }
  6776. /** Sorts the elements in the array.
  6777. This will use a comparator object to sort the elements into order. The object
  6778. passed must have a method of the form:
  6779. @code
  6780. int compareElements (ElementType first, ElementType second);
  6781. @endcode
  6782. ..and this method must return:
  6783. - a value of < 0 if the first comes before the second
  6784. - a value of 0 if the two objects are equivalent
  6785. - a value of > 0 if the second comes before the first
  6786. To improve performance, the compareElements() method can be declared as static or const.
  6787. @param comparator the comparator to use for comparing elements.
  6788. @param retainOrderOfEquivalentItems if this is true, then items
  6789. which the comparator says are equivalent will be
  6790. kept in the order in which they currently appear
  6791. in the array. This is slower to perform, but may
  6792. be important in some cases. If it's false, a faster
  6793. algorithm is used, but equivalent elements may be
  6794. rearranged.
  6795. @see sortArray
  6796. */
  6797. template <class ElementComparator>
  6798. void sort (ElementComparator& comparator,
  6799. const bool retainOrderOfEquivalentItems = false) const throw()
  6800. {
  6801. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6802. // avoids getting warning messages about the parameter being unused
  6803. lock.enter();
  6804. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  6805. lock.exit();
  6806. }
  6807. /** Reduces the amount of storage being used by the array.
  6808. Arrays typically allocate slightly more storage than they need, and after
  6809. removing elements, they may have quite a lot of unused space allocated.
  6810. This method will reduce the amount of allocated storage to a minimum.
  6811. */
  6812. void minimiseStorageOverheads() throw()
  6813. {
  6814. lock.enter();
  6815. if (numUsed == 0)
  6816. {
  6817. this->setAllocatedSize (0);
  6818. }
  6819. else
  6820. {
  6821. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  6822. if (newAllocation < this->numAllocated)
  6823. this->setAllocatedSize (newAllocation);
  6824. }
  6825. lock.exit();
  6826. }
  6827. /** Locks the array's CriticalSection.
  6828. Of course if the type of section used is a DummyCriticalSection, this won't
  6829. have any effect.
  6830. @see unlockArray
  6831. */
  6832. void lockArray() const throw()
  6833. {
  6834. lock.enter();
  6835. }
  6836. /** Unlocks the array's CriticalSection.
  6837. Of course if the type of section used is a DummyCriticalSection, this won't
  6838. have any effect.
  6839. @see lockArray
  6840. */
  6841. void unlockArray() const throw()
  6842. {
  6843. lock.exit();
  6844. }
  6845. juce_UseDebuggingNewOperator
  6846. private:
  6847. int numUsed;
  6848. TypeOfCriticalSectionToUse lock;
  6849. };
  6850. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6851. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  6852. #endif
  6853. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6854. #endif
  6855. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  6856. /********* Start of inlined file: juce_SparseSet.h *********/
  6857. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  6858. #define __JUCE_SPARSESET_JUCEHEADER__
  6859. /**
  6860. Holds a set of primitive values, storing them as a set of ranges.
  6861. This container acts like a simple BitArray, but can efficiently hold large
  6862. continguous ranges of values. It's quite a specialised class, mostly useful
  6863. for things like keeping the set of selected rows in a listbox.
  6864. The type used as a template paramter must be an integer type, such as int, short,
  6865. int64, etc.
  6866. */
  6867. template <class Type>
  6868. class SparseSet
  6869. {
  6870. public:
  6871. /** Creates a new empty set. */
  6872. SparseSet() throw()
  6873. {
  6874. }
  6875. /** Creates a copy of another SparseSet. */
  6876. SparseSet (const SparseSet<Type>& other) throw()
  6877. : values (other.values)
  6878. {
  6879. }
  6880. /** Destructor. */
  6881. ~SparseSet() throw()
  6882. {
  6883. }
  6884. /** Clears the set. */
  6885. void clear() throw()
  6886. {
  6887. values.clear();
  6888. }
  6889. /** Checks whether the set is empty.
  6890. This is much quicker than using (size() == 0).
  6891. */
  6892. bool isEmpty() const throw()
  6893. {
  6894. return values.size() == 0;
  6895. }
  6896. /** Returns the number of values in the set.
  6897. Because of the way the data is stored, this method can take longer if there
  6898. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  6899. are any items.
  6900. */
  6901. Type size() const throw()
  6902. {
  6903. Type num = 0;
  6904. for (int i = 0; i < values.size(); i += 2)
  6905. num += values[i + 1] - values[i];
  6906. return num;
  6907. }
  6908. /** Returns one of the values in the set.
  6909. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  6910. @returns the value at this index, or 0 if it's out-of-range
  6911. */
  6912. Type operator[] (int index) const throw()
  6913. {
  6914. for (int i = 0; i < values.size(); i += 2)
  6915. {
  6916. const Type s = values.getUnchecked(i);
  6917. const Type e = values.getUnchecked(i + 1);
  6918. if (index < e - s)
  6919. return s + index;
  6920. index -= e - s;
  6921. }
  6922. return (Type) 0;
  6923. }
  6924. /** Checks whether a particular value is in the set. */
  6925. bool contains (const Type valueToLookFor) const throw()
  6926. {
  6927. bool on = false;
  6928. for (int i = 0; i < values.size(); ++i)
  6929. {
  6930. if (values.getUnchecked(i) > valueToLookFor)
  6931. return on;
  6932. on = ! on;
  6933. }
  6934. return false;
  6935. }
  6936. /** Returns the number of contiguous blocks of values.
  6937. @see getRange
  6938. */
  6939. int getNumRanges() const throw()
  6940. {
  6941. return values.size() >> 1;
  6942. }
  6943. /** Returns one of the contiguous ranges of values stored.
  6944. @param rangeIndex the index of the range to look up, between 0
  6945. and (getNumRanges() - 1)
  6946. @param startValue on return, the value at the start of the range
  6947. @param numValues on return, the number of values in the range
  6948. @see getTotalRange
  6949. */
  6950. bool getRange (const int rangeIndex,
  6951. Type& startValue,
  6952. Type& numValues) const throw()
  6953. {
  6954. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  6955. {
  6956. startValue = values [rangeIndex << 1];
  6957. numValues = values [(rangeIndex << 1) + 1] - startValue;
  6958. return true;
  6959. }
  6960. return false;
  6961. }
  6962. /** Returns the lowest and highest values in the set.
  6963. @see getRange
  6964. */
  6965. bool getTotalRange (Type& lowestValue,
  6966. Type& highestValue) const throw()
  6967. {
  6968. if (values.size() > 0)
  6969. {
  6970. lowestValue = values.getUnchecked (0);
  6971. highestValue = values.getUnchecked (values.size() - 1);
  6972. return true;
  6973. }
  6974. return false;
  6975. }
  6976. /** Adds a range of contiguous values to the set.
  6977. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  6978. @param firstValue the start of the range of values to add
  6979. @param numValuesToAdd how many values to add
  6980. */
  6981. void addRange (const Type firstValue,
  6982. const Type numValuesToAdd) throw()
  6983. {
  6984. jassert (numValuesToAdd >= 0);
  6985. if (numValuesToAdd > 0)
  6986. {
  6987. removeRange (firstValue, numValuesToAdd);
  6988. IntegerElementComparator<Type> sorter;
  6989. values.addSorted (sorter, firstValue);
  6990. values.addSorted (sorter, firstValue + numValuesToAdd);
  6991. simplify();
  6992. }
  6993. }
  6994. /** Removes a range of values from the set.
  6995. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  6996. @param firstValue the start of the range of values to remove
  6997. @param numValuesToRemove how many values to remove
  6998. */
  6999. void removeRange (const Type firstValue,
  7000. const Type numValuesToRemove) throw()
  7001. {
  7002. jassert (numValuesToRemove >= 0);
  7003. if (numValuesToRemove >= 0
  7004. && firstValue < values.getLast())
  7005. {
  7006. const bool onAtStart = contains (firstValue - 1);
  7007. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  7008. const bool onAtEnd = contains (lastValue);
  7009. for (int i = values.size(); --i >= 0;)
  7010. {
  7011. if (values.getUnchecked(i) <= lastValue)
  7012. {
  7013. while (values.getUnchecked(i) >= firstValue)
  7014. {
  7015. values.remove (i);
  7016. if (--i < 0)
  7017. break;
  7018. }
  7019. break;
  7020. }
  7021. }
  7022. IntegerElementComparator<Type> sorter;
  7023. if (onAtStart)
  7024. values.addSorted (sorter, firstValue);
  7025. if (onAtEnd)
  7026. values.addSorted (sorter, lastValue);
  7027. simplify();
  7028. }
  7029. }
  7030. /** Does an XOR of the values in a given range. */
  7031. void invertRange (const Type firstValue,
  7032. const Type numValues)
  7033. {
  7034. SparseSet newItems;
  7035. newItems.addRange (firstValue, numValues);
  7036. int i;
  7037. for (i = getNumRanges(); --i >= 0;)
  7038. {
  7039. const int start = values [i << 1];
  7040. const int end = values [(i << 1) + 1];
  7041. newItems.removeRange (start, end);
  7042. }
  7043. removeRange (firstValue, numValues);
  7044. for (i = newItems.getNumRanges(); --i >= 0;)
  7045. {
  7046. const int start = newItems.values [i << 1];
  7047. const int end = newItems.values [(i << 1) + 1];
  7048. addRange (start, end);
  7049. }
  7050. }
  7051. /** Checks whether any part of a given range overlaps any part of this one. */
  7052. bool overlapsRange (const Type firstValue,
  7053. const Type numValues) throw()
  7054. {
  7055. jassert (numValues >= 0);
  7056. if (numValues > 0)
  7057. {
  7058. for (int i = getNumRanges(); --i >= 0;)
  7059. {
  7060. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  7061. return false;
  7062. if (firstValue + numValues > values.getUnchecked (i << 1))
  7063. return true;
  7064. }
  7065. }
  7066. return false;
  7067. }
  7068. /** Checks whether the whole of a given range is contained within this one. */
  7069. bool containsRange (const Type firstValue,
  7070. const Type numValues) throw()
  7071. {
  7072. jassert (numValues >= 0);
  7073. if (numValues > 0)
  7074. {
  7075. for (int i = getNumRanges(); --i >= 0;)
  7076. {
  7077. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  7078. return false;
  7079. if (firstValue >= values.getUnchecked (i << 1)
  7080. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  7081. return true;
  7082. }
  7083. }
  7084. return false;
  7085. }
  7086. bool operator== (const SparseSet<Type>& other) throw()
  7087. {
  7088. return values == other.values;
  7089. }
  7090. bool operator!= (const SparseSet<Type>& other) throw()
  7091. {
  7092. return values != other.values;
  7093. }
  7094. juce_UseDebuggingNewOperator
  7095. private:
  7096. // alternating start/end values of ranges of values that are present.
  7097. Array<Type> values;
  7098. void simplify() throw()
  7099. {
  7100. jassert ((values.size() & 1) == 0);
  7101. for (int i = values.size(); --i > 0;)
  7102. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  7103. values.removeRange (i - 1, 2);
  7104. }
  7105. };
  7106. #endif // __JUCE_SPARSESET_JUCEHEADER__
  7107. /********* End of inlined file: juce_SparseSet.h *********/
  7108. #endif
  7109. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  7110. #endif
  7111. #ifndef __JUCE_ARRAY_JUCEHEADER__
  7112. #endif
  7113. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  7114. #endif
  7115. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  7116. #endif
  7117. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7118. #endif
  7119. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  7120. #endif
  7121. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7122. #endif
  7123. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  7124. /********* Start of inlined file: juce_PropertySet.h *********/
  7125. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  7126. #define __JUCE_PROPERTYSET_JUCEHEADER__
  7127. /********* Start of inlined file: juce_StringPairArray.h *********/
  7128. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7129. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7130. /**
  7131. A container for holding a set of strings which are keyed by another string.
  7132. @see StringArray
  7133. */
  7134. class JUCE_API StringPairArray
  7135. {
  7136. public:
  7137. /** Creates an empty array */
  7138. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  7139. /** Creates a copy of another array */
  7140. StringPairArray (const StringPairArray& other) throw();
  7141. /** Destructor. */
  7142. ~StringPairArray() throw();
  7143. /** Copies the contents of another string array into this one */
  7144. const StringPairArray& operator= (const StringPairArray& other) throw();
  7145. /** Compares two arrays.
  7146. Comparisons are case-sensitive.
  7147. @returns true only if the other array contains exactly the same strings with the same keys
  7148. */
  7149. bool operator== (const StringPairArray& other) const throw();
  7150. /** Compares two arrays.
  7151. Comparisons are case-sensitive.
  7152. @returns false if the other array contains exactly the same strings with the same keys
  7153. */
  7154. bool operator!= (const StringPairArray& other) const throw();
  7155. /** Finds the value corresponding to a key string.
  7156. If no such key is found, this will just return an empty string. To check whether
  7157. a given key actually exists (because it might actually be paired with an empty string), use
  7158. the getAllKeys() method to obtain a list.
  7159. Obviously the reference returned shouldn't be stored for later use, as the
  7160. string it refers to may disappear when the array changes.
  7161. @see getValue
  7162. */
  7163. const String& operator[] (const String& key) const throw();
  7164. /** Finds the value corresponding to a key string.
  7165. If no such key is found, this will just return the value provided as a default.
  7166. @see operator[]
  7167. */
  7168. const String getValue (const String& key, const String& defaultReturnValue) const;
  7169. /** Returns a list of all keys in the array. */
  7170. const StringArray& getAllKeys() const throw() { return keys; }
  7171. /** Returns a list of all values in the array. */
  7172. const StringArray& getAllValues() const throw() { return values; }
  7173. /** Returns the number of strings in the array */
  7174. inline int size() const throw() { return keys.size(); };
  7175. /** Adds or amends a key/value pair.
  7176. If a value already exists with this key, its value will be overwritten,
  7177. otherwise the key/value pair will be added to the array.
  7178. */
  7179. void set (const String& key,
  7180. const String& value) throw();
  7181. /** Adds the items from another array to this one.
  7182. This is equivalent to using set() to add each of the pairs from the other array.
  7183. */
  7184. void addArray (const StringPairArray& other);
  7185. /** Removes all elements from the array. */
  7186. void clear() throw();
  7187. /** Removes a string from the array based on its key.
  7188. If the key isn't found, nothing will happen.
  7189. */
  7190. void remove (const String& key) throw();
  7191. /** Removes a string from the array based on its index.
  7192. If the index is out-of-range, no action will be taken.
  7193. */
  7194. void remove (const int index) throw();
  7195. /** Indicates whether to use a case-insensitive search when looking up a key string.
  7196. */
  7197. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  7198. /** Returns a descriptive string containing the items.
  7199. This is handy for dumping the contents of an array.
  7200. */
  7201. const String getDescription() const;
  7202. /** Reduces the amount of storage being used by the array.
  7203. Arrays typically allocate slightly more storage than they need, and after
  7204. removing elements, they may have quite a lot of unused space allocated.
  7205. This method will reduce the amount of allocated storage to a minimum.
  7206. */
  7207. void minimiseStorageOverheads() throw();
  7208. juce_UseDebuggingNewOperator
  7209. private:
  7210. StringArray keys, values;
  7211. bool ignoreCase;
  7212. };
  7213. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7214. /********* End of inlined file: juce_StringPairArray.h *********/
  7215. /********* Start of inlined file: juce_XmlElement.h *********/
  7216. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  7217. #define __JUCE_XMLELEMENT_JUCEHEADER__
  7218. /********* Start of inlined file: juce_OutputStream.h *********/
  7219. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  7220. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  7221. /********* Start of inlined file: juce_InputStream.h *********/
  7222. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  7223. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  7224. /** The base class for streams that read data.
  7225. Input and output streams are used throughout the library - subclasses can override
  7226. some or all of the virtual functions to implement their behaviour.
  7227. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  7228. */
  7229. class JUCE_API InputStream
  7230. {
  7231. public:
  7232. /** Destructor. */
  7233. virtual ~InputStream() {}
  7234. /** Returns the total number of bytes available for reading in this stream.
  7235. Note that this is the number of bytes available from the start of the
  7236. stream, not from the current position.
  7237. If the size of the stream isn't actually known, this may return -1.
  7238. */
  7239. virtual int64 getTotalLength() = 0;
  7240. /** Returns true if the stream has no more data to read. */
  7241. virtual bool isExhausted() = 0;
  7242. /** Reads a set of bytes from the stream into a memory buffer.
  7243. This is the only read method that subclasses actually need to implement, as the
  7244. InputStream base class implements the other read methods in terms of this one (although
  7245. it's often more efficient for subclasses to implement them directly).
  7246. @param destBuffer the destination buffer for the data
  7247. @param maxBytesToRead the maximum number of bytes to read - make sure the
  7248. memory block passed in is big enough to contain this
  7249. many bytes.
  7250. @returns the actual number of bytes that were read, which may be less than
  7251. maxBytesToRead if the stream is exhausted before it gets that far
  7252. */
  7253. virtual int read (void* destBuffer,
  7254. int maxBytesToRead) = 0;
  7255. /** Reads a byte from the stream.
  7256. If the stream is exhausted, this will return zero.
  7257. @see OutputStream::writeByte
  7258. */
  7259. virtual char readByte();
  7260. /** Reads a boolean from the stream.
  7261. The bool is encoded as a single byte - 1 for true, 0 for false.
  7262. If the stream is exhausted, this will return false.
  7263. @see OutputStream::writeBool
  7264. */
  7265. virtual bool readBool();
  7266. /** Reads two bytes from the stream as a little-endian 16-bit value.
  7267. If the next two bytes read are byte1 and byte2, this returns
  7268. (byte1 | (byte2 << 8)).
  7269. If the stream is exhausted partway through reading the bytes, this will return zero.
  7270. @see OutputStream::writeShort, readShortBigEndian
  7271. */
  7272. virtual short readShort();
  7273. /** Reads two bytes from the stream as a little-endian 16-bit value.
  7274. If the next two bytes read are byte1 and byte2, this returns
  7275. (byte2 | (byte1 << 8)).
  7276. If the stream is exhausted partway through reading the bytes, this will return zero.
  7277. @see OutputStream::writeShortBigEndian, readShort
  7278. */
  7279. virtual short readShortBigEndian();
  7280. /** Reads four bytes from the stream as a little-endian 32-bit value.
  7281. If the next four bytes are byte1 to byte4, this returns
  7282. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  7283. If the stream is exhausted partway through reading the bytes, this will return zero.
  7284. @see OutputStream::writeInt, readIntBigEndian
  7285. */
  7286. virtual int readInt();
  7287. /** Reads four bytes from the stream as a big-endian 32-bit value.
  7288. If the next four bytes are byte1 to byte4, this returns
  7289. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  7290. If the stream is exhausted partway through reading the bytes, this will return zero.
  7291. @see OutputStream::writeIntBigEndian, readInt
  7292. */
  7293. virtual int readIntBigEndian();
  7294. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  7295. If the next eight bytes are byte1 to byte8, this returns
  7296. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  7297. If the stream is exhausted partway through reading the bytes, this will return zero.
  7298. @see OutputStream::writeInt64, readInt64BigEndian
  7299. */
  7300. virtual int64 readInt64();
  7301. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  7302. If the next eight bytes are byte1 to byte8, this returns
  7303. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  7304. If the stream is exhausted partway through reading the bytes, this will return zero.
  7305. @see OutputStream::writeInt64BigEndian, readInt64
  7306. */
  7307. virtual int64 readInt64BigEndian();
  7308. /** Reads four bytes as a 32-bit floating point value.
  7309. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  7310. If the stream is exhausted partway through reading the bytes, this will return zero.
  7311. @see OutputStream::writeFloat, readDouble
  7312. */
  7313. virtual float readFloat();
  7314. /** Reads four bytes as a 32-bit floating point value.
  7315. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  7316. If the stream is exhausted partway through reading the bytes, this will return zero.
  7317. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  7318. */
  7319. virtual float readFloatBigEndian();
  7320. /** Reads eight bytes as a 64-bit floating point value.
  7321. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  7322. If the stream is exhausted partway through reading the bytes, this will return zero.
  7323. @see OutputStream::writeDouble, readFloat
  7324. */
  7325. virtual double readDouble();
  7326. /** Reads eight bytes as a 64-bit floating point value.
  7327. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  7328. If the stream is exhausted partway through reading the bytes, this will return zero.
  7329. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  7330. */
  7331. virtual double readDoubleBigEndian();
  7332. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  7333. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  7334. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  7335. @see OutputStream::writeCompressedInt()
  7336. */
  7337. virtual int readCompressedInt();
  7338. /** Reads a string from the stream, up to the next linefeed or carriage return.
  7339. The stream is treated as 8-bit characters encoded with the system's default encoding,
  7340. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  7341. After this call, the stream's position will be left pointing to the character
  7342. following the line-feed, but the linefeeds aren't included in the string that
  7343. is returned.
  7344. */
  7345. virtual const String readNextLine();
  7346. /** Reads a zero-terminated string from the stream.
  7347. This will read characters from the stream until it hits a zero character or
  7348. end-of-stream.
  7349. @see OutputStream::writeString, readEntireStreamAsString
  7350. */
  7351. virtual const String readString();
  7352. /** Tries to read the whole stream and turn it into a string.
  7353. This will read from the stream's current position until the end-of-stream, and
  7354. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  7355. */
  7356. virtual const String readEntireStreamAsString();
  7357. /** Reads from the stream and appends the data to a MemoryBlock.
  7358. @param destBlock the block to append the data onto
  7359. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  7360. of bytes that will be read - if it's negative, data
  7361. will be read until the stream is exhausted.
  7362. @returns the number of bytes that were added to the memory block
  7363. */
  7364. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  7365. int maxNumBytesToRead = -1);
  7366. /** Returns the offset of the next byte that will be read from the stream.
  7367. @see setPosition
  7368. */
  7369. virtual int64 getPosition() = 0;
  7370. /** Tries to move the current read position of the stream.
  7371. The position is an absolute number of bytes from the stream's start.
  7372. Some streams might not be able to do this, in which case they should do
  7373. nothing and return false. Others might be able to manage it by resetting
  7374. themselves and skipping to the correct position, although this is
  7375. obviously a bit slow.
  7376. @returns true if the stream manages to reposition itself correctly
  7377. @see getPosition
  7378. */
  7379. virtual bool setPosition (int64 newPosition) = 0;
  7380. /** Reads and discards a number of bytes from the stream.
  7381. Some input streams might implement this efficiently, but the base
  7382. class will just keep reading data until the requisite number of bytes
  7383. have been done.
  7384. */
  7385. virtual void skipNextBytes (int64 numBytesToSkip);
  7386. juce_UseDebuggingNewOperator
  7387. protected:
  7388. InputStream() throw() {}
  7389. };
  7390. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  7391. /********* End of inlined file: juce_InputStream.h *********/
  7392. /**
  7393. The base class for streams that write data to some kind of destination.
  7394. Input and output streams are used throughout the library - subclasses can override
  7395. some or all of the virtual functions to implement their behaviour.
  7396. @see InputStream, MemoryOutputStream, FileOutputStream
  7397. */
  7398. class JUCE_API OutputStream
  7399. {
  7400. public:
  7401. /** Destructor.
  7402. Some subclasses might want to do things like call flush() during their
  7403. destructors.
  7404. */
  7405. virtual ~OutputStream();
  7406. /** If the stream is using a buffer, this will ensure it gets written
  7407. out to the destination. */
  7408. virtual void flush() = 0;
  7409. /** Tries to move the stream's output position.
  7410. Not all streams will be able to seek to a new position - this will return
  7411. false if it fails to work.
  7412. @see getPosition
  7413. */
  7414. virtual bool setPosition (int64 newPosition) = 0;
  7415. /** Returns the stream's current position.
  7416. @see setPosition
  7417. */
  7418. virtual int64 getPosition() = 0;
  7419. /** Writes a block of data to the stream.
  7420. When creating a subclass of OutputStream, this is the only write method
  7421. that needs to be overloaded - the base class has methods for writing other
  7422. types of data which use this to do the work.
  7423. @returns false if the write operation fails for some reason
  7424. */
  7425. virtual bool write (const void* dataToWrite,
  7426. int howManyBytes) = 0;
  7427. /** Writes a single byte to the stream.
  7428. @see InputStream::readByte
  7429. */
  7430. virtual void writeByte (char byte);
  7431. /** Writes a boolean to the stream.
  7432. This is encoded as a byte - either 1 or 0.
  7433. @see InputStream::readBool
  7434. */
  7435. virtual void writeBool (bool boolValue);
  7436. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  7437. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  7438. @see InputStream::readShort
  7439. */
  7440. virtual void writeShort (short value);
  7441. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  7442. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  7443. @see InputStream::readShortBigEndian
  7444. */
  7445. virtual void writeShortBigEndian (short value);
  7446. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  7447. @see InputStream::readInt
  7448. */
  7449. virtual void writeInt (int value);
  7450. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  7451. @see InputStream::readIntBigEndian
  7452. */
  7453. virtual void writeIntBigEndian (int value);
  7454. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  7455. @see InputStream::readInt64
  7456. */
  7457. virtual void writeInt64 (int64 value);
  7458. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  7459. @see InputStream::readInt64BigEndian
  7460. */
  7461. virtual void writeInt64BigEndian (int64 value);
  7462. /** Writes a 32-bit floating point value to the stream.
  7463. The binary 32-bit encoding of the float is written as a little-endian int.
  7464. @see InputStream::readFloat
  7465. */
  7466. virtual void writeFloat (float value);
  7467. /** Writes a 32-bit floating point value to the stream.
  7468. The binary 32-bit encoding of the float is written as a big-endian int.
  7469. @see InputStream::readFloatBigEndian
  7470. */
  7471. virtual void writeFloatBigEndian (float value);
  7472. /** Writes a 64-bit floating point value to the stream.
  7473. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  7474. @see InputStream::readDouble
  7475. */
  7476. virtual void writeDouble (double value);
  7477. /** Writes a 64-bit floating point value to the stream.
  7478. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  7479. @see InputStream::readDoubleBigEndian
  7480. */
  7481. virtual void writeDoubleBigEndian (double value);
  7482. /** Writes a condensed encoding of a 32-bit integer.
  7483. If you're storing a lot of integers which are unlikely to have very large values,
  7484. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  7485. under 0xffff only 3 bytes, etc.
  7486. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  7487. @see InputStream::readCompressedInt
  7488. */
  7489. virtual void writeCompressedInt (int value);
  7490. /** Stores a string in the stream.
  7491. This isn't the method to use if you're trying to append text to the end of a
  7492. text-file! It's intended for storing a string for later retrieval
  7493. by InputStream::readString.
  7494. For appending text to a file, instead use writeText, printf, or operator<<
  7495. @see InputStream::readString, writeText, printf, operator<<
  7496. */
  7497. virtual void writeString (const String& text);
  7498. /** Writes a string of text to the stream.
  7499. It can either write it as 8-bit system-encoded characters, or as unicode, and
  7500. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  7501. should only be done at the start of a file).
  7502. The method also replaces '\\n' characters in the text with '\\r\\n'.
  7503. */
  7504. virtual void writeText (const String& text,
  7505. const bool asUnicode,
  7506. const bool writeUnicodeHeaderBytes);
  7507. /** Writes a string of text to the stream.
  7508. @see writeText
  7509. */
  7510. virtual void printf (const char* format, ...);
  7511. /** Reads data from an input stream and writes it to this stream.
  7512. @param source the stream to read from
  7513. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  7514. less than zero, it will keep reading until the input
  7515. is exhausted)
  7516. */
  7517. virtual int writeFromInputStream (InputStream& source,
  7518. int maxNumBytesToWrite);
  7519. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  7520. virtual OutputStream& operator<< (const int number);
  7521. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  7522. virtual OutputStream& operator<< (const double number);
  7523. /** Writes a character to the stream. */
  7524. virtual OutputStream& operator<< (const char character);
  7525. /** Writes a null-terminated string to the stream. */
  7526. virtual OutputStream& operator<< (const char* const text);
  7527. /** Writes a null-terminated unicode text string to the stream, converting it
  7528. to 8-bit characters in the default system encoding. */
  7529. virtual OutputStream& operator<< (const juce_wchar* const text);
  7530. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  7531. virtual OutputStream& operator<< (const String& text);
  7532. juce_UseDebuggingNewOperator
  7533. protected:
  7534. OutputStream() throw();
  7535. };
  7536. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  7537. /********* End of inlined file: juce_OutputStream.h *********/
  7538. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  7539. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7540. will be the name of a pointer to each child element.
  7541. E.g. @code
  7542. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7543. forEachXmlChildElement (*myParentXml, child)
  7544. {
  7545. if (child->hasTagName ("FOO"))
  7546. doSomethingWithXmlElement (child);
  7547. }
  7548. @endcode
  7549. @see forEachXmlChildElementWithTagName
  7550. */
  7551. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  7552. \
  7553. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  7554. childElementVariableName != 0; \
  7555. childElementVariableName = childElementVariableName->getNextElement())
  7556. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  7557. which have a specified tag.
  7558. This does the same job as the forEachXmlChildElement macro, but only for those
  7559. elements that have a particular tag name.
  7560. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7561. will be the name of a pointer to each child element. The requiredTagName is the
  7562. tag name to match.
  7563. E.g. @code
  7564. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7565. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  7566. {
  7567. // the child object is now guaranteed to be a <MYTAG> element..
  7568. doSomethingWithMYTAGElement (child);
  7569. }
  7570. @endcode
  7571. @see forEachXmlChildElement
  7572. */
  7573. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7574. \
  7575. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7576. childElementVariableName != 0; \
  7577. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7578. /** Used to build a tree of elements representing an XML document.
  7579. An XML document can be parsed into a tree of XmlElements, each of which
  7580. represents an XML tag structure, and which may itself contain other
  7581. nested elements.
  7582. An XmlElement can also be converted back into a text document, and has
  7583. lots of useful methods for manipulating its attributes and sub-elements,
  7584. so XmlElements can actually be used as a handy general-purpose data
  7585. structure.
  7586. Here's an example of parsing some elements: @code
  7587. // check we're looking at the right kind of document..
  7588. if (myElement->hasTagName ("ANIMALS"))
  7589. {
  7590. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7591. forEachXmlChildElement (*myElement, e)
  7592. {
  7593. if (e->hasTagName ("GIRAFFE"))
  7594. {
  7595. // found a giraffe, so use some of its attributes..
  7596. String giraffeName = e->getStringAttribute ("name");
  7597. int giraffeAge = e->getIntAttribute ("age");
  7598. bool isFriendly = e->getBoolAttribute ("friendly");
  7599. }
  7600. }
  7601. }
  7602. @endcode
  7603. And here's an example of how to create an XML document from scratch: @code
  7604. // create an outer node called "ANIMALS"
  7605. XmlElement animalsList ("ANIMALS");
  7606. for (int i = 0; i < numAnimals; ++i)
  7607. {
  7608. // create an inner element..
  7609. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7610. giraffe->setAttribute ("name", "nigel");
  7611. giraffe->setAttribute ("age", 10);
  7612. giraffe->setAttribute ("friendly", true);
  7613. // ..and add our new element to the parent node
  7614. animalsList.addChildElement (giraffe);
  7615. }
  7616. // now we can turn the whole thing into a text document..
  7617. String myXmlDoc = animalsList.createDocument (String::empty);
  7618. @endcode
  7619. @see XmlDocument
  7620. */
  7621. class JUCE_API XmlElement
  7622. {
  7623. public:
  7624. /** Creates an XmlElement with this tag name. */
  7625. XmlElement (const String& tagName) throw();
  7626. /** Creates a (deep) copy of another element. */
  7627. XmlElement (const XmlElement& other) throw();
  7628. /** Creates a (deep) copy of another element. */
  7629. const XmlElement& operator= (const XmlElement& other) throw();
  7630. /** Deleting an XmlElement will also delete all its child elements. */
  7631. ~XmlElement() throw();
  7632. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7633. The elements are only considered equivalent if they contain the same attiributes
  7634. with the same values, and have the same sub-nodes.
  7635. @param other the other element to compare to
  7636. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7637. same attributes in a different order will be
  7638. considered the same; if false, the attributes must
  7639. be in the same order as well
  7640. */
  7641. bool isEquivalentTo (const XmlElement* const other,
  7642. const bool ignoreOrderOfAttributes) const throw();
  7643. /** Returns an XML text document that represents this element.
  7644. The string returned can be parsed to recreate the same XmlElement that
  7645. was used to create it.
  7646. @param dtdToUse the DTD to add to the document
  7647. @param allOnOneLine if true, this means that the document will not contain any
  7648. linefeeds, so it'll be smaller but not very easy to read.
  7649. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7650. document
  7651. @param encodingType the character encoding format string to put into the xml
  7652. header
  7653. @param lineWrapLength the line length that will be used before items get placed on
  7654. a new line. This isn't an absolute maximum length, it just
  7655. determines how lists of attributes get broken up
  7656. @see writeToFile
  7657. */
  7658. const String createDocument (const String& dtdToUse,
  7659. const bool allOnOneLine = false,
  7660. const bool includeXmlHeader = true,
  7661. const tchar* const encodingType = JUCE_T("UTF-8"),
  7662. const int lineWrapLength = 60) const throw();
  7663. /** Writes the element to a file as an XML document.
  7664. To improve safety in case something goes wrong while writing the file, this
  7665. will actually write the document to a new temporary file in the same
  7666. directory as the destination file, and if this succeeds, it will rename this
  7667. new file as the destination file (overwriting any existing file that was there).
  7668. @param destinationFile the file to write to. If this already exists, it will be
  7669. overwritten.
  7670. @param dtdToUse the DTD to add to the document
  7671. @param encodingType the character encoding format string to put into the xml
  7672. header
  7673. @param lineWrapLength the line length that will be used before items get placed on
  7674. a new line. This isn't an absolute maximum length, it just
  7675. determines how lists of attributes get broken up
  7676. @returns true if the file is written successfully; false if something goes wrong
  7677. in the process
  7678. @see createDocument
  7679. */
  7680. bool writeToFile (const File& destinationFile,
  7681. const String& dtdToUse,
  7682. const tchar* const encodingType = JUCE_T("UTF-8"),
  7683. const int lineWrapLength = 60) const throw();
  7684. /** Returns this element's tag type name.
  7685. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7686. "MOOSE".
  7687. @see hasTagName
  7688. */
  7689. inline const String& getTagName() const throw() { return tagName; }
  7690. /** Tests whether this element has a particular tag name.
  7691. @param possibleTagName the tag name you're comparing it with
  7692. @see getTagName
  7693. */
  7694. bool hasTagName (const tchar* const possibleTagName) const throw();
  7695. /** Returns the number of XML attributes this element contains.
  7696. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7697. return 2.
  7698. */
  7699. int getNumAttributes() const throw();
  7700. /** Returns the name of one of the elements attributes.
  7701. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7702. getAttributeName(1) would return "antlers".
  7703. @see getAttributeValue, getStringAttribute
  7704. */
  7705. const String& getAttributeName (const int attributeIndex) const throw();
  7706. /** Returns the value of one of the elements attributes.
  7707. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7708. getAttributeName(1) would return "2".
  7709. @see getAttributeName, getStringAttribute
  7710. */
  7711. const String& getAttributeValue (const int attributeIndex) const throw();
  7712. // Attribute-handling methods..
  7713. /** Checks whether the element contains an attribute with a certain name. */
  7714. bool hasAttribute (const tchar* const attributeName) const throw();
  7715. /** Returns the value of a named attribute.
  7716. @param attributeName the name of the attribute to look up
  7717. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7718. with this name
  7719. */
  7720. const String getStringAttribute (const tchar* const attributeName,
  7721. const tchar* const defaultReturnValue = 0) const throw();
  7722. /** Compares the value of a named attribute with a value passed-in.
  7723. @param attributeName the name of the attribute to look up
  7724. @param stringToCompareAgainst the value to compare it with
  7725. @param ignoreCase whether the comparison should be case-insensitive
  7726. @returns true if the value of the attribute is the same as the string passed-in;
  7727. false if it's different (or if no such attribute exists)
  7728. */
  7729. bool compareAttribute (const tchar* const attributeName,
  7730. const tchar* const stringToCompareAgainst,
  7731. const bool ignoreCase = false) const throw();
  7732. /** Returns the value of a named attribute as an integer.
  7733. This will try to find the attribute and convert it to an integer (using
  7734. the String::getIntValue() method).
  7735. @param attributeName the name of the attribute to look up
  7736. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7737. with this name
  7738. @see setAttribute (const tchar* const, int)
  7739. */
  7740. int getIntAttribute (const tchar* const attributeName,
  7741. const int defaultReturnValue = 0) const throw();
  7742. /** Returns the value of a named attribute as floating-point.
  7743. This will try to find the attribute and convert it to an integer (using
  7744. the String::getDoubleValue() method).
  7745. @param attributeName the name of the attribute to look up
  7746. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7747. with this name
  7748. @see setAttribute (const tchar* const, double)
  7749. */
  7750. double getDoubleAttribute (const tchar* const attributeName,
  7751. const double defaultReturnValue = 0.0) const throw();
  7752. /** Returns the value of a named attribute as a boolean.
  7753. This will try to find the attribute and interpret it as a boolean. To do this,
  7754. it'll return true if the value is "1", "true", "y", etc, or false for other
  7755. values.
  7756. @param attributeName the name of the attribute to look up
  7757. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7758. with this name
  7759. */
  7760. bool getBoolAttribute (const tchar* const attributeName,
  7761. const bool defaultReturnValue = false) const throw();
  7762. /** Adds a named attribute to the element.
  7763. If the element already contains an attribute with this name, it's value will
  7764. be updated to the new value. If there's no such attribute yet, a new one will
  7765. be added.
  7766. Note that there are other setAttribute() methods that take integers,
  7767. doubles, etc. to make it easy to store numbers.
  7768. @param attributeName the name of the attribute to set
  7769. @param newValue the value to set it to
  7770. @see removeAttribute
  7771. */
  7772. void setAttribute (const tchar* const attributeName,
  7773. const String& newValue) throw();
  7774. /** Adds a named attribute to the element.
  7775. If the element already contains an attribute with this name, it's value will
  7776. be updated to the new value. If there's no such attribute yet, a new one will
  7777. be added.
  7778. Note that there are other setAttribute() methods that take integers,
  7779. doubles, etc. to make it easy to store numbers.
  7780. @param attributeName the name of the attribute to set
  7781. @param newValue the value to set it to
  7782. */
  7783. void setAttribute (const tchar* const attributeName,
  7784. const tchar* const newValue) throw();
  7785. /** Adds a named attribute to the element, setting it to an integer value.
  7786. If the element already contains an attribute with this name, it's value will
  7787. be updated to the new value. If there's no such attribute yet, a new one will
  7788. be added.
  7789. Note that there are other setAttribute() methods that take integers,
  7790. doubles, etc. to make it easy to store numbers.
  7791. @param attributeName the name of the attribute to set
  7792. @param newValue the value to set it to
  7793. */
  7794. void setAttribute (const tchar* const attributeName,
  7795. const int newValue) throw();
  7796. /** Adds a named attribute to the element, setting it to a floating-point value.
  7797. If the element already contains an attribute with this name, it's value will
  7798. be updated to the new value. If there's no such attribute yet, a new one will
  7799. be added.
  7800. Note that there are other setAttribute() methods that take integers,
  7801. doubles, etc. to make it easy to store numbers.
  7802. @param attributeName the name of the attribute to set
  7803. @param newValue the value to set it to
  7804. */
  7805. void setAttribute (const tchar* const attributeName,
  7806. const double newValue) throw();
  7807. /** Removes a named attribute from the element.
  7808. @param attributeName the name of the attribute to remove
  7809. @see removeAllAttributes
  7810. */
  7811. void removeAttribute (const tchar* const attributeName) throw();
  7812. /** Removes all attributes from this element.
  7813. */
  7814. void removeAllAttributes() throw();
  7815. // Child element methods..
  7816. /** Returns the first of this element's sub-elements.
  7817. see getNextElement() for an example of how to iterate the sub-elements.
  7818. @see forEachXmlChildElement
  7819. */
  7820. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7821. /** Returns the next of this element's siblings.
  7822. This can be used for iterating an element's sub-elements, e.g.
  7823. @code
  7824. XmlElement* child = myXmlDocument->getFirstChildElement();
  7825. while (child != 0)
  7826. {
  7827. ...do stuff with this child..
  7828. child = child->getNextElement();
  7829. }
  7830. @endcode
  7831. Note that when iterating the child elements, some of them might be
  7832. text elements as well as XML tags - use isTextElement() to work this
  7833. out.
  7834. Also, it's much easier and neater to use this method indirectly via the
  7835. forEachXmlChildElement macro.
  7836. @returns the sibling element that follows this one, or zero if this is the last
  7837. element in its parent
  7838. @see getNextElement, isTextElement, forEachXmlChildElement
  7839. */
  7840. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7841. /** Returns the next of this element's siblings which has the specified tag
  7842. name.
  7843. This is like getNextElement(), but will scan through the list until it
  7844. finds an element with the given tag name.
  7845. @see getNextElement, forEachXmlChildElementWithTagName
  7846. */
  7847. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  7848. /** Returns the number of sub-elements in this element.
  7849. @see getChildElement
  7850. */
  7851. int getNumChildElements() const throw();
  7852. /** Returns the sub-element at a certain index.
  7853. It's not very efficient to iterate the sub-elements by index - see
  7854. getNextElement() for an example of how best to iterate.
  7855. @returns the n'th child of this element, or 0 if the index is out-of-range
  7856. @see getNextElement, isTextElement, getChildByName
  7857. */
  7858. XmlElement* getChildElement (const int index) const throw();
  7859. /** Returns the first sub-element with a given tag-name.
  7860. @param tagNameToLookFor the tag name of the element you want to find
  7861. @returns the first element with this tag name, or 0 if none is found
  7862. @see getNextElement, isTextElement, getChildElement
  7863. */
  7864. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  7865. /** Appends an element to this element's list of children.
  7866. Child elements are deleted automatically when their parent is deleted, so
  7867. make sure the object that you pass in will not be deleted by anything else,
  7868. and make sure it's not already the child of another element.
  7869. @see getFirstChildElement, getNextElement, getNumChildElements,
  7870. getChildElement, removeChildElement
  7871. */
  7872. void addChildElement (XmlElement* const newChildElement) throw();
  7873. /** Inserts an element into this element's list of children.
  7874. Child elements are deleted automatically when their parent is deleted, so
  7875. make sure the object that you pass in will not be deleted by anything else,
  7876. and make sure it's not already the child of another element.
  7877. @param newChildNode the element to add
  7878. @param indexToInsertAt the index at which to insert the new element - if this is
  7879. below zero, it will be added to the end of the list
  7880. @see addChildElement, insertChildElement
  7881. */
  7882. void insertChildElement (XmlElement* const newChildNode,
  7883. int indexToInsertAt) throw();
  7884. /** Replaces one of this element's children with another node.
  7885. If the current element passed-in isn't actually a child of this element,
  7886. this will return false and the new one won't be added. Otherwise, the
  7887. existing element will be deleted, replaced with the new one, and it
  7888. will return true.
  7889. */
  7890. bool replaceChildElement (XmlElement* const currentChildElement,
  7891. XmlElement* const newChildNode) throw();
  7892. /** Removes a child element.
  7893. @param childToRemove the child to look for and remove
  7894. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7895. just remove it
  7896. */
  7897. void removeChildElement (XmlElement* const childToRemove,
  7898. const bool shouldDeleteTheChild) throw();
  7899. /** Deletes all the child elements in the element.
  7900. @see removeChildElement, deleteAllChildElementsWithTagName
  7901. */
  7902. void deleteAllChildElements() throw();
  7903. /** Deletes all the child elements with a given tag name.
  7904. @see removeChildElement
  7905. */
  7906. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  7907. /** Returns true if the given element is a child of this one. */
  7908. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7909. /** Recursively searches all sub-elements to find one that contains the specified
  7910. child element.
  7911. */
  7912. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  7913. /** Sorts the child elements using a comparator.
  7914. This will use a comparator object to sort the elements into order. The object
  7915. passed must have a method of the form:
  7916. @code
  7917. int compareElements (const XmlElement* first, const XmlElement* second);
  7918. @endcode
  7919. ..and this method must return:
  7920. - a value of < 0 if the first comes before the second
  7921. - a value of 0 if the two objects are equivalent
  7922. - a value of > 0 if the second comes before the first
  7923. To improve performance, the compareElements() method can be declared as static or const.
  7924. @param comparator the comparator to use for comparing elements.
  7925. @param retainOrderOfEquivalentItems if this is true, then items
  7926. which the comparator says are equivalent will be
  7927. kept in the order in which they currently appear
  7928. in the array. This is slower to perform, but may
  7929. be important in some cases. If it's false, a faster
  7930. algorithm is used, but equivalent elements may be
  7931. rearranged.
  7932. */
  7933. template <class ElementComparator>
  7934. void sortChildElements (ElementComparator& comparator,
  7935. const bool retainOrderOfEquivalentItems = false) throw()
  7936. {
  7937. const int num = getNumChildElements();
  7938. if (num > 1)
  7939. {
  7940. XmlElement** const elems = getChildElementsAsArray (num);
  7941. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  7942. reorderChildElements (elems, num);
  7943. delete[] elems;
  7944. }
  7945. }
  7946. /** Returns true if this element is a section of text.
  7947. Elements can either be an XML tag element or a secton of text, so this
  7948. is used to find out what kind of element this one is.
  7949. @see getAllText, addTextElement, deleteAllTextElements
  7950. */
  7951. bool isTextElement() const throw();
  7952. /** Returns the text for a text element.
  7953. Note that if you have an element like this:
  7954. @code<xyz>hello</xyz>@endcode
  7955. then calling getText on the "xyz" element won't return "hello", because that is
  7956. actually stored in a special text sub-element inside the xyz element. To get the
  7957. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7958. use getAllSubText() to do this automatically.
  7959. @see isTextElement, getAllSubText, getChildElementAllSubText
  7960. */
  7961. const String getText() const throw();
  7962. /** Sets the text in a text element.
  7963. Note that this is only a valid call if this element is a text element. If it's
  7964. not, then no action will be performed.
  7965. */
  7966. void setText (const String& newText) throw();
  7967. /** Returns all the text from this element's child nodes.
  7968. This iterates all the child elements and when it finds text elements,
  7969. it concatenates their text into a big string which it returns.
  7970. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7971. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7972. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7973. */
  7974. const String getAllSubText() const throw();
  7975. /** Returns all the sub-text of a named child element.
  7976. If there is a child element with the given tag name, this will return
  7977. all of its sub-text (by calling getAllSubText() on it). If there is
  7978. no such child element, this will return the default string passed-in.
  7979. @see getAllSubText
  7980. */
  7981. const String getChildElementAllSubText (const tchar* const childTagName,
  7982. const String& defaultReturnValue) const throw();
  7983. /** Appends a section of text to this element.
  7984. @see isTextElement, getText, getAllSubText
  7985. */
  7986. void addTextElement (const String& text) throw();
  7987. /** Removes all the text elements from this element.
  7988. @see isTextElement, getText, getAllSubText, addTextElement
  7989. */
  7990. void deleteAllTextElements() throw();
  7991. /** Creates a text element that can be added to a parent element.
  7992. */
  7993. static XmlElement* createTextElement (const String& text) throw();
  7994. juce_UseDebuggingNewOperator
  7995. private:
  7996. friend class XmlDocument;
  7997. String tagName;
  7998. XmlElement* firstChildElement;
  7999. XmlElement* nextElement;
  8000. struct XmlAttributeNode
  8001. {
  8002. XmlAttributeNode (const XmlAttributeNode& other) throw();
  8003. XmlAttributeNode (const String& name, const String& value) throw();
  8004. String name, value;
  8005. XmlAttributeNode* next;
  8006. };
  8007. XmlAttributeNode* attributes;
  8008. XmlElement (int) throw(); // for internal use
  8009. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  8010. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  8011. void writeElementAsText (OutputStream& out,
  8012. const int indentationLevel,
  8013. const int lineWrapLength) const throw();
  8014. XmlElement** getChildElementsAsArray (const int) const throw();
  8015. void reorderChildElements (XmlElement** const, const int) throw();
  8016. };
  8017. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  8018. /********* End of inlined file: juce_XmlElement.h *********/
  8019. /**
  8020. A set of named property values, which can be strings, integers, floating point, etc.
  8021. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  8022. to load and save types other than strings.
  8023. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  8024. messages and saves/loads the list from a file.
  8025. */
  8026. class JUCE_API PropertySet
  8027. {
  8028. public:
  8029. /** Creates an empty PropertySet.
  8030. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  8031. case-insensitive way
  8032. */
  8033. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  8034. /** Creates a copy of another PropertySet.
  8035. */
  8036. PropertySet (const PropertySet& other) throw();
  8037. /** Copies another PropertySet over this one.
  8038. */
  8039. const PropertySet& operator= (const PropertySet& other) throw();
  8040. /** Destructor. */
  8041. virtual ~PropertySet();
  8042. /** Returns one of the properties as a string.
  8043. If the value isn't found in this set, then this will look for it in a fallback
  8044. property set (if you've specified one with the setFallbackPropertySet() method),
  8045. and if it can't find one there, it'll return the default value passed-in.
  8046. @param keyName the name of the property to retrieve
  8047. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8048. */
  8049. const String getValue (const String& keyName,
  8050. const String& defaultReturnValue = String::empty) const throw();
  8051. /** Returns one of the properties as an integer.
  8052. If the value isn't found in this set, then this will look for it in a fallback
  8053. property set (if you've specified one with the setFallbackPropertySet() method),
  8054. and if it can't find one there, it'll return the default value passed-in.
  8055. @param keyName the name of the property to retrieve
  8056. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8057. */
  8058. int getIntValue (const String& keyName,
  8059. const int defaultReturnValue = 0) const throw();
  8060. /** Returns one of the properties as an double.
  8061. If the value isn't found in this set, then this will look for it in a fallback
  8062. property set (if you've specified one with the setFallbackPropertySet() method),
  8063. and if it can't find one there, it'll return the default value passed-in.
  8064. @param keyName the name of the property to retrieve
  8065. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8066. */
  8067. double getDoubleValue (const String& keyName,
  8068. const double defaultReturnValue = 0.0) const throw();
  8069. /** Returns one of the properties as an boolean.
  8070. The result will be true if the string found for this key name can be parsed as a non-zero
  8071. integer.
  8072. If the value isn't found in this set, then this will look for it in a fallback
  8073. property set (if you've specified one with the setFallbackPropertySet() method),
  8074. and if it can't find one there, it'll return the default value passed-in.
  8075. @param keyName the name of the property to retrieve
  8076. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8077. */
  8078. bool getBoolValue (const String& keyName,
  8079. const bool defaultReturnValue = false) const throw();
  8080. /** Returns one of the properties as an XML element.
  8081. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  8082. key isn't found, or if the entry contains an string that isn't valid XML.
  8083. If the value isn't found in this set, then this will look for it in a fallback
  8084. property set (if you've specified one with the setFallbackPropertySet() method),
  8085. and if it can't find one there, it'll return the default value passed-in.
  8086. @param keyName the name of the property to retrieve
  8087. */
  8088. XmlElement* getXmlValue (const String& keyName) const;
  8089. /** Sets a named property as a string.
  8090. @param keyName the name of the property to set. (This mustn't be an empty string)
  8091. @param value the new value to set it to
  8092. */
  8093. void setValue (const String& keyName, const String& value) throw();
  8094. /** Sets a named property as a string.
  8095. @param keyName the name of the property to set. (This mustn't be an empty string)
  8096. @param value the new value to set it to
  8097. */
  8098. void setValue (const String& keyName, const tchar* const value) throw();
  8099. /** Sets a named property to an integer.
  8100. @param keyName the name of the property to set. (This mustn't be an empty string)
  8101. @param value the new value to set it to
  8102. */
  8103. void setValue (const String& keyName, const int value) throw();
  8104. /** Sets a named property to a double.
  8105. @param keyName the name of the property to set. (This mustn't be an empty string)
  8106. @param value the new value to set it to
  8107. */
  8108. void setValue (const String& keyName, const double value) throw();
  8109. /** Sets a named property to a boolean.
  8110. @param keyName the name of the property to set. (This mustn't be an empty string)
  8111. @param value the new value to set it to
  8112. */
  8113. void setValue (const String& keyName, const bool value) throw();
  8114. /** Sets a named property to an XML element.
  8115. @param keyName the name of the property to set. (This mustn't be an empty string)
  8116. @param xml the new element to set it to. If this is zero, the value will be set to
  8117. an empty string
  8118. @see getXmlValue
  8119. */
  8120. void setValue (const String& keyName, const XmlElement* const xml);
  8121. /** Deletes a property.
  8122. @param keyName the name of the property to delete. (This mustn't be an empty string)
  8123. */
  8124. void removeValue (const String& keyName) throw();
  8125. /** Returns true if the properies include the given key. */
  8126. bool containsKey (const String& keyName) const throw();
  8127. /** Removes all values. */
  8128. void clear();
  8129. /** Returns the keys/value pair array containing all the properties. */
  8130. StringPairArray& getAllProperties() throw() { return properties; }
  8131. /** Returns the lock used when reading or writing to this set */
  8132. const CriticalSection& getLock() const throw() { return lock; }
  8133. /** Returns an XML element which encapsulates all the items in this property set.
  8134. The string parameter is the tag name that should be used for the node.
  8135. @see restoreFromXml
  8136. */
  8137. XmlElement* createXml (const String& nodeName) const throw();
  8138. /** Reloads a set of properties that were previously stored as XML.
  8139. The node passed in must have been created by the createXml() method.
  8140. @see createXml
  8141. */
  8142. void restoreFromXml (const XmlElement& xml) throw();
  8143. /** Sets up a second PopertySet that will be used to look up any values that aren't
  8144. set in this one.
  8145. If you set this up to be a pointer to a second property set, then whenever one
  8146. of the getValue() methods fails to find an entry in this set, it will look up that
  8147. value in the fallback set, and if it finds it, it will return that.
  8148. Make sure that you don't delete the fallback set while it's still being used by
  8149. another set! To remove the fallback set, just call this method with a null pointer.
  8150. @see getFallbackPropertySet
  8151. */
  8152. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  8153. /** Returns the fallback property set.
  8154. @see setFallbackPropertySet
  8155. */
  8156. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  8157. juce_UseDebuggingNewOperator
  8158. protected:
  8159. /** Subclasses can override this to be told when one of the properies has been changed.
  8160. */
  8161. virtual void propertyChanged();
  8162. private:
  8163. StringPairArray properties;
  8164. PropertySet* fallbackProperties;
  8165. CriticalSection lock;
  8166. bool ignoreCaseOfKeys;
  8167. };
  8168. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  8169. /********* End of inlined file: juce_PropertySet.h *********/
  8170. #endif
  8171. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8172. /********* Start of inlined file: juce_SortedSet.h *********/
  8173. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8174. #define __JUCE_SORTEDSET_JUCEHEADER__
  8175. #if JUCE_MSVC
  8176. #pragma warning (push)
  8177. #pragma warning (disable: 4512)
  8178. #endif
  8179. /**
  8180. Holds a set of unique primitive objects, such as ints or doubles.
  8181. A set can only hold one item with a given value, so if for example it's a
  8182. set of integers, attempting to add the same integer twice will do nothing
  8183. the second time.
  8184. Internally, the list of items is kept sorted (which means that whatever
  8185. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8186. to determine the order), and searching the set for known values is very fast
  8187. because it uses a binary-chop method.
  8188. Note that if you're using a class or struct as the element type, it must be
  8189. capable of being copied or moved with a straightforward memcpy, rather than
  8190. needing construction and destruction code.
  8191. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8192. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8193. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8194. */
  8195. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8196. class SortedSet : private ArrayAllocationBase <ElementType>
  8197. {
  8198. public:
  8199. /** Creates an empty set.
  8200. @param granularity this is the size of increment by which the internal storage
  8201. used by the array will grow. Only change it from the default if you know the
  8202. array is going to be very big and needs to be able to grow efficiently.
  8203. @see ArrayAllocationBase
  8204. */
  8205. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  8206. : ArrayAllocationBase <ElementType> (granularity),
  8207. numUsed (0)
  8208. {
  8209. }
  8210. /** Creates a copy of another set.
  8211. @param other the set to copy
  8212. */
  8213. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8214. : ArrayAllocationBase <ElementType> (other.granularity)
  8215. {
  8216. other.lockSet();
  8217. numUsed = other.numUsed;
  8218. setAllocatedSize (other.numUsed);
  8219. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  8220. other.unlockSet();
  8221. }
  8222. /** Destructor. */
  8223. ~SortedSet() throw()
  8224. {
  8225. }
  8226. /** Copies another set over this one.
  8227. @param other the set to copy
  8228. */
  8229. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8230. {
  8231. if (this != &other)
  8232. {
  8233. other.lockSet();
  8234. lock.enter();
  8235. this->granularity = other.granularity;
  8236. ensureAllocatedSize (other.size());
  8237. numUsed = other.numUsed;
  8238. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  8239. minimiseStorageOverheads();
  8240. lock.exit();
  8241. other.unlockSet();
  8242. }
  8243. return *this;
  8244. }
  8245. /** Compares this set to another one.
  8246. Two sets are considered equal if they both contain the same set of
  8247. elements.
  8248. @param other the other set to compare with
  8249. */
  8250. bool operator== (const SortedSet<ElementType>& other) const throw()
  8251. {
  8252. lock.enter();
  8253. if (numUsed != other.numUsed)
  8254. {
  8255. lock.exit();
  8256. return false;
  8257. }
  8258. for (int i = numUsed; --i >= 0;)
  8259. {
  8260. if (this->elements [i] != other.elements [i])
  8261. {
  8262. lock.exit();
  8263. return false;
  8264. }
  8265. }
  8266. lock.exit();
  8267. return true;
  8268. }
  8269. /** Compares this set to another one.
  8270. Two sets are considered equal if they both contain the same set of
  8271. elements.
  8272. @param other the other set to compare with
  8273. */
  8274. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8275. {
  8276. return ! operator== (other);
  8277. }
  8278. /** Removes all elements from the set.
  8279. This will remove all the elements, and free any storage that the set is
  8280. using. To clear it without freeing the storage, use the clearQuick()
  8281. method instead.
  8282. @see clearQuick
  8283. */
  8284. void clear() throw()
  8285. {
  8286. lock.enter();
  8287. this->setAllocatedSize (0);
  8288. numUsed = 0;
  8289. lock.exit();
  8290. }
  8291. /** Removes all elements from the set without freeing the array's allocated storage.
  8292. @see clear
  8293. */
  8294. void clearQuick() throw()
  8295. {
  8296. lock.enter();
  8297. numUsed = 0;
  8298. lock.exit();
  8299. }
  8300. /** Returns the current number of elements in the set.
  8301. */
  8302. inline int size() const throw()
  8303. {
  8304. return numUsed;
  8305. }
  8306. /** Returns one of the elements in the set.
  8307. If the index passed in is beyond the range of valid elements, this
  8308. will return zero.
  8309. If you're certain that the index will always be a valid element, you
  8310. can call getUnchecked() instead, which is faster.
  8311. @param index the index of the element being requested (0 is the first element in the set)
  8312. @see getUnchecked, getFirst, getLast
  8313. */
  8314. inline ElementType operator[] (const int index) const throw()
  8315. {
  8316. lock.enter();
  8317. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8318. ? this->elements [index]
  8319. : (ElementType) 0;
  8320. lock.exit();
  8321. return result;
  8322. }
  8323. /** Returns one of the elements in the set, without checking the index passed in.
  8324. Unlike the operator[] method, this will try to return an element without
  8325. checking that the index is within the bounds of the set, so should only
  8326. be used when you're confident that it will always be a valid index.
  8327. @param index the index of the element being requested (0 is the first element in the set)
  8328. @see operator[], getFirst, getLast
  8329. */
  8330. inline ElementType getUnchecked (const int index) const throw()
  8331. {
  8332. lock.enter();
  8333. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8334. const ElementType result = this->elements [index];
  8335. lock.exit();
  8336. return result;
  8337. }
  8338. /** Returns the first element in the set, or 0 if the set is empty.
  8339. @see operator[], getUnchecked, getLast
  8340. */
  8341. inline ElementType getFirst() const throw()
  8342. {
  8343. lock.enter();
  8344. const ElementType result = (numUsed > 0) ? this->elements [0]
  8345. : (ElementType) 0;
  8346. lock.exit();
  8347. return result;
  8348. }
  8349. /** Returns the last element in the set, or 0 if the set is empty.
  8350. @see operator[], getUnchecked, getFirst
  8351. */
  8352. inline ElementType getLast() const throw()
  8353. {
  8354. lock.enter();
  8355. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8356. : (ElementType) 0;
  8357. lock.exit();
  8358. return result;
  8359. }
  8360. /** Finds the index of the first element which matches the value passed in.
  8361. This will search the set for the given object, and return the index
  8362. of its first occurrence. If the object isn't found, the method will return -1.
  8363. @param elementToLookFor the value or object to look for
  8364. @returns the index of the object, or -1 if it's not found
  8365. */
  8366. int indexOf (const ElementType elementToLookFor) const throw()
  8367. {
  8368. lock.enter();
  8369. int start = 0;
  8370. int end = numUsed;
  8371. for (;;)
  8372. {
  8373. if (start >= end)
  8374. {
  8375. lock.exit();
  8376. return -1;
  8377. }
  8378. else if (elementToLookFor == this->elements [start])
  8379. {
  8380. lock.exit();
  8381. return start;
  8382. }
  8383. else
  8384. {
  8385. const int halfway = (start + end) >> 1;
  8386. if (halfway == start)
  8387. {
  8388. lock.exit();
  8389. return -1;
  8390. }
  8391. else if (elementToLookFor >= this->elements [halfway])
  8392. start = halfway;
  8393. else
  8394. end = halfway;
  8395. }
  8396. }
  8397. }
  8398. /** Returns true if the set contains at least one occurrence of an object.
  8399. @param elementToLookFor the value or object to look for
  8400. @returns true if the item is found
  8401. */
  8402. bool contains (const ElementType elementToLookFor) const throw()
  8403. {
  8404. lock.enter();
  8405. int start = 0;
  8406. int end = numUsed;
  8407. for (;;)
  8408. {
  8409. if (start >= end)
  8410. {
  8411. lock.exit();
  8412. return false;
  8413. }
  8414. else if (elementToLookFor == this->elements [start])
  8415. {
  8416. lock.exit();
  8417. return true;
  8418. }
  8419. else
  8420. {
  8421. const int halfway = (start + end) >> 1;
  8422. if (halfway == start)
  8423. {
  8424. lock.exit();
  8425. return false;
  8426. }
  8427. else if (elementToLookFor >= this->elements [halfway])
  8428. start = halfway;
  8429. else
  8430. end = halfway;
  8431. }
  8432. }
  8433. }
  8434. /** Adds a new element to the set, (as long as it's not already in there).
  8435. @param newElement the new object to add to the set
  8436. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8437. */
  8438. void add (const ElementType newElement) throw()
  8439. {
  8440. lock.enter();
  8441. int start = 0;
  8442. int end = numUsed;
  8443. for (;;)
  8444. {
  8445. if (start >= end)
  8446. {
  8447. jassert (start <= end);
  8448. insertInternal (start, newElement);
  8449. break;
  8450. }
  8451. else if (newElement == this->elements [start])
  8452. {
  8453. break;
  8454. }
  8455. else
  8456. {
  8457. const int halfway = (start + end) >> 1;
  8458. if (halfway == start)
  8459. {
  8460. if (newElement >= this->elements [halfway])
  8461. insertInternal (start + 1, newElement);
  8462. else
  8463. insertInternal (start, newElement);
  8464. break;
  8465. }
  8466. else if (newElement >= this->elements [halfway])
  8467. start = halfway;
  8468. else
  8469. end = halfway;
  8470. }
  8471. }
  8472. lock.exit();
  8473. }
  8474. /** Adds elements from an array to this set.
  8475. @param elementsToAdd the array of elements to add
  8476. @param numElementsToAdd how many elements are in this other array
  8477. @see add
  8478. */
  8479. void addArray (const ElementType* elementsToAdd,
  8480. int numElementsToAdd) throw()
  8481. {
  8482. lock.enter();
  8483. while (--numElementsToAdd >= 0)
  8484. add (*elementsToAdd++);
  8485. lock.exit();
  8486. }
  8487. /** Adds elements from another set to this one.
  8488. @param setToAddFrom the set from which to copy the elements
  8489. @param startIndex the first element of the other set to start copying from
  8490. @param numElementsToAdd how many elements to add from the other set. If this
  8491. value is negative or greater than the number of available elements,
  8492. all available elements will be copied.
  8493. @see add
  8494. */
  8495. template <class OtherSetType>
  8496. void addSet (const OtherSetType& setToAddFrom,
  8497. int startIndex = 0,
  8498. int numElementsToAdd = -1) throw()
  8499. {
  8500. setToAddFrom.lockSet();
  8501. lock.enter();
  8502. jassert (this != &setToAddFrom);
  8503. if (this != &setToAddFrom)
  8504. {
  8505. if (startIndex < 0)
  8506. {
  8507. jassertfalse
  8508. startIndex = 0;
  8509. }
  8510. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8511. numElementsToAdd = setToAddFrom.size() - startIndex;
  8512. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8513. }
  8514. lock.exit();
  8515. setToAddFrom.unlockSet();
  8516. }
  8517. /** Removes an element from the set.
  8518. This will remove the element at a given index.
  8519. If the index passed in is out-of-range, nothing will happen.
  8520. @param indexToRemove the index of the element to remove
  8521. @returns the element that has been removed
  8522. @see removeValue, removeRange
  8523. */
  8524. ElementType remove (const int indexToRemove) throw()
  8525. {
  8526. lock.enter();
  8527. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8528. {
  8529. --numUsed;
  8530. ElementType* const e = this->elements + indexToRemove;
  8531. ElementType const removed = *e;
  8532. const int numberToShift = numUsed - indexToRemove;
  8533. if (numberToShift > 0)
  8534. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8535. if ((numUsed << 1) < this->numAllocated)
  8536. minimiseStorageOverheads();
  8537. lock.exit();
  8538. return removed;
  8539. }
  8540. else
  8541. {
  8542. lock.exit();
  8543. return 0;
  8544. }
  8545. }
  8546. /** Removes an item from the set.
  8547. This will remove the given element from the set, if it's there.
  8548. @param valueToRemove the object to try to remove
  8549. @see remove, removeRange
  8550. */
  8551. void removeValue (const ElementType valueToRemove) throw()
  8552. {
  8553. lock.enter();
  8554. remove (indexOf (valueToRemove));
  8555. lock.exit();
  8556. }
  8557. /** Removes any elements which are also in another set.
  8558. @param otherSet the other set in which to look for elements to remove
  8559. @see removeValuesNotIn, remove, removeValue, removeRange
  8560. */
  8561. template <class OtherSetType>
  8562. void removeValuesIn (const OtherSetType& otherSet) throw()
  8563. {
  8564. otherSet.lockSet();
  8565. lock.enter();
  8566. if (this == &otherSet)
  8567. {
  8568. clear();
  8569. }
  8570. else
  8571. {
  8572. if (otherSet.size() > 0)
  8573. {
  8574. for (int i = numUsed; --i >= 0;)
  8575. if (otherSet.contains (this->elements [i]))
  8576. remove (i);
  8577. }
  8578. }
  8579. lock.exit();
  8580. otherSet.unlockSet();
  8581. }
  8582. /** Removes any elements which are not found in another set.
  8583. Only elements which occur in this other set will be retained.
  8584. @param otherSet the set in which to look for elements NOT to remove
  8585. @see removeValuesIn, remove, removeValue, removeRange
  8586. */
  8587. template <class OtherSetType>
  8588. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8589. {
  8590. otherSet.lockSet();
  8591. lock.enter();
  8592. if (this != &otherSet)
  8593. {
  8594. if (otherSet.size() <= 0)
  8595. {
  8596. clear();
  8597. }
  8598. else
  8599. {
  8600. for (int i = numUsed; --i >= 0;)
  8601. if (! otherSet.contains (this->elements [i]))
  8602. remove (i);
  8603. }
  8604. }
  8605. lock.exit();
  8606. otherSet.lockSet();
  8607. }
  8608. /** Reduces the amount of storage being used by the set.
  8609. Sets typically allocate slightly more storage than they need, and after
  8610. removing elements, they may have quite a lot of unused space allocated.
  8611. This method will reduce the amount of allocated storage to a minimum.
  8612. */
  8613. void minimiseStorageOverheads() throw()
  8614. {
  8615. lock.enter();
  8616. if (numUsed == 0)
  8617. {
  8618. this->setAllocatedSize (0);
  8619. }
  8620. else
  8621. {
  8622. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8623. if (newAllocation < this->numAllocated)
  8624. this->setAllocatedSize (newAllocation);
  8625. }
  8626. lock.exit();
  8627. }
  8628. /** Locks the set's CriticalSection.
  8629. Of course if the type of section used is a DummyCriticalSection, this won't
  8630. have any effect.
  8631. @see unlockSet
  8632. */
  8633. void lockSet() const throw()
  8634. {
  8635. lock.enter();
  8636. }
  8637. /** Unlocks the set's CriticalSection.
  8638. Of course if the type of section used is a DummyCriticalSection, this won't
  8639. have any effect.
  8640. @see lockSet
  8641. */
  8642. void unlockSet() const throw()
  8643. {
  8644. lock.exit();
  8645. }
  8646. juce_UseDebuggingNewOperator
  8647. private:
  8648. int numUsed;
  8649. TypeOfCriticalSectionToUse lock;
  8650. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8651. {
  8652. this->ensureAllocatedSize (numUsed + 1);
  8653. ElementType* const insertPos = this->elements + indexToInsertAt;
  8654. const int numberToMove = numUsed - indexToInsertAt;
  8655. if (numberToMove > 0)
  8656. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8657. *insertPos = newElement;
  8658. ++numUsed;
  8659. }
  8660. };
  8661. #if JUCE_MSVC
  8662. #pragma warning (pop)
  8663. #endif
  8664. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8665. /********* End of inlined file: juce_SortedSet.h *********/
  8666. #endif
  8667. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  8668. #endif
  8669. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  8670. #endif
  8671. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8672. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  8673. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8674. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8675. /**
  8676. Searches through a the files in a directory, returning each file that is found.
  8677. A DirectoryIterator will search through a directory and its subdirectories using
  8678. a wildcard filepattern match.
  8679. If you may be finding a large number of files, this is better than
  8680. using File::findChildFiles() because it doesn't block while it finds them
  8681. all, and this is more memory-efficient.
  8682. It can also guess how far it's got using a wildly inaccurate algorithm.
  8683. */
  8684. class JUCE_API DirectoryIterator
  8685. {
  8686. public:
  8687. /** Creates a DirectoryIterator for a given directory.
  8688. After creating one of these, call its next() method to get the
  8689. first file - e.g. @code
  8690. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  8691. while (iter.next())
  8692. {
  8693. File theFileItFound (iter.getFile());
  8694. ... etc
  8695. }
  8696. @endcode
  8697. @param directory the directory to search in
  8698. @param isRecursive whether all the subdirectories should also be searched
  8699. @param wildCard the file pattern to match
  8700. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  8701. whether to look for files, directories, or both.
  8702. */
  8703. DirectoryIterator (const File& directory,
  8704. bool isRecursive,
  8705. const String& wildCard = JUCE_T("*"),
  8706. const int whatToLookFor = File::findFiles) throw();
  8707. /** Destructor. */
  8708. ~DirectoryIterator() throw();
  8709. /** Call this to move the iterator along to the next file.
  8710. @returns true if a file was found (you can then use getFile() to see what it was) - or
  8711. false if there are no more matching files.
  8712. */
  8713. bool next() throw();
  8714. /** Returns the file that the iterator is currently pointing at.
  8715. The result of this call is only valid after a call to next() has returned true.
  8716. */
  8717. const File getFile() const throw();
  8718. /** Returns a guess of how far through the search the iterator has got.
  8719. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  8720. very accurate.
  8721. */
  8722. float getEstimatedProgress() const throw();
  8723. juce_UseDebuggingNewOperator
  8724. private:
  8725. OwnedArray <File> filesFound;
  8726. OwnedArray <File> dirsFound;
  8727. String wildCard;
  8728. int index;
  8729. const int whatToLookFor;
  8730. DirectoryIterator* subIterator;
  8731. DirectoryIterator (const DirectoryIterator&);
  8732. const DirectoryIterator& operator= (const DirectoryIterator&);
  8733. };
  8734. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8735. /********* End of inlined file: juce_DirectoryIterator.h *********/
  8736. #endif
  8737. #ifndef __JUCE_FILE_JUCEHEADER__
  8738. #endif
  8739. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8740. /********* Start of inlined file: juce_FileInputStream.h *********/
  8741. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8742. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8743. /**
  8744. An input stream that reads from a local file.
  8745. @see InputStream, FileOutputStream, File::createInputStream
  8746. */
  8747. class JUCE_API FileInputStream : public InputStream
  8748. {
  8749. public:
  8750. /** Creates a FileInputStream.
  8751. @param fileToRead the file to read from - if the file can't be accessed for some
  8752. reason, then the stream will just contain no data
  8753. */
  8754. FileInputStream (const File& fileToRead);
  8755. /** Destructor. */
  8756. ~FileInputStream();
  8757. const File& getFile() const throw() { return file; }
  8758. int64 getTotalLength();
  8759. int read (void* destBuffer, int maxBytesToRead);
  8760. bool isExhausted();
  8761. int64 getPosition();
  8762. bool setPosition (int64 pos);
  8763. juce_UseDebuggingNewOperator
  8764. private:
  8765. File file;
  8766. void* fileHandle;
  8767. int64 currentPosition, totalSize;
  8768. bool needToSeek;
  8769. };
  8770. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8771. /********* End of inlined file: juce_FileInputStream.h *********/
  8772. #endif
  8773. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8774. /********* Start of inlined file: juce_FileOutputStream.h *********/
  8775. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8776. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8777. /**
  8778. An output stream that writes into a local file.
  8779. @see OutputStream, FileInputStream, File::createOutputStream
  8780. */
  8781. class JUCE_API FileOutputStream : public OutputStream
  8782. {
  8783. public:
  8784. /** Creates a FileOutputStream.
  8785. If the file doesn't exist, it will first be created. If the file can't be
  8786. created or opened, the failedToOpen() method will return
  8787. true.
  8788. If the file already exists when opened, the stream's write-postion will
  8789. be set to the end of the file. To overwrite an existing file,
  8790. use File::deleteFile() before opening the stream, or use setPosition(0)
  8791. after it's opened (although this won't truncate the file).
  8792. It's better to use File::createOutputStream() to create one of these, rather
  8793. than using the class directly.
  8794. */
  8795. FileOutputStream (const File& fileToWriteTo,
  8796. const int bufferSizeToUse = 16384);
  8797. /** Destructor. */
  8798. ~FileOutputStream();
  8799. /** Returns the file that this stream is writing to.
  8800. */
  8801. const File& getFile() const throw() { return file; }
  8802. /** Returns true if the stream couldn't be opened for some reason.
  8803. */
  8804. bool failedToOpen() const throw() { return fileHandle == 0; }
  8805. void flush();
  8806. int64 getPosition();
  8807. bool setPosition (int64 pos);
  8808. bool write (const void* data, int numBytes);
  8809. juce_UseDebuggingNewOperator
  8810. private:
  8811. File file;
  8812. void* fileHandle;
  8813. int64 currentPosition;
  8814. int bufferSize, bytesInBuffer;
  8815. char* buffer;
  8816. };
  8817. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8818. /********* End of inlined file: juce_FileOutputStream.h *********/
  8819. #endif
  8820. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8821. /********* Start of inlined file: juce_FileSearchPath.h *********/
  8822. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8823. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  8824. /**
  8825. Encapsulates a set of folders that make up a search path.
  8826. @see File
  8827. */
  8828. class JUCE_API FileSearchPath
  8829. {
  8830. public:
  8831. /** Creates an empty search path. */
  8832. FileSearchPath();
  8833. /** Creates a search path from a string of pathnames.
  8834. The path can be semicolon- or comma-separated, e.g.
  8835. "/foo/bar;/foo/moose;/fish/moose"
  8836. The separate folders are tokenised and added to the search path.
  8837. */
  8838. FileSearchPath (const String& path);
  8839. /** Creates a copy of another search path. */
  8840. FileSearchPath (const FileSearchPath& other);
  8841. /** Destructor. */
  8842. ~FileSearchPath();
  8843. /** Uses a string containing a list of pathnames to re-initialise this list.
  8844. This search path is cleared and the semicolon- or comma-separated folders
  8845. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  8846. */
  8847. const FileSearchPath& operator= (const String& path);
  8848. /** Returns the number of folders in this search path.
  8849. @see operator[]
  8850. */
  8851. int getNumPaths() const;
  8852. /** Returns one of the folders in this search path.
  8853. The file returned isn't guaranteed to actually be a valid directory.
  8854. @see getNumPaths
  8855. */
  8856. const File operator[] (const int index) const;
  8857. /** Returns the search path as a semicolon-separated list of directories. */
  8858. const String toString() const;
  8859. /** Adds a new directory to the search path.
  8860. The new directory is added to the end of the list if the insertIndex parameter is
  8861. less than zero, otherwise it is inserted at the given index.
  8862. */
  8863. void add (const File& directoryToAdd,
  8864. const int insertIndex = -1);
  8865. /** Adds a new directory to the search path if it's not already in there. */
  8866. void addIfNotAlreadyThere (const File& directoryToAdd);
  8867. /** Removes a directory from the search path. */
  8868. void remove (const int indexToRemove);
  8869. /** Merges another search path into this one.
  8870. This will remove any duplicate directories.
  8871. */
  8872. void addPath (const FileSearchPath& other);
  8873. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  8874. If the search is intended to be recursive, there's no point having nested folders in the search
  8875. path, because they'll just get searched twice and you'll get duplicate results.
  8876. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  8877. */
  8878. void removeRedundantPaths();
  8879. /** Removes any directories that don't actually exist. */
  8880. void removeNonExistentPaths();
  8881. /** Searches the path for a wildcard.
  8882. This will search all the directories in the search path in order, adding any
  8883. matching files to the results array.
  8884. @param results an array to append the results to
  8885. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  8886. return files, directories, or both.
  8887. @param searchRecursively whether to recursively search the subdirectories too
  8888. @param wildCardPattern a pattern to match against the filenames
  8889. @returns the number of files added to the array
  8890. @see File::findChildFiles
  8891. */
  8892. int findChildFiles (OwnedArray<File>& results,
  8893. const int whatToLookFor,
  8894. const bool searchRecursively,
  8895. const String& wildCardPattern = JUCE_T("*")) const;
  8896. /** Finds out whether a file is inside one of the path's directories.
  8897. This will return true if the specified file is a child of one of the
  8898. directories specified by this path. Note that this doesn't actually do any
  8899. searching or check that the files exist - it just looks at the pathnames
  8900. to work out whether the file would be inside a directory.
  8901. @param fileToCheck the file to look for
  8902. @param checkRecursively if true, then this will return true if the file is inside a
  8903. subfolder of one of the path's directories (at any depth). If false
  8904. it will only return true if the file is actually a direct child
  8905. of one of the directories.
  8906. @see File::isAChildOf
  8907. */
  8908. bool isFileInPath (const File& fileToCheck,
  8909. const bool checkRecursively) const;
  8910. juce_UseDebuggingNewOperator
  8911. private:
  8912. StringArray directories;
  8913. void init (const String& path);
  8914. };
  8915. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  8916. /********* End of inlined file: juce_FileSearchPath.h *********/
  8917. #endif
  8918. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8919. /********* Start of inlined file: juce_NamedPipe.h *********/
  8920. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8921. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  8922. /**
  8923. A cross-process pipe that can have data written to and read from it.
  8924. Two or more processes can use these for inter-process communication.
  8925. @see InterprocessConnection
  8926. */
  8927. class JUCE_API NamedPipe
  8928. {
  8929. public:
  8930. /** Creates a NamedPipe. */
  8931. NamedPipe();
  8932. /** Destructor. */
  8933. ~NamedPipe();
  8934. /** Tries to open a pipe that already exists.
  8935. Returns true if it succeeds.
  8936. */
  8937. bool openExisting (const String& pipeName);
  8938. /** Tries to create a new pipe.
  8939. Returns true if it succeeds.
  8940. */
  8941. bool createNewPipe (const String& pipeName);
  8942. /** Closes the pipe, if it's open. */
  8943. void close();
  8944. /** True if the pipe is currently open. */
  8945. bool isOpen() const throw();
  8946. /** Returns the last name that was used to try to open this pipe. */
  8947. const String getName() const throw();
  8948. /** Reads data from the pipe.
  8949. This will block until another thread has written enough data into the pipe to fill
  8950. the number of bytes specified, or until another thread calls the cancelPendingReads()
  8951. method.
  8952. If the operation fails, it returns -1, otherwise, it will return the number of
  8953. bytes read.
  8954. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  8955. this is a maximum timeout for reading from the pipe.
  8956. */
  8957. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  8958. /** Writes some data to the pipe.
  8959. If the operation fails, it returns -1, otherwise, it will return the number of
  8960. bytes written.
  8961. */
  8962. int write (const void* sourceBuffer, int numBytesToWrite,
  8963. int timeOutMilliseconds = 2000);
  8964. /** If any threads are currently blocked on a read operation, this tells them to abort.
  8965. */
  8966. void cancelPendingReads();
  8967. juce_UseDebuggingNewOperator
  8968. private:
  8969. void* internal;
  8970. String currentPipeName;
  8971. NamedPipe (const NamedPipe&);
  8972. const NamedPipe& operator= (const NamedPipe&);
  8973. bool openInternal (const String& pipeName, const bool createPipe);
  8974. };
  8975. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  8976. /********* End of inlined file: juce_NamedPipe.h *********/
  8977. #endif
  8978. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8979. /********* Start of inlined file: juce_BlowFish.h *********/
  8980. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8981. #define __JUCE_BLOWFISH_JUCEHEADER__
  8982. /**
  8983. BlowFish encryption class.
  8984. */
  8985. class JUCE_API BlowFish
  8986. {
  8987. public:
  8988. /** Creates an object that can encode/decode based on the specified key.
  8989. The key data can be up to 72 bytes long.
  8990. */
  8991. BlowFish (const uint8* keyData, int keyBytes);
  8992. /** Creates a copy of another blowfish object. */
  8993. BlowFish (const BlowFish& other);
  8994. /** Copies another blowfish object. */
  8995. const BlowFish& operator= (const BlowFish& other);
  8996. /** Destructor. */
  8997. ~BlowFish();
  8998. /** Encrypts a pair of 32-bit integers. */
  8999. void encrypt (uint32& data1, uint32& data2) const;
  9000. /** Decrypts a pair of 32-bit integers. */
  9001. void decrypt (uint32& data1, uint32& data2) const;
  9002. juce_UseDebuggingNewOperator
  9003. private:
  9004. uint32 p[18];
  9005. uint32* s[4];
  9006. uint32 F (uint32 x) const;
  9007. };
  9008. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  9009. /********* End of inlined file: juce_BlowFish.h *********/
  9010. #endif
  9011. #ifndef __JUCE_MD5_JUCEHEADER__
  9012. /********* Start of inlined file: juce_MD5.h *********/
  9013. #ifndef __JUCE_MD5_JUCEHEADER__
  9014. #define __JUCE_MD5_JUCEHEADER__
  9015. /**
  9016. MD5 checksum class.
  9017. Create one of these with a block of source data or a string, and it calculates the
  9018. MD5 checksum of that data.
  9019. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  9020. */
  9021. class JUCE_API MD5
  9022. {
  9023. public:
  9024. /** Creates a null MD5 object. */
  9025. MD5();
  9026. /** Creates a copy of another MD5. */
  9027. MD5 (const MD5& other);
  9028. /** Copies another MD5. */
  9029. const MD5& operator= (const MD5& other);
  9030. /** Creates a checksum for a block of binary data. */
  9031. MD5 (const MemoryBlock& data);
  9032. /** Creates a checksum for a block of binary data. */
  9033. MD5 (const char* data, const int numBytes);
  9034. /** Creates a checksum for a string.
  9035. Note that this operates on the string as a block of unicode characters, so the
  9036. result you get will differ from the value you'd get if the string was treated
  9037. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  9038. of this method with a checksum created by a different framework, which may have
  9039. used a different encoding.
  9040. */
  9041. MD5 (const String& text);
  9042. /** Creates a checksum for the input from a stream.
  9043. This will read up to the given number of bytes from the stream, and produce the
  9044. checksum of that. If the number of bytes to read is negative, it'll read
  9045. until the stream is exhausted.
  9046. */
  9047. MD5 (InputStream& input, int numBytesToRead = -1);
  9048. /** Creates a checksum for a file. */
  9049. MD5 (const File& file);
  9050. /** Destructor. */
  9051. ~MD5();
  9052. /** Returns the checksum as a 16-byte block of data. */
  9053. const MemoryBlock getRawChecksumData() const;
  9054. /** Returns the checksum as a 32-digit hex string. */
  9055. const String toHexString() const;
  9056. /** Compares this to another MD5. */
  9057. bool operator== (const MD5& other) const;
  9058. /** Compares this to another MD5. */
  9059. bool operator!= (const MD5& other) const;
  9060. juce_UseDebuggingNewOperator
  9061. private:
  9062. uint8 result [16];
  9063. struct ProcessContext
  9064. {
  9065. uint8 buffer [64];
  9066. uint32 state [4];
  9067. uint32 count [2];
  9068. ProcessContext();
  9069. void processBlock (const uint8* const data, int dataSize);
  9070. void transform (const uint8* const buffer);
  9071. void finish (uint8* const result);
  9072. };
  9073. void processStream (InputStream& input, int numBytesToRead);
  9074. };
  9075. #endif // __JUCE_MD5_JUCEHEADER__
  9076. /********* End of inlined file: juce_MD5.h *********/
  9077. #endif
  9078. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9079. /********* Start of inlined file: juce_Primes.h *********/
  9080. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9081. #define __JUCE_PRIMES_JUCEHEADER__
  9082. /**
  9083. Prime number creation class.
  9084. This class contains static methods for generating and testing prime numbers.
  9085. @see BitArray
  9086. */
  9087. class JUCE_API Primes
  9088. {
  9089. public:
  9090. /** Creates a random prime number with a given bit-length.
  9091. The certainty parameter specifies how many iterations to use when testing
  9092. for primality. A safe value might be anything over about 20-30.
  9093. The randomSeeds parameter lets you optionally pass it a set of values with
  9094. which to seed the random number generation, improving the security of the
  9095. keys generated.
  9096. */
  9097. static const BitArray createProbablePrime (int bitLength,
  9098. int certainty,
  9099. const int* randomSeeds = 0,
  9100. int numRandomSeeds = 0) throw();
  9101. /** Tests a number to see if it's prime.
  9102. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9103. whether the number is prime.
  9104. The certainty parameter specifies how many iterations to use when testing - a
  9105. safe value might be anything over about 20-30.
  9106. */
  9107. static bool isProbablyPrime (const BitArray& number,
  9108. int certainty) throw();
  9109. };
  9110. #endif // __JUCE_PRIMES_JUCEHEADER__
  9111. /********* End of inlined file: juce_Primes.h *********/
  9112. #endif
  9113. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9114. /********* Start of inlined file: juce_RSAKey.h *********/
  9115. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9116. #define __JUCE_RSAKEY_JUCEHEADER__
  9117. /**
  9118. RSA public/private key-pair encryption class.
  9119. An object of this type makes up one half of a public/private RSA key pair. Use the
  9120. createKeyPair() method to create a matching pair for encoding/decoding.
  9121. */
  9122. class JUCE_API RSAKey
  9123. {
  9124. public:
  9125. /** Creates a null key object.
  9126. Initialise a pair of objects for use with the createKeyPair() method.
  9127. */
  9128. RSAKey() throw();
  9129. /** Loads a key from an encoded string representation.
  9130. This reloads a key from a string created by the toString() method.
  9131. */
  9132. RSAKey (const String& stringRepresentation) throw();
  9133. /** Destructor. */
  9134. ~RSAKey() throw();
  9135. /** Turns the key into a string representation.
  9136. This can be reloaded using the constructor that takes a string.
  9137. */
  9138. const String toString() const throw();
  9139. /** Encodes or decodes a value.
  9140. Call this on the public key object to encode some data, then use the matching
  9141. private key object to decode it.
  9142. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9143. */
  9144. bool applyToValue (BitArray& value) const throw();
  9145. /** Creates a public/private key-pair.
  9146. Each key will perform one-way encryption that can only be reversed by
  9147. using the other key.
  9148. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9149. sizes are more secure, but this method will take longer to execute.
  9150. The randomSeeds parameter lets you optionally pass it a set of values with
  9151. which to seed the random number generation, improving the security of the
  9152. keys generated.
  9153. */
  9154. static void createKeyPair (RSAKey& publicKey,
  9155. RSAKey& privateKey,
  9156. const int numBits,
  9157. const int* randomSeeds = 0,
  9158. const int numRandomSeeds = 0) throw();
  9159. juce_UseDebuggingNewOperator
  9160. protected:
  9161. BitArray part1, part2;
  9162. };
  9163. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9164. /********* End of inlined file: juce_RSAKey.h *********/
  9165. #endif
  9166. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9167. /********* Start of inlined file: juce_Socket.h *********/
  9168. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9169. #define __JUCE_SOCKET_JUCEHEADER__
  9170. /**
  9171. A wrapper for a streaming (TCP) socket.
  9172. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9173. sockets, you could also try the InterprocessConnection class.
  9174. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9175. */
  9176. class JUCE_API StreamingSocket
  9177. {
  9178. public:
  9179. /** Creates an uninitialised socket.
  9180. To connect it, use the connect() method, after which you can read() or write()
  9181. to it.
  9182. To wait for other sockets to connect to this one, the createListener() method
  9183. enters "listener" mode, and can be used to spawn new sockets for each connection
  9184. that comes along.
  9185. */
  9186. StreamingSocket();
  9187. /** Destructor. */
  9188. ~StreamingSocket();
  9189. /** Binds the socket to the specified local port.
  9190. @returns true on success; false may indicate that another socket is already bound
  9191. on the same port
  9192. */
  9193. bool bindToPort (const int localPortNumber);
  9194. /** Tries to connect the socket to hostname:port.
  9195. If timeOutMillisecs is 0, then this method will block until the operating system
  9196. rejects the connection (which could take a long time).
  9197. @returns true if it succeeds.
  9198. @see isConnected
  9199. */
  9200. bool connect (const String& remoteHostname,
  9201. const int remotePortNumber,
  9202. const int timeOutMillisecs = 3000);
  9203. /** True if the socket is currently connected. */
  9204. bool isConnected() const throw() { return connected; }
  9205. /** Closes the connection. */
  9206. void close();
  9207. /** Returns the name of the currently connected host. */
  9208. const String& getHostName() const throw() { return hostName; }
  9209. /** Returns the port number that's currently open. */
  9210. int getPort() const throw() { return portNumber; }
  9211. /** True if the socket is connected to this machine rather than over the network. */
  9212. bool isLocal() const throw();
  9213. /** Waits until the socket is ready for reading or writing.
  9214. If readyForReading is true, it will wait until the socket is ready for
  9215. reading; if false, it will wait until it's ready for writing.
  9216. If the timeout is < 0, it will wait forever, or else will give up after
  9217. the specified time.
  9218. If the socket is ready on return, this returns 1. If it times-out before
  9219. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9220. */
  9221. int waitUntilReady (const bool readyForReading,
  9222. const int timeoutMsecs) const;
  9223. /** Reads bytes from the socket (blocking).
  9224. Note that this method will block unless you have checked the socket is ready
  9225. for reading before calling it (see the waitUntilReady() method).
  9226. @returns the number of bytes read, or -1 if there was an error.
  9227. */
  9228. int read (void* destBuffer, const int maxBytesToRead);
  9229. /** Writes bytes to the socket from a buffer.
  9230. Note that this method will block unless you have checked the socket is ready
  9231. for writing before calling it (see the waitUntilReady() method).
  9232. @returns the number of bytes written, or -1 if there was an error.
  9233. */
  9234. int write (const void* sourceBuffer, const int numBytesToWrite);
  9235. /** Puts this socket into "listener" mode.
  9236. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9237. which will spawn new sockets for each new connection, so that these can
  9238. be handled in parallel by other threads.
  9239. This returns true if it manages to open the socket successfully.
  9240. @see waitForNextConnection
  9241. */
  9242. bool createListener (const int portNumber);
  9243. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9244. socket.
  9245. The object that gets returned will be owned by the caller.
  9246. This method can only be called after using createListener().
  9247. @see createListener
  9248. */
  9249. StreamingSocket* waitForNextConnection() const;
  9250. juce_UseDebuggingNewOperator
  9251. private:
  9252. String hostName;
  9253. int volatile portNumber, handle;
  9254. bool connected, isListener;
  9255. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9256. StreamingSocket (const StreamingSocket&);
  9257. const StreamingSocket& operator= (const StreamingSocket&);
  9258. };
  9259. /**
  9260. A wrapper for a datagram (UDP) socket.
  9261. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9262. sockets, you could also try the InterprocessConnection class.
  9263. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9264. */
  9265. class JUCE_API DatagramSocket
  9266. {
  9267. public:
  9268. /**
  9269. Creates an (uninitialised) datagram socket.
  9270. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9271. the port number is assigned by the operating system.
  9272. To use the socket for sending, call the connect() method. This will not immediately
  9273. make a connection, but will save the destination you've provided. After this, you can
  9274. call read() or write().
  9275. To wait for other sockets to connect to this one, call waitForNextConnection().
  9276. */
  9277. DatagramSocket (const int localPortNumber);
  9278. /** Destructor. */
  9279. ~DatagramSocket();
  9280. /** Binds the socket to the specified local port.
  9281. @returns true on success; false may indicate that another socket is already bound
  9282. on the same port
  9283. */
  9284. bool bindToPort (const int localPortNumber);
  9285. /** Tries to connect the socket to hostname:port.
  9286. If timeOutMillisecs is 0, then this method will block until the operating system
  9287. rejects the connection (which could take a long time).
  9288. @returns true if it succeeds.
  9289. @see isConnected
  9290. */
  9291. bool connect (const String& remoteHostname,
  9292. const int remotePortNumber,
  9293. const int timeOutMillisecs = 3000);
  9294. /** True if the socket is currently connected. */
  9295. bool isConnected() const throw() { return connected; }
  9296. /** Closes the connection. */
  9297. void close();
  9298. /** Returns the name of the currently connected host. */
  9299. const String& getHostName() const throw() { return hostName; }
  9300. /** Returns the port number that's currently open. */
  9301. int getPort() const throw() { return portNumber; }
  9302. /** True if the socket is connected to this machine rather than over the network. */
  9303. bool isLocal() const throw();
  9304. /** Waits until the socket is ready for reading or writing.
  9305. If readyForReading is true, it will wait until the socket is ready for
  9306. reading; if false, it will wait until it's ready for writing.
  9307. If the timeout is < 0, it will wait forever, or else will give up after
  9308. the specified time.
  9309. If the socket is ready on return, this returns 1. If it times-out before
  9310. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9311. */
  9312. int waitUntilReady (const bool readyForReading,
  9313. const int timeoutMsecs) const;
  9314. /** Reads bytes from the socket (blocking).
  9315. Note that this method will block unless you have checked the socket is ready
  9316. for reading before calling it (see the waitUntilReady() method).
  9317. @returns the number of bytes read, or -1 if there was an error.
  9318. */
  9319. int read (void* destBuffer, const int maxBytesToRead);
  9320. /** Writes bytes to the socket from a buffer.
  9321. Note that this method will block unless you have checked the socket is ready
  9322. for writing before calling it (see the waitUntilReady() method).
  9323. @returns the number of bytes written, or -1 if there was an error.
  9324. */
  9325. int write (const void* sourceBuffer, const int numBytesToWrite);
  9326. /** This waits for incoming data to be sent, and returns a socket that can be used
  9327. to read it.
  9328. The object that gets returned is owned by the caller, and can't be used for
  9329. sending, but can be used to read the data.
  9330. */
  9331. DatagramSocket* waitForNextConnection() const;
  9332. juce_UseDebuggingNewOperator
  9333. private:
  9334. String hostName;
  9335. int volatile portNumber, handle;
  9336. bool connected;
  9337. void* serverAddress;
  9338. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9339. DatagramSocket (const DatagramSocket&);
  9340. const DatagramSocket& operator= (const DatagramSocket&);
  9341. };
  9342. #endif // __JUCE_SOCKET_JUCEHEADER__
  9343. /********* End of inlined file: juce_Socket.h *********/
  9344. #endif
  9345. #ifndef __JUCE_URL_JUCEHEADER__
  9346. /********* Start of inlined file: juce_URL.h *********/
  9347. #ifndef __JUCE_URL_JUCEHEADER__
  9348. #define __JUCE_URL_JUCEHEADER__
  9349. /**
  9350. Represents a URL and has a bunch of useful functions to manipulate it.
  9351. This class can be used to launch URLs in browsers, and also to create
  9352. InputStreams that can read from remote http or ftp sources.
  9353. */
  9354. class JUCE_API URL
  9355. {
  9356. public:
  9357. /** Creates an empty URL. */
  9358. URL() throw();
  9359. /** Creates a URL from a string. */
  9360. URL (const String& url);
  9361. /** Creates a copy of another URL. */
  9362. URL (const URL& other);
  9363. /** Destructor. */
  9364. ~URL() throw();
  9365. /** Copies this URL from another one. */
  9366. const URL& operator= (const URL& other);
  9367. /** Returns a string version of the URL.
  9368. If includeGetParameters is true and any parameters have been set with the
  9369. withParameter() method, then the string will have these appended on the
  9370. end and url-encoded.
  9371. */
  9372. const String toString (const bool includeGetParameters) const;
  9373. /** True if it seems to be valid. */
  9374. bool isWellFormed() const;
  9375. /** Returns a copy of this URL, with a GET parameter added to the end.
  9376. Any control characters in the value will be encoded.
  9377. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  9378. would produce a new url whose toString(true) method would return
  9379. "www.fish.com?amount=some+fish".
  9380. */
  9381. const URL withParameter (const String& parameterName,
  9382. const String& parameterValue) const;
  9383. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  9384. When performing a POST where one of your parameters is a binary file, this
  9385. lets you specify the file.
  9386. Note that the filename is stored, but the file itself won't actually be read
  9387. until this URL is later used to create a network input stream.
  9388. */
  9389. const URL withFileToUpload (const String& parameterName,
  9390. const File& fileToUpload,
  9391. const String& mimeType) const;
  9392. /** Returns a set of all the parameters encoded into the url.
  9393. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  9394. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  9395. The values returned will have been cleaned up to remove any escape characters.
  9396. @see getNamedParameter, withParameter
  9397. */
  9398. const StringPairArray& getParameters() const throw();
  9399. /** Returns the set of files that should be uploaded as part of a POST operation.
  9400. This is the set of files that were added to the URL with the withFileToUpload()
  9401. method.
  9402. */
  9403. const StringPairArray& getFilesToUpload() const throw();
  9404. /** Returns the set of mime types associated with each of the upload files.
  9405. */
  9406. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  9407. /** Returns a copy of this URL, with a block of data to send as the POST data.
  9408. If you're setting the POST data, be careful not to have any parameters set
  9409. as well, otherwise it'll all get thrown in together, and might not have the
  9410. desired effect.
  9411. If the URL already contains some POST data, this will replace it, rather
  9412. than being appended to it.
  9413. This data will only be used if you specify a post operation when you call
  9414. createInputStream().
  9415. */
  9416. const URL withPOSTData (const String& postData) const;
  9417. /** Returns the data that was set using withPOSTData().
  9418. */
  9419. const String getPostData() const throw() { return postData; }
  9420. /** Tries to launch the system's default browser to open the URL.
  9421. Returns true if this seems to have worked.
  9422. */
  9423. bool launchInDefaultBrowser() const;
  9424. /** Takes a guess as to whether a string might be a valid website address.
  9425. This isn't foolproof!
  9426. */
  9427. static bool isProbablyAWebsiteURL (const String& possibleURL);
  9428. /** Takes a guess as to whether a string might be a valid email address.
  9429. This isn't foolproof!
  9430. */
  9431. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  9432. /** This callback function can be used by the createInputStream() method.
  9433. It allows your app to receive progress updates during a lengthy POST operation. If you
  9434. want to continue the operation, this should return true, or false to abort.
  9435. */
  9436. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  9437. /** Attempts to open a stream that can read from this URL.
  9438. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  9439. the paramters, otherwise it'll encode them into the
  9440. URL and do a 'GET'.
  9441. @param progressCallback if this is non-zero, it lets you supply a callback function
  9442. to keep track of the operation's progress. This can be useful
  9443. for lengthy POST operations, so that you can provide user feedback.
  9444. @param progressCallbackContext if a callback is specified, this value will be passed to
  9445. the function
  9446. @param extraHeaders if not empty, this string is appended onto the headers that
  9447. are used for the request. It must therefore be a valid set of HTML
  9448. header directives, separated by newlines.
  9449. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  9450. a negative number, it will be infinite. Otherwise it specifies a
  9451. time in milliseconds.
  9452. */
  9453. InputStream* createInputStream (const bool usePostCommand,
  9454. OpenStreamProgressCallback* const progressCallback = 0,
  9455. void* const progressCallbackContext = 0,
  9456. const String& extraHeaders = String::empty,
  9457. const int connectionTimeOutMs = 0) const;
  9458. /** Tries to download the entire contents of this URL into a binary data block.
  9459. If it succeeds, this will return true and append the data it read onto the end
  9460. of the memory block.
  9461. @param destData the memory block to append the new data to
  9462. @param usePostCommand whether to use a POST command to get the data (uses
  9463. a GET command if this is false)
  9464. @see readEntireTextStream, readEntireXmlStream
  9465. */
  9466. bool readEntireBinaryStream (MemoryBlock& destData,
  9467. const bool usePostCommand = false) const;
  9468. /** Tries to download the entire contents of this URL as a string.
  9469. If it fails, this will return an empty string, otherwise it will return the
  9470. contents of the downloaded file. If you need to distinguish between a read
  9471. operation that fails and one that returns an empty string, you'll need to use
  9472. a different method, such as readEntireBinaryStream().
  9473. @param usePostCommand whether to use a POST command to get the data (uses
  9474. a GET command if this is false)
  9475. @see readEntireBinaryStream, readEntireXmlStream
  9476. */
  9477. const String readEntireTextStream (const bool usePostCommand = false) const;
  9478. /** Tries to download the entire contents of this URL and parse it as XML.
  9479. If it fails, or if the text that it reads can't be parsed as XML, this will
  9480. return 0.
  9481. When it returns a valid XmlElement object, the caller is responsibile for deleting
  9482. this object when no longer needed.
  9483. @param usePostCommand whether to use a POST command to get the data (uses
  9484. a GET command if this is false)
  9485. @see readEntireBinaryStream, readEntireTextStream
  9486. */
  9487. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  9488. /** Adds escape sequences to a string to encode any characters that aren't
  9489. legal in a URL.
  9490. E.g. any spaces will be replaced with "%20".
  9491. This is the opposite of removeEscapeChars().
  9492. If isParameter is true, it means that the string is going to be used
  9493. as a parameter, so it also encodes '$' and ',' (which would otherwise
  9494. be legal in a URL.
  9495. @see removeEscapeChars
  9496. */
  9497. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  9498. const bool isParameter);
  9499. /** Replaces any escape character sequences in a string with their original
  9500. character codes.
  9501. E.g. any instances of "%20" will be replaced by a space.
  9502. This is the opposite of addEscapeChars().
  9503. @see addEscapeChars
  9504. */
  9505. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  9506. juce_UseDebuggingNewOperator
  9507. private:
  9508. String url, postData;
  9509. StringPairArray parameters, filesToUpload, mimeTypes;
  9510. };
  9511. #endif // __JUCE_URL_JUCEHEADER__
  9512. /********* End of inlined file: juce_URL.h *********/
  9513. #endif
  9514. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9515. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9516. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9517. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9518. /** Writes data to an internal memory buffer, which grows as required.
  9519. The data that was written into the stream can then be accessed later as
  9520. a contiguous block of memory.
  9521. */
  9522. class JUCE_API MemoryOutputStream : public OutputStream
  9523. {
  9524. public:
  9525. /** Creates a memory stream ready for writing into.
  9526. @param initialSize the intial amount of space to allocate for writing into
  9527. @param granularity the increments by which the internal storage will be increased
  9528. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9529. place that the data gets stored. If it's zero, the stream
  9530. will allocate its own storage internally, which you can
  9531. access using getData() and getDataSize()
  9532. */
  9533. MemoryOutputStream (const int initialSize = 256,
  9534. const int granularity = 256,
  9535. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9536. /** Destructor.
  9537. This will free any data that was written to it.
  9538. */
  9539. ~MemoryOutputStream() throw();
  9540. /** Returns a pointer to the data that has been written to the stream.
  9541. @see getDataSize
  9542. */
  9543. const char* getData() throw();
  9544. /** Returns the number of bytes of data that have been written to the stream.
  9545. @see getData
  9546. */
  9547. int getDataSize() const throw();
  9548. /** Resets the stream, clearing any data that has been written to it so far. */
  9549. void reset() throw();
  9550. void flush();
  9551. bool write (const void* buffer, int howMany);
  9552. int64 getPosition();
  9553. bool setPosition (int64 newPosition);
  9554. juce_UseDebuggingNewOperator
  9555. private:
  9556. MemoryBlock* data;
  9557. int position, size, blockSize;
  9558. bool ownsMemoryBlock;
  9559. };
  9560. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9561. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9562. #endif
  9563. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9564. /********* Start of inlined file: juce_SubregionStream.h *********/
  9565. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9566. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9567. /** Wraps another input stream, and reads from a specific part of it.
  9568. This lets you take a subsection of a stream and present it as an entire
  9569. stream in its own right.
  9570. */
  9571. class JUCE_API SubregionStream : public InputStream
  9572. {
  9573. public:
  9574. /** Creates a SubregionStream from an input source.
  9575. @param sourceStream the source stream to read from
  9576. @param startPositionInSourceStream this is the position in the source stream that
  9577. corresponds to position 0 in this stream
  9578. @param lengthOfSourceStream this specifies the maximum number of bytes
  9579. from the source stream that will be passed through
  9580. by this stream. When the position of this stream
  9581. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9582. If the length passed in here is greater than the length
  9583. of the source stream (as returned by getTotalLength()),
  9584. then the smaller value will be used.
  9585. Passing a negative value for this parameter means it
  9586. will keep reading until the source's end-of-stream.
  9587. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9588. deleted by this object when it is itself deleted.
  9589. */
  9590. SubregionStream (InputStream* const sourceStream,
  9591. const int64 startPositionInSourceStream,
  9592. const int64 lengthOfSourceStream,
  9593. const bool deleteSourceWhenDestroyed) throw();
  9594. /** Destructor.
  9595. This may also delete the source stream, if that option was chosen when the
  9596. buffered stream was created.
  9597. */
  9598. ~SubregionStream() throw();
  9599. int64 getTotalLength();
  9600. int64 getPosition();
  9601. bool setPosition (int64 newPosition);
  9602. int read (void* destBuffer, int maxBytesToRead);
  9603. bool isExhausted();
  9604. juce_UseDebuggingNewOperator
  9605. private:
  9606. InputStream* const source;
  9607. const bool deleteSourceWhenDestroyed;
  9608. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9609. SubregionStream (const SubregionStream&);
  9610. const SubregionStream& operator= (const SubregionStream&);
  9611. };
  9612. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9613. /********* End of inlined file: juce_SubregionStream.h *********/
  9614. #endif
  9615. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9616. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9617. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9618. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9619. /** Wraps another input stream, and reads from it using an intermediate buffer
  9620. If you're using an input stream such as a file input stream, and making lots of
  9621. small read accesses to it, it's probably sensible to wrap it in one of these,
  9622. so that the source stream gets accessed in larger chunk sizes, meaning less
  9623. work for the underlying stream.
  9624. */
  9625. class JUCE_API BufferedInputStream : public InputStream
  9626. {
  9627. public:
  9628. /** Creates a BufferedInputStream from an input source.
  9629. @param sourceStream the source stream to read from
  9630. @param bufferSize the size of reservoir to use to buffer the source
  9631. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9632. deleted by this object when it is itself deleted.
  9633. */
  9634. BufferedInputStream (InputStream* const sourceStream,
  9635. const int bufferSize,
  9636. const bool deleteSourceWhenDestroyed) throw();
  9637. /** Destructor.
  9638. This may also delete the source stream, if that option was chosen when the
  9639. buffered stream was created.
  9640. */
  9641. ~BufferedInputStream() throw();
  9642. int64 getTotalLength();
  9643. int64 getPosition();
  9644. bool setPosition (int64 newPosition);
  9645. int read (void* destBuffer, int maxBytesToRead);
  9646. const String readString();
  9647. bool isExhausted();
  9648. juce_UseDebuggingNewOperator
  9649. private:
  9650. InputStream* const source;
  9651. const bool deleteSourceWhenDestroyed;
  9652. int bufferSize;
  9653. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9654. char* buffer;
  9655. void ensureBuffered();
  9656. BufferedInputStream (const BufferedInputStream&);
  9657. const BufferedInputStream& operator= (const BufferedInputStream&);
  9658. };
  9659. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9660. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9661. #endif
  9662. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9663. /********* Start of inlined file: juce_FileInputSource.h *********/
  9664. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9665. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9666. /********* Start of inlined file: juce_InputSource.h *********/
  9667. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9668. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9669. /**
  9670. A lightweight object that can create a stream to read some kind of resource.
  9671. This may be used to refer to a file, or some other kind of source, allowing a
  9672. caller to create an input stream that can read from it when required.
  9673. @see FileInputSource
  9674. */
  9675. class JUCE_API InputSource
  9676. {
  9677. public:
  9678. InputSource() throw() {}
  9679. /** Destructor. */
  9680. virtual ~InputSource() {}
  9681. /** Returns a new InputStream to read this item.
  9682. @returns an inputstream that the caller will delete, or 0 if
  9683. the filename isn't found.
  9684. */
  9685. virtual InputStream* createInputStream() = 0;
  9686. /** Returns a new InputStream to read an item, relative.
  9687. @param relatedItemPath the relative pathname of the resource that is required
  9688. @returns an inputstream that the caller will delete, or 0 if
  9689. the item isn't found.
  9690. */
  9691. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9692. /** Returns a hash code that uniquely represents this item.
  9693. */
  9694. virtual int64 hashCode() const = 0;
  9695. juce_UseDebuggingNewOperator
  9696. };
  9697. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9698. /********* End of inlined file: juce_InputSource.h *********/
  9699. /**
  9700. A type of InputSource that represents a normal file.
  9701. @see InputSource
  9702. */
  9703. class JUCE_API FileInputSource : public InputSource
  9704. {
  9705. public:
  9706. FileInputSource (const File& file) throw();
  9707. ~FileInputSource();
  9708. InputStream* createInputStream();
  9709. InputStream* createInputStreamFor (const String& relatedItemPath);
  9710. int64 hashCode() const;
  9711. juce_UseDebuggingNewOperator
  9712. private:
  9713. const File file;
  9714. FileInputSource (const FileInputSource&);
  9715. const FileInputSource& operator= (const FileInputSource&);
  9716. };
  9717. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9718. /********* End of inlined file: juce_FileInputSource.h *********/
  9719. #endif
  9720. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9721. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9722. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9723. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9724. /**
  9725. A stream which uses zlib to compress the data written into it.
  9726. @see GZIPDecompressorInputStream
  9727. */
  9728. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9729. {
  9730. public:
  9731. /** Creates a compression stream.
  9732. @param destStream the stream into which the compressed data should
  9733. be written
  9734. @param compressionLevel how much to compress the data, between 1 and 9, where
  9735. 1 is the fastest/lowest compression, and 9 is the
  9736. slowest/highest compression. Any value outside this range
  9737. indicates that a default compression level should be used.
  9738. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9739. this stream is destroyed
  9740. @param noWrap this is used internally by the ZipFile class
  9741. and should be ignored by user applications
  9742. */
  9743. GZIPCompressorOutputStream (OutputStream* const destStream,
  9744. int compressionLevel = 0,
  9745. const bool deleteDestStreamWhenDestroyed = false,
  9746. const bool noWrap = false);
  9747. /** Destructor. */
  9748. ~GZIPCompressorOutputStream();
  9749. void flush();
  9750. int64 getPosition();
  9751. bool setPosition (int64 newPosition);
  9752. bool write (const void* destBuffer, int howMany);
  9753. juce_UseDebuggingNewOperator
  9754. private:
  9755. OutputStream* const destStream;
  9756. const bool deleteDestStream;
  9757. uint8* buffer;
  9758. void* helper;
  9759. bool doNextBlock();
  9760. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9761. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9762. };
  9763. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9764. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9765. #endif
  9766. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9767. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9768. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9769. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9770. /**
  9771. This stream will decompress a source-stream using zlib.
  9772. Tip: if you're reading lots of small items from one of these streams, you
  9773. can increase the performance enormously by passing it through a
  9774. BufferedInputStream, so that it has to read larger blocks less often.
  9775. @see GZIPCompressorOutputStream
  9776. */
  9777. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9778. {
  9779. public:
  9780. /** Creates a decompressor stream.
  9781. @param sourceStream the stream to read from
  9782. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9783. when this object is destroyed
  9784. @param noWrap this is used internally by the ZipFile class
  9785. and should be ignored by user applications
  9786. @param uncompressedStreamLength if the creator knows the length that the
  9787. uncompressed stream will be, then it can supply this
  9788. value, which will be returned by getTotalLength()
  9789. */
  9790. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9791. const bool deleteSourceWhenDestroyed,
  9792. const bool noWrap = false,
  9793. const int64 uncompressedStreamLength = -1);
  9794. /** Destructor. */
  9795. ~GZIPDecompressorInputStream();
  9796. int64 getPosition();
  9797. bool setPosition (int64 pos);
  9798. int64 getTotalLength();
  9799. bool isExhausted();
  9800. int read (void* destBuffer, int maxBytesToRead);
  9801. juce_UseDebuggingNewOperator
  9802. private:
  9803. InputStream* const sourceStream;
  9804. const int64 uncompressedStreamLength;
  9805. const bool deleteSourceWhenDestroyed, noWrap;
  9806. bool isEof;
  9807. int activeBufferSize;
  9808. int64 originalSourcePos, currentPos;
  9809. uint8* buffer;
  9810. void* helper;
  9811. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9812. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9813. };
  9814. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9815. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9816. #endif
  9817. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9818. #endif
  9819. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9820. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9821. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9822. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9823. /**
  9824. Allows a block of data and to be accessed as a stream.
  9825. This can either be used to refer to a shared block of memory, or can make its
  9826. own internal copy of the data when the MemoryInputStream is created.
  9827. */
  9828. class JUCE_API MemoryInputStream : public InputStream
  9829. {
  9830. public:
  9831. /** Creates a MemoryInputStream.
  9832. @param sourceData the block of data to use as the stream's source
  9833. @param sourceDataSize the number of bytes in the source data block
  9834. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9835. the source data, so this data shouldn't be changed
  9836. for the lifetime of the stream; if this parameter is
  9837. true, the stream will make its own copy of the
  9838. data and use that.
  9839. */
  9840. MemoryInputStream (const void* const sourceData,
  9841. const int sourceDataSize,
  9842. const bool keepInternalCopyOfData) throw();
  9843. /** Destructor. */
  9844. ~MemoryInputStream() throw();
  9845. int64 getPosition();
  9846. bool setPosition (int64 pos);
  9847. int64 getTotalLength();
  9848. bool isExhausted();
  9849. int read (void* destBuffer, int maxBytesToRead);
  9850. juce_UseDebuggingNewOperator
  9851. private:
  9852. const char* data;
  9853. int dataSize, position;
  9854. MemoryBlock internalCopy;
  9855. };
  9856. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9857. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9858. #endif
  9859. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9860. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9861. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9862. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9863. /** A timer for measuring performance of code and dumping the results to a file.
  9864. e.g. @code
  9865. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9866. for (;;)
  9867. {
  9868. pc.start();
  9869. doSomethingFishy();
  9870. pc.stop();
  9871. }
  9872. @endcode
  9873. In this example, the time of each period between calling start/stop will be
  9874. measured and averaged over 50 runs, and the results printed to a file
  9875. every 50 times round the loop.
  9876. */
  9877. class JUCE_API PerformanceCounter
  9878. {
  9879. public:
  9880. /** Creates a PerformanceCounter object.
  9881. @param counterName the name used when printing out the statistics
  9882. @param runsPerPrintout the number of start/stop iterations before calling
  9883. printStatistics()
  9884. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9885. the results are just written to the debugger output
  9886. */
  9887. PerformanceCounter (const String& counterName,
  9888. int runsPerPrintout = 100,
  9889. const File& loggingFile = File::nonexistent);
  9890. /** Destructor. */
  9891. ~PerformanceCounter();
  9892. /** Starts timing.
  9893. @see stop
  9894. */
  9895. void start();
  9896. /** Stops timing and prints out the results.
  9897. The number of iterations before doing a printout of the
  9898. results is set in the constructor.
  9899. @see start
  9900. */
  9901. void stop();
  9902. /** Dumps the current metrics to the debugger output and to a file.
  9903. As well as using Logger::outputDebugString to print the results,
  9904. this will write then to the file specified in the constructor (if
  9905. this was valid).
  9906. */
  9907. void printStatistics();
  9908. juce_UseDebuggingNewOperator
  9909. private:
  9910. String name;
  9911. int numRuns, runsPerPrint;
  9912. double totalTime;
  9913. int64 started;
  9914. File outputFile;
  9915. };
  9916. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9917. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9918. #endif
  9919. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9920. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9921. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9922. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9923. /**
  9924. A collection of miscellaneous platform-specific utilities.
  9925. */
  9926. class JUCE_API PlatformUtilities
  9927. {
  9928. public:
  9929. /** Plays the operating system's default alert 'beep' sound. */
  9930. static void beep();
  9931. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9932. const String& emailSubject,
  9933. const String& bodyText,
  9934. const StringArray& filesToAttach);
  9935. #if JUCE_MAC || DOXYGEN
  9936. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9937. static const String cfStringToJuceString (CFStringRef cfString);
  9938. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9939. static CFStringRef juceStringToCFString (const String& s);
  9940. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9941. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9942. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9943. static const String makePathFromFSRef (FSRef* file);
  9944. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9945. their precomposed equivalents.
  9946. */
  9947. static const String convertToPrecomposedUnicode (const String& s);
  9948. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9949. static OSType getTypeOfFile (const String& filename);
  9950. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9951. static bool isBundle (const String& filename);
  9952. /** MAC ONLY - Adds an item to the dock */
  9953. static void addItemToDock (const File& file);
  9954. #endif
  9955. #if JUCE_WIN32 || DOXYGEN
  9956. // Some registry helper functions:
  9957. /** WIN32 ONLY - Returns a string from the registry.
  9958. The path is a string for the entire path of a value in the registry,
  9959. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9960. */
  9961. static const String getRegistryValue (const String& regValuePath,
  9962. const String& defaultValue = String::empty);
  9963. /** WIN32 ONLY - Sets a registry value as a string.
  9964. This will take care of creating any groups needed to get to the given
  9965. registry value.
  9966. */
  9967. static void setRegistryValue (const String& regValuePath,
  9968. const String& value);
  9969. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9970. static bool registryValueExists (const String& regValuePath);
  9971. /** WIN32 ONLY - Deletes a registry value. */
  9972. static void deleteRegistryValue (const String& regValuePath);
  9973. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9974. static void deleteRegistryKey (const String& regKeyPath);
  9975. /** WIN32 ONLY - Creates a file association in the registry.
  9976. This lets you set the exe that should be launched by a given file extension.
  9977. @param fileExtension the file extension to associate, including the
  9978. initial dot, e.g. ".txt"
  9979. @param symbolicDescription a space-free short token to identify the file type
  9980. @param fullDescription a human-readable description of the file type
  9981. @param targetExecutable the executable that should be launched
  9982. @param iconResourceNumber the icon that gets displayed for the file type will be
  9983. found by looking up this resource number in the
  9984. executable. Pass 0 here to not use an icon
  9985. */
  9986. static void registerFileAssociation (const String& fileExtension,
  9987. const String& symbolicDescription,
  9988. const String& fullDescription,
  9989. const File& targetExecutable,
  9990. int iconResourceNumber);
  9991. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9992. In a normal Juce application this will be set to the module handle
  9993. of the application executable.
  9994. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9995. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9996. to set the correct module handle in your DllMain() function, because
  9997. the win32 system relies on the correct instance handle when opening windows.
  9998. */
  9999. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10000. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10001. @see getCurrentModuleInstanceHandle()
  10002. */
  10003. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10004. /** WIN32 ONLY - Gets the command-line params as a string.
  10005. This is needed to avoid unicode problems with the argc type params.
  10006. */
  10007. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  10008. #endif
  10009. /** Clears the floating point unit's flags.
  10010. Only has an effect under win32, currently.
  10011. */
  10012. static void fpuReset();
  10013. #if JUCE_LINUX || JUCE_WIN32
  10014. /** Loads a dynamically-linked library into the process's address space.
  10015. @param pathOrFilename the platform-dependent name and search path
  10016. @returns a handle which can be used by getProcedureEntryPoint(), or
  10017. zero if it fails.
  10018. @see freeDynamicLibrary, getProcedureEntryPoint
  10019. */
  10020. static void* loadDynamicLibrary (const String& pathOrFilename);
  10021. /** Frees a dynamically-linked library.
  10022. @param libraryHandle a handle created by loadDynamicLibrary
  10023. @see loadDynamicLibrary, getProcedureEntryPoint
  10024. */
  10025. static void freeDynamicLibrary (void* libraryHandle);
  10026. /** Finds a procedure call in a dynamically-linked library.
  10027. @param libraryHandle a library handle returned by loadDynamicLibrary
  10028. @param procedureName the name of the procedure call to try to load
  10029. @returns a pointer to the function if found, or 0 if it fails
  10030. @see loadDynamicLibrary
  10031. */
  10032. static void* getProcedureEntryPoint (void* libraryHandle,
  10033. const String& procedureName);
  10034. #endif
  10035. #if JUCE_LINUX || DOXYGEN
  10036. #endif
  10037. };
  10038. #if JUCE_MAC
  10039. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10040. using RAII.
  10041. */
  10042. class ScopedAutoReleasePool
  10043. {
  10044. public:
  10045. ScopedAutoReleasePool();
  10046. ~ScopedAutoReleasePool();
  10047. private:
  10048. void* pool;
  10049. };
  10050. /**
  10051. A wrapper class for picking up events from an Apple IR remote control device.
  10052. To use it, just create a subclass of this class, implementing the buttonPressed()
  10053. callback, then call start() and stop() to start or stop receiving events.
  10054. */
  10055. class JUCE_API AppleRemoteDevice
  10056. {
  10057. public:
  10058. AppleRemoteDevice();
  10059. virtual ~AppleRemoteDevice();
  10060. /** The set of buttons that may be pressed.
  10061. @see buttonPressed
  10062. */
  10063. enum ButtonType
  10064. {
  10065. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10066. playButton, /**< The play button. */
  10067. plusButton, /**< The plus or volume-up button. */
  10068. minusButton, /**< The minus or volume-down button. */
  10069. rightButton, /**< The right button (if it's held for a short time). */
  10070. leftButton, /**< The left button (if it's held for a short time). */
  10071. rightButton_Long, /**< The right button (if it's held for a long time). */
  10072. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10073. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10074. playButtonSleepMode,
  10075. switched
  10076. };
  10077. /** Override this method to receive the callback about a button press.
  10078. The callback will happen on the application's message thread.
  10079. Some buttons trigger matching up and down events, in which the isDown parameter
  10080. will be true and then false. Others only send a single event when the
  10081. button is pressed.
  10082. */
  10083. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10084. /** Starts the device running and responding to events.
  10085. Returns true if it managed to open the device.
  10086. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10087. and will not be available to any other part of the system. If
  10088. false, it will be shared with other apps.
  10089. @see stop
  10090. */
  10091. bool start (const bool inExclusiveMode) throw();
  10092. /** Stops the device running.
  10093. @see start
  10094. */
  10095. void stop() throw();
  10096. /** Returns true if the device has been started successfully.
  10097. */
  10098. bool isActive() const throw();
  10099. /** Returns the ID number of the remote, if it has sent one.
  10100. */
  10101. int getRemoteId() const throw() { return remoteId; }
  10102. juce_UseDebuggingNewOperator
  10103. /** @internal */
  10104. void handleCallbackInternal();
  10105. private:
  10106. void* device;
  10107. void* queue;
  10108. int remoteId;
  10109. bool open (const bool openInExclusiveMode) throw();
  10110. };
  10111. #endif
  10112. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10113. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10114. #endif
  10115. #ifndef __JUCE_UUID_JUCEHEADER__
  10116. /********* Start of inlined file: juce_Uuid.h *********/
  10117. #ifndef __JUCE_UUID_JUCEHEADER__
  10118. #define __JUCE_UUID_JUCEHEADER__
  10119. /**
  10120. A universally unique 128-bit identifier.
  10121. This class generates very random unique numbers based on the system time
  10122. and MAC addresses if any are available. It's extremely unlikely that two identical
  10123. UUIDs would ever be created by chance.
  10124. The class includes methods for saving the ID as a string or as raw binary data.
  10125. */
  10126. class JUCE_API Uuid
  10127. {
  10128. public:
  10129. /** Creates a new unique ID. */
  10130. Uuid();
  10131. /** Destructor. */
  10132. ~Uuid() throw();
  10133. /** Creates a copy of another UUID. */
  10134. Uuid (const Uuid& other);
  10135. /** Copies another UUID. */
  10136. Uuid& operator= (const Uuid& other);
  10137. /** Returns true if the ID is zero. */
  10138. bool isNull() const throw();
  10139. /** Compares two UUIDs. */
  10140. bool operator== (const Uuid& other) const;
  10141. /** Compares two UUIDs. */
  10142. bool operator!= (const Uuid& other) const;
  10143. /** Returns a stringified version of this UUID.
  10144. A Uuid object can later be reconstructed from this string using operator= or
  10145. the constructor that takes a string parameter.
  10146. @returns a 32 character hex string.
  10147. */
  10148. const String toString() const;
  10149. /** Creates an ID from an encoded string version.
  10150. @see toString
  10151. */
  10152. Uuid (const String& uuidString);
  10153. /** Copies from a stringified UUID.
  10154. The string passed in should be one that was created with the toString() method.
  10155. */
  10156. Uuid& operator= (const String& uuidString);
  10157. /** Returns a pointer to the internal binary representation of the ID.
  10158. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10159. the constructor or operator= method that takes an array of uint8s.
  10160. */
  10161. const uint8* getRawData() const throw() { return value.asBytes; }
  10162. /** Creates a UUID from a 16-byte array.
  10163. @see getRawData
  10164. */
  10165. Uuid (const uint8* const rawData);
  10166. /** Sets this UUID from 16-bytes of raw data. */
  10167. Uuid& operator= (const uint8* const rawData);
  10168. juce_UseDebuggingNewOperator
  10169. private:
  10170. union
  10171. {
  10172. uint8 asBytes [16];
  10173. int asInt[4];
  10174. int64 asInt64[2];
  10175. } value;
  10176. };
  10177. #endif // __JUCE_UUID_JUCEHEADER__
  10178. /********* End of inlined file: juce_Uuid.h *********/
  10179. #endif
  10180. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10181. /********* Start of inlined file: juce_ZipFile.h *********/
  10182. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10183. #define __JUCE_ZIPFILE_JUCEHEADER__
  10184. /**
  10185. Decodes a ZIP file from a stream.
  10186. This can enumerate the items in a ZIP file and can create suitable stream objects
  10187. to read each one.
  10188. */
  10189. class JUCE_API ZipFile
  10190. {
  10191. public:
  10192. /** Creates a ZipFile for a given stream.
  10193. @param inputStream the stream to read from
  10194. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10195. will be deleted when this ZipFile object is deleted
  10196. */
  10197. ZipFile (InputStream* const inputStream,
  10198. const bool deleteStreamWhenDestroyed) throw();
  10199. /** Creates a ZipFile based for a file. */
  10200. ZipFile (const File& file);
  10201. /** Creates a ZipFile for an input source.
  10202. The inputSource object will be owned by the zip file, which will delete
  10203. it later when not needed.
  10204. */
  10205. ZipFile (InputSource* const inputSource);
  10206. /** Destructor. */
  10207. ~ZipFile() throw();
  10208. /**
  10209. Contains information about one of the entries in a ZipFile.
  10210. @see ZipFile::getEntry
  10211. */
  10212. struct ZipEntry
  10213. {
  10214. /** The name of the file, which may also include a partial pathname. */
  10215. String filename;
  10216. /** The file's original size. */
  10217. unsigned int uncompressedSize;
  10218. /** The last time the file was modified. */
  10219. Time fileTime;
  10220. };
  10221. /** Returns the number of items in the zip file. */
  10222. int getNumEntries() const throw();
  10223. /** Returns a structure that describes one of the entries in the zip file.
  10224. This may return zero if the index is out of range.
  10225. @see ZipFile::ZipEntry
  10226. */
  10227. const ZipEntry* getEntry (const int index) const throw();
  10228. /** Returns the index of the first entry with a given filename.
  10229. This uses a case-sensitive comparison to look for a filename in the
  10230. list of entries. It might return -1 if no match is found.
  10231. @see ZipFile::ZipEntry
  10232. */
  10233. int getIndexOfFileName (const String& fileName) const throw();
  10234. /** Returns a structure that describes one of the entries in the zip file.
  10235. This uses a case-sensitive comparison to look for a filename in the
  10236. list of entries. It might return 0 if no match is found.
  10237. @see ZipFile::ZipEntry
  10238. */
  10239. const ZipEntry* getEntry (const String& fileName) const throw();
  10240. /** Sorts the list of entries, based on the filename.
  10241. */
  10242. void sortEntriesByFilename();
  10243. /** Creates a stream that can read from one of the zip file's entries.
  10244. The stream that is returned must be deleted by the caller (and
  10245. zero might be returned if a stream can't be opened for some reason).
  10246. The stream must not be used after the ZipFile object that created
  10247. has been deleted.
  10248. */
  10249. InputStream* createStreamForEntry (const int index);
  10250. /** Uncompresses all of the files in the zip file.
  10251. This will expand all the entires into a target directory. The relative
  10252. paths of the entries are used.
  10253. @param targetDirectory the root folder to uncompress to
  10254. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10255. */
  10256. void uncompressTo (const File& targetDirectory,
  10257. const bool shouldOverwriteFiles = true);
  10258. juce_UseDebuggingNewOperator
  10259. private:
  10260. VoidArray entries;
  10261. friend class ZipInputStream;
  10262. CriticalSection lock;
  10263. InputStream* inputStream;
  10264. InputSource* inputSource;
  10265. bool deleteStreamWhenDestroyed;
  10266. int numEntries, centralRecStart;
  10267. #ifdef JUCE_DEBUG
  10268. int numOpenStreams;
  10269. #endif
  10270. void init();
  10271. int findEndOfZipEntryTable (InputStream* in);
  10272. ZipFile (const ZipFile&);
  10273. const ZipFile& operator= (const ZipFile&);
  10274. };
  10275. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10276. /********* End of inlined file: juce_ZipFile.h *********/
  10277. #endif
  10278. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10279. #endif
  10280. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10281. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10282. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10283. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10284. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10285. string into a localised version using the LocalisedStrings class.
  10286. @see LocalisedStrings
  10287. */
  10288. #define TRANS(stringLiteral) \
  10289. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10290. /**
  10291. Used to convert strings to localised foreign-language versions.
  10292. This is basically a look-up table of strings and their translated equivalents.
  10293. It can be loaded from a text file, so that you can supply a set of localised
  10294. versions of strings that you use in your app.
  10295. To use it in your code, simply call the translate() method on each string that
  10296. might have foreign versions, and if none is found, the method will just return
  10297. the original string.
  10298. The translation file should start with some lines specifying a description of
  10299. the language it contains, and also a list of ISO country codes where it might
  10300. be appropriate to use the file. After that, each line of the file should contain
  10301. a pair of quoted strings with an '=' sign.
  10302. E.g. for a french translation, the file might be:
  10303. @code
  10304. language: French
  10305. countries: fr be mc ch lu
  10306. "hello" = "bonjour"
  10307. "goodbye" = "au revoir"
  10308. @endcode
  10309. If the strings need to contain a quote character, they can use '\"' instead, and
  10310. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10311. (you can use this to add comments).
  10312. Note that this is a singleton class, so don't create or destroy the object directly.
  10313. There's also a TRANS(text) macro defined to make it easy to use the this.
  10314. E.g. @code
  10315. printSomething (TRANS("hello"));
  10316. @endcode
  10317. This macro is used in the Juce classes themselves, so your application has a chance to
  10318. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10319. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10320. code).
  10321. */
  10322. class JUCE_API LocalisedStrings
  10323. {
  10324. public:
  10325. /** Creates a set of translations from the text of a translation file.
  10326. When you create one of these, you can call setCurrentMappings() to make it
  10327. the set of mappings that the system's using.
  10328. */
  10329. LocalisedStrings (const String& fileContents) throw();
  10330. /** Creates a set of translations from a file.
  10331. When you create one of these, you can call setCurrentMappings() to make it
  10332. the set of mappings that the system's using.
  10333. */
  10334. LocalisedStrings (const File& fileToLoad) throw();
  10335. /** Destructor. */
  10336. ~LocalisedStrings() throw();
  10337. /** Selects the current set of mappings to be used by the system.
  10338. The object you pass in will be automatically deleted when no longer needed, so
  10339. don't keep a pointer to it. You can also pass in zero to remove the current
  10340. mappings.
  10341. See also the TRANS() macro, which uses the current set to do its translation.
  10342. @see translateWithCurrentMappings
  10343. */
  10344. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10345. /** Returns the currently selected set of mappings.
  10346. This is the object that was last passed to setCurrentMappings(). It may
  10347. be 0 if none has been created.
  10348. */
  10349. static LocalisedStrings* getCurrentMappings() throw();
  10350. /** Tries to translate a string using the currently selected set of mappings.
  10351. If no mapping has been set, or if the mapping doesn't contain a translation
  10352. for the string, this will just return the original string.
  10353. See also the TRANS() macro, which uses this method to do its translation.
  10354. @see setCurrentMappings, getCurrentMappings
  10355. */
  10356. static const String translateWithCurrentMappings (const String& text) throw();
  10357. /** Tries to translate a string using the currently selected set of mappings.
  10358. If no mapping has been set, or if the mapping doesn't contain a translation
  10359. for the string, this will just return the original string.
  10360. See also the TRANS() macro, which uses this method to do its translation.
  10361. @see setCurrentMappings, getCurrentMappings
  10362. */
  10363. static const String translateWithCurrentMappings (const char* text) throw();
  10364. /** Attempts to look up a string and return its localised version.
  10365. If the string isn't found in the list, the original string will be returned.
  10366. */
  10367. const String translate (const String& text) const throw();
  10368. /** Returns the name of the language specified in the translation file.
  10369. This is specified in the file using a line starting with "language:", e.g.
  10370. @code
  10371. language: german
  10372. @endcode
  10373. */
  10374. const String getLanguageName() const throw() { return languageName; }
  10375. /** Returns the list of suitable country codes listed in the translation file.
  10376. These is specified in the file using a line starting with "countries:", e.g.
  10377. @code
  10378. countries: fr be mc ch lu
  10379. @endcode
  10380. The country codes are supposed to be 2-character ISO complient codes.
  10381. */
  10382. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10383. /** Indicates whether to use a case-insensitive search when looking up a string.
  10384. This defaults to true.
  10385. */
  10386. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  10387. juce_UseDebuggingNewOperator
  10388. private:
  10389. String languageName;
  10390. StringArray countryCodes;
  10391. StringPairArray translations;
  10392. void loadFromText (const String& fileContents) throw();
  10393. };
  10394. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10395. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10396. #endif
  10397. #ifndef __JUCE_STRING_JUCEHEADER__
  10398. #endif
  10399. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10400. #endif
  10401. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10402. #endif
  10403. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10404. /********* Start of inlined file: juce_XmlDocument.h *********/
  10405. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10406. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10407. /**
  10408. Parses a text-based XML document and creates an XmlElement object from it.
  10409. The parser will parse DTDs to load external entities but won't
  10410. check the document for validity against the DTD.
  10411. e.g.
  10412. @code
  10413. XmlDocument myDocument (File ("myfile.xml"));
  10414. XmlElement* mainElement = myDocument.getDocumentElement();
  10415. if (mainElement == 0)
  10416. {
  10417. String error = myDocument.getLastParseError();
  10418. }
  10419. else
  10420. {
  10421. ..use the element
  10422. }
  10423. @endcode
  10424. @see XmlElement
  10425. */
  10426. class JUCE_API XmlDocument
  10427. {
  10428. public:
  10429. /** Creates an XmlDocument from the xml text.
  10430. The text doesn't actually get parsed until the getDocumentElement() method is
  10431. called.
  10432. */
  10433. XmlDocument (const String& documentText) throw();
  10434. /** Creates an XmlDocument from a file.
  10435. The text doesn't actually get parsed until the getDocumentElement() method is
  10436. called.
  10437. */
  10438. XmlDocument (const File& file);
  10439. /** Destructor. */
  10440. ~XmlDocument() throw();
  10441. /** Creates an XmlElement object to represent the main document node.
  10442. This method will do the actual parsing of the text, and if there's a
  10443. parse error, it may returns 0 (and you can find out the error using
  10444. the getLastParseError() method).
  10445. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10446. first section of the file, and will only
  10447. return the outer document element - this
  10448. allows quick checking of large files to
  10449. see if they contain the correct type of
  10450. tag, without having to parse the entire file
  10451. @returns a new XmlElement which the caller will need to delete, or null if
  10452. there was an error.
  10453. @see getLastParseError
  10454. */
  10455. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10456. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10457. @returns the error, or an empty string if there was no error.
  10458. */
  10459. const String& getLastParseError() const throw();
  10460. /** Sets an input source object to use for parsing documents that reference external entities.
  10461. If the document has been created from a file, this probably won't be needed, but
  10462. if you're parsing some text and there might be a DTD that references external
  10463. files, you may need to create a custom input source that can retrieve the
  10464. other files it needs.
  10465. The object that is passed-in will be deleted automatically when no longer needed.
  10466. @see InputSource
  10467. */
  10468. void setInputSource (InputSource* const newSource) throw();
  10469. /** Sets a flag to change the treatment of empty text elements.
  10470. If this is true (the default state), then any text elements that contain only
  10471. whitespace characters will be ingored during parsing. If you need to catch
  10472. whitespace-only text, then you should set this to false before calling the
  10473. getDocumentElement() method.
  10474. */
  10475. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  10476. juce_UseDebuggingNewOperator
  10477. private:
  10478. String originalText;
  10479. const tchar* input;
  10480. bool outOfData, errorOccurred;
  10481. bool identifierLookupTable [128];
  10482. String lastError, dtdText;
  10483. StringArray tokenisedDTD;
  10484. bool needToLoadDTD, ignoreEmptyTextElements;
  10485. InputSource* inputSource;
  10486. void setLastError (const String& desc, const bool carryOn) throw();
  10487. void skipHeader() throw();
  10488. void skipNextWhiteSpace() throw();
  10489. tchar readNextChar() throw();
  10490. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10491. void readChildElements (XmlElement* parent) throw();
  10492. int findNextTokenLength() throw();
  10493. void readQuotedString (String& result) throw();
  10494. void readEntity (String& result) throw();
  10495. const String getFileContents (const String& filename) const;
  10496. const String expandEntity (const String& entity);
  10497. const String expandExternalEntity (const String& entity);
  10498. const String getParameterEntity (const String& entity);
  10499. };
  10500. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10501. /********* End of inlined file: juce_XmlDocument.h *********/
  10502. #endif
  10503. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10504. #endif
  10505. #ifndef __JUCE_THREAD_JUCEHEADER__
  10506. /********* Start of inlined file: juce_Thread.h *********/
  10507. #ifndef __JUCE_THREAD_JUCEHEADER__
  10508. #define __JUCE_THREAD_JUCEHEADER__
  10509. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10510. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10511. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10512. /**
  10513. Allows threads to wait for events triggered by other threads.
  10514. A thread can call wait() on a WaitableObject, and this will suspend the
  10515. calling thread until another thread wakes it up by calling the signal()
  10516. method.
  10517. */
  10518. class JUCE_API WaitableEvent
  10519. {
  10520. public:
  10521. /** Creates a WaitableEvent object. */
  10522. WaitableEvent() throw();
  10523. /** Destructor.
  10524. If other threads are waiting on this object when it gets deleted, this
  10525. can cause nasty errors, so be careful!
  10526. */
  10527. ~WaitableEvent() throw();
  10528. /** Suspends the calling thread until the event has been signalled.
  10529. This will wait until the object's signal() method is called by another thread,
  10530. or until the timeout expires.
  10531. After the event has been signalled, this method will return true and reset
  10532. the event.
  10533. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10534. value will cause it to wait forever.
  10535. @returns true if the object has been signalled, false if the timeout expires first.
  10536. @see signal, reset
  10537. */
  10538. bool wait (const int timeOutMilliseconds = -1) const throw();
  10539. /** Wakes up any threads that are currently waiting on this object.
  10540. If signal() is called when nothing is waiting, the next thread to call wait()
  10541. will return immediately and reset the signal.
  10542. @see wait, reset
  10543. */
  10544. void signal() const throw();
  10545. /** Resets the event to an unsignalled state.
  10546. If it's not already signalled, this does nothing.
  10547. */
  10548. void reset() const throw();
  10549. juce_UseDebuggingNewOperator
  10550. private:
  10551. void* internal;
  10552. WaitableEvent (const WaitableEvent&);
  10553. const WaitableEvent& operator= (const WaitableEvent&);
  10554. };
  10555. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10556. /********* End of inlined file: juce_WaitableEvent.h *********/
  10557. /**
  10558. Encapsulates a thread.
  10559. Subclasses derive from Thread and implement the run() method, in which they
  10560. do their business. The thread can then be started with the startThread() method
  10561. and controlled with various other methods.
  10562. This class also contains some thread-related static methods, such
  10563. as sleep(), yield(), getCurrentThreadId() etc.
  10564. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10565. MessageManagerLock
  10566. */
  10567. class JUCE_API Thread
  10568. {
  10569. public:
  10570. /**
  10571. Creates a thread.
  10572. When first created, the thread is not running. Use the startThread()
  10573. method to start it.
  10574. */
  10575. Thread (const String& threadName);
  10576. /** Destructor.
  10577. Deleting a Thread object that is running will only give the thread a
  10578. brief opportunity to stop itself cleanly, so it's recommended that you
  10579. should always call stopThread() with a decent timeout before deleting,
  10580. to avoid the thread being forcibly killed (which is a Bad Thing).
  10581. */
  10582. virtual ~Thread();
  10583. /** Must be implemented to perform the thread's actual code.
  10584. Remember that the thread must regularly check the threadShouldExit()
  10585. method whilst running, and if this returns true it should return from
  10586. the run() method as soon as possible to avoid being forcibly killed.
  10587. @see threadShouldExit, startThread
  10588. */
  10589. virtual void run() = 0;
  10590. // Thread control functions..
  10591. /** Starts the thread running.
  10592. This will start the thread's run() method.
  10593. (if it's already started, startThread() won't do anything).
  10594. @see stopThread
  10595. */
  10596. void startThread() throw();
  10597. /** Starts the thread with a given priority.
  10598. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10599. If the thread is already running, its priority will be changed.
  10600. @see startThread, setPriority
  10601. */
  10602. void startThread (const int priority) throw();
  10603. /** Attempts to stop the thread running.
  10604. This method will cause the threadShouldExit() method to return true
  10605. and call notify() in case the thread is currently waiting.
  10606. Hopefully the thread will then respond to this by exiting cleanly, and
  10607. the stopThread method will wait for a given time-period for this to
  10608. happen.
  10609. If the thread is stuck and fails to respond after the time-out, it gets
  10610. forcibly killed, which is a very bad thing to happen, as it could still
  10611. be holding locks, etc. which are needed by other parts of your program.
  10612. @param timeOutMilliseconds The number of milliseconds to wait for the
  10613. thread to finish before killing it by force. A negative
  10614. value in here will wait forever.
  10615. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10616. */
  10617. void stopThread (const int timeOutMilliseconds) throw();
  10618. /** Returns true if the thread is currently active */
  10619. bool isThreadRunning() const throw();
  10620. /** Sets a flag to tell the thread it should stop.
  10621. Calling this means that the threadShouldExit() method will then return true.
  10622. The thread should be regularly checking this to see whether it should exit.
  10623. @see threadShouldExit
  10624. @see waitForThreadToExit
  10625. */
  10626. void signalThreadShouldExit() throw();
  10627. /** Checks whether the thread has been told to stop running.
  10628. Threads need to check this regularly, and if it returns true, they should
  10629. return from their run() method at the first possible opportunity.
  10630. @see signalThreadShouldExit
  10631. */
  10632. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10633. /** Waits for the thread to stop.
  10634. This will waits until isThreadRunning() is false or until a timeout expires.
  10635. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10636. is less than zero, it will wait forever.
  10637. @returns true if the thread exits, or false if the timeout expires first.
  10638. */
  10639. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10640. /** Changes the thread's priority.
  10641. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10642. of 5 is normal.
  10643. */
  10644. void setPriority (const int priority) throw();
  10645. /** Changes the priority of the caller thread.
  10646. Similar to setPriority(), but this static method acts on the caller thread.
  10647. @see setPriority
  10648. */
  10649. static void setCurrentThreadPriority (const int priority) throw();
  10650. /** Sets the affinity mask for the thread.
  10651. This will only have an effect next time the thread is started - i.e. if the
  10652. thread is already running when called, it'll have no effect.
  10653. @see setCurrentThreadAffinityMask
  10654. */
  10655. void setAffinityMask (const uint32 affinityMask) throw();
  10656. /** Changes the affinity mask for the caller thread.
  10657. This will change the affinity mask for the thread that calls this static method.
  10658. @see setAffinityMask
  10659. */
  10660. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10661. // this can be called from any thread that needs to pause..
  10662. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10663. /** Yields the calling thread's current time-slot. */
  10664. static void JUCE_CALLTYPE yield() throw();
  10665. /** Makes the thread wait for a notification.
  10666. This puts the thread to sleep until either the timeout period expires, or
  10667. another thread calls the notify() method to wake it up.
  10668. @returns true if the event has been signalled, false if the timeout expires.
  10669. */
  10670. bool wait (const int timeOutMilliseconds) const throw();
  10671. /** Wakes up the thread.
  10672. If the thread has called the wait() method, this will wake it up.
  10673. @see wait
  10674. */
  10675. void notify() const throw();
  10676. /** A value type used for thread IDs.
  10677. @see getCurrentThreadId(), getThreadId()
  10678. */
  10679. typedef void* ThreadID;
  10680. /** Returns an id that identifies the caller thread.
  10681. To find the ID of a particular thread object, use getThreadId().
  10682. @returns a unique identifier that identifies the calling thread.
  10683. @see getThreadId
  10684. */
  10685. static ThreadID getCurrentThreadId() throw();
  10686. /** Finds the thread object that is currently running.
  10687. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10688. object associated with them, so this will return 0.
  10689. */
  10690. static Thread* getCurrentThread() throw();
  10691. /** Returns the ID of this thread.
  10692. That means the ID of this thread object - not of the thread that's calling the method.
  10693. This can change when the thread is started and stopped, and will be invalid if the
  10694. thread's not actually running.
  10695. @see getCurrentThreadId
  10696. */
  10697. ThreadID getThreadId() const throw();
  10698. /** Returns the name of the thread.
  10699. This is the name that gets set in the constructor.
  10700. */
  10701. const String getThreadName() const throw() { return threadName_; }
  10702. /** Returns the number of currently-running threads.
  10703. @returns the number of Thread objects known to be currently running.
  10704. @see stopAllThreads
  10705. */
  10706. static int getNumRunningThreads() throw();
  10707. /** Tries to stop all currently-running threads.
  10708. This will attempt to stop all the threads known to be running at the moment.
  10709. */
  10710. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10711. juce_UseDebuggingNewOperator
  10712. private:
  10713. const String threadName_;
  10714. void* volatile threadHandle_;
  10715. CriticalSection startStopLock;
  10716. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10717. int threadPriority_;
  10718. ThreadID threadId_;
  10719. uint32 affinityMask_;
  10720. bool volatile threadShouldExit_;
  10721. friend void JUCE_API juce_threadEntryPoint (void*);
  10722. static void threadEntryPoint (Thread* thread) throw();
  10723. Thread (const Thread&);
  10724. const Thread& operator= (const Thread&);
  10725. };
  10726. #endif // __JUCE_THREAD_JUCEHEADER__
  10727. /********* End of inlined file: juce_Thread.h *********/
  10728. #endif
  10729. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10730. /********* Start of inlined file: juce_ThreadPool.h *********/
  10731. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  10732. #define __JUCE_THREADPOOL_JUCEHEADER__
  10733. class ThreadPool;
  10734. class ThreadPoolThread;
  10735. /**
  10736. A task that is executed by a ThreadPool object.
  10737. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  10738. its threads.
  10739. The runJob() method needs to be implemented to do the task, and if the code that
  10740. does the work takes a significant time to run, it must keep checking the shouldExit()
  10741. method to see if something is trying to interrupt the job. If shouldExit() returns
  10742. true, the runJob() method must return immediately.
  10743. @see ThreadPool, Thread
  10744. */
  10745. class JUCE_API ThreadPoolJob
  10746. {
  10747. public:
  10748. /** Creates a thread pool job object.
  10749. After creating your job, add it to a thread pool with ThreadPool::addJob().
  10750. */
  10751. ThreadPoolJob (const String& name);
  10752. /** Destructor. */
  10753. virtual ~ThreadPoolJob();
  10754. /** Returns the name of this job.
  10755. @see setJobName
  10756. */
  10757. const String getJobName() const;
  10758. /** Changes the job's name.
  10759. @see getJobName
  10760. */
  10761. void setJobName (const String& newName);
  10762. /** These are the values that can be returned by the runJob() method.
  10763. */
  10764. enum JobStatus
  10765. {
  10766. jobHasFinished = 0, /**< indicates that the job has finished and can be
  10767. removed from the pool. */
  10768. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  10769. should be automatically deleted by the pool. */
  10770. jobNeedsRunningAgain /**< indicates that the job would like to be called
  10771. again when a thread is free. */
  10772. };
  10773. /** Peforms the actual work that this job needs to do.
  10774. Your subclass must implement this method, in which is does its work.
  10775. If the code in this method takes a significant time to run, it must repeatedly check
  10776. the shouldExit() method to see if something is trying to interrupt the job.
  10777. If shouldExit() ever returns true, the runJob() method must return immediately.
  10778. If this method returns jobHasFinished, then the job will be removed from the pool
  10779. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  10780. pool and will get a chance to run again as soon as a thread is free.
  10781. @see shouldExit()
  10782. */
  10783. virtual JobStatus runJob() = 0;
  10784. /** Returns true if this job is currently running its runJob() method. */
  10785. bool isRunning() const throw() { return isActive; }
  10786. /** Returns true if something is trying to interrupt this job and make it stop.
  10787. Your runJob() method must call this whenever it gets a chance, and if it ever
  10788. returns true, the runJob() method must return immediately.
  10789. @see signalJobShouldExit()
  10790. */
  10791. bool shouldExit() const throw() { return shouldStop; }
  10792. /** Calling this will cause the shouldExit() method to return true, and the job
  10793. should (if it's been implemented correctly) stop as soon as possible.
  10794. @see shouldExit()
  10795. */
  10796. void signalJobShouldExit();
  10797. juce_UseDebuggingNewOperator
  10798. private:
  10799. friend class ThreadPool;
  10800. friend class ThreadPoolThread;
  10801. String jobName;
  10802. ThreadPool* pool;
  10803. bool shouldStop, isActive, shouldBeDeleted;
  10804. };
  10805. /**
  10806. A set of threads that will run a list of jobs.
  10807. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  10808. will be called by the next pooled thread that becomes free.
  10809. @see ThreadPoolJob, Thread
  10810. */
  10811. class JUCE_API ThreadPool
  10812. {
  10813. public:
  10814. /** Creates a thread pool.
  10815. Once you've created a pool, you can give it some things to do with the addJob()
  10816. method.
  10817. @param numberOfThreads the maximum number of actual threads to run.
  10818. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  10819. until there are some jobs to run. If false, then
  10820. all the threads will be fired-up immediately so that
  10821. they're ready for action
  10822. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  10823. inactive for this length of time, they will automatically
  10824. be stopped until more jobs come along and they're needed
  10825. */
  10826. ThreadPool (const int numberOfThreads,
  10827. const bool startThreadsOnlyWhenNeeded = true,
  10828. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  10829. /** Destructor.
  10830. This will attempt to remove all the jobs before deleting, but if you want to
  10831. specify a timeout, you should call removeAllJobs() explicitly before deleting
  10832. the pool.
  10833. */
  10834. ~ThreadPool();
  10835. /** Adds a job to the queue.
  10836. Once a job has been added, then the next time a thread is free, it will run
  10837. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  10838. runJob() method, the pool will either remove the job from the pool or add it to
  10839. the back of the queue to be run again.
  10840. */
  10841. void addJob (ThreadPoolJob* const job);
  10842. /** Tries to remove a job from the pool.
  10843. If the job isn't yet running, this will simply remove it. If it is running, it
  10844. will wait for it to finish.
  10845. If the timeout period expires before the job finishes running, then the job will be
  10846. left in the pool and this will return false. It returns true if the job is sucessfully
  10847. stopped and removed.
  10848. @param job the job to remove
  10849. @param interruptIfRunning if true, then if the job is currently busy, its
  10850. ThreadPoolJob::signalJobShouldExit() method will be called to try
  10851. to interrupt it. If false, then if the job will be allowed to run
  10852. until it stops normally (or the timeout expires)
  10853. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  10854. before giving up and returning false
  10855. */
  10856. bool removeJob (ThreadPoolJob* const job,
  10857. const bool interruptIfRunning,
  10858. const int timeOutMilliseconds);
  10859. /** Tries clear all jobs from the pool.
  10860. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  10861. methods called to try to interrupt them
  10862. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  10863. before giving up and returning false
  10864. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  10865. expires while waiting for them to stop
  10866. */
  10867. bool removeAllJobs (const bool interruptRunningJobs,
  10868. const int timeOutMilliseconds);
  10869. /** Returns the number of jobs currently running or queued.
  10870. */
  10871. int getNumJobs() const throw();
  10872. /** Returns one of the jobs in the queue.
  10873. Note that this can be a very volatile list as jobs might be continuously getting shifted
  10874. around in the list, and this method may return 0 if the index is currently out-of-range.
  10875. */
  10876. ThreadPoolJob* getJob (const int index) const;
  10877. /** Returns true if the given job is currently queued or running.
  10878. @see isJobRunning()
  10879. */
  10880. bool contains (const ThreadPoolJob* const job) const throw();
  10881. /** Returns true if the given job is currently being run by a thread.
  10882. */
  10883. bool isJobRunning (const ThreadPoolJob* const job) const;
  10884. /** Waits until a job has finished running and has been removed from the pool.
  10885. This will wait until the job is no longer in the pool - i.e. until its
  10886. runJob() method returns ThreadPoolJob::jobHasFinished.
  10887. If the timeout period expires before the job finishes, this will return false;
  10888. it returns true if the job has finished successfully.
  10889. */
  10890. bool waitForJobToFinish (const ThreadPoolJob* const job,
  10891. const int timeOutMilliseconds) const;
  10892. /** Returns a list of the names of all the jobs currently running or queued.
  10893. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  10894. */
  10895. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  10896. /** Changes the priority of all the threads.
  10897. This will call Thread::setPriority() for each thread in the pool.
  10898. */
  10899. void setThreadPriorities (const int newPriority);
  10900. juce_UseDebuggingNewOperator
  10901. private:
  10902. const int numThreads, threadStopTimeout;
  10903. int priority;
  10904. Thread** threads;
  10905. VoidArray jobs;
  10906. CriticalSection lock;
  10907. uint32 lastJobEndTime;
  10908. friend class ThreadPoolThread;
  10909. bool runNextJob();
  10910. ThreadPool (const ThreadPool&);
  10911. const ThreadPool& operator= (const ThreadPool&);
  10912. };
  10913. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  10914. /********* End of inlined file: juce_ThreadPool.h *********/
  10915. #endif
  10916. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10917. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  10918. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10919. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10920. /**
  10921. Used by the TimeSliceThread class.
  10922. To register your class with a TimeSliceThread, derive from this class and
  10923. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  10924. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  10925. deleting your client!
  10926. @see TimeSliceThread
  10927. */
  10928. class JUCE_API TimeSliceClient
  10929. {
  10930. public:
  10931. /** Destructor. */
  10932. virtual ~TimeSliceClient() {}
  10933. /** Called back by a TimeSliceThread.
  10934. When you register this class with it, a TimeSliceThread will repeatedly call
  10935. this method.
  10936. The implementation of this method should use its time-slice to do something that's
  10937. quick - never block for longer than absolutely necessary.
  10938. @returns Your method should return true if it needs more time, or false if it's
  10939. not too busy and doesn't need calling back urgently. If all the thread's
  10940. clients indicate that they're not busy, then it'll save CPU by sleeping for
  10941. up to half a second in between callbacks. You can force the TimeSliceThread
  10942. to wake up and poll again immediately by calling its notify() method.
  10943. */
  10944. virtual bool useTimeSlice() = 0;
  10945. };
  10946. /**
  10947. A thread that keeps a list of clients, and calls each one in turn, giving them
  10948. all a chance to run some sort of short task.
  10949. @see TimeSliceClient, Thread
  10950. */
  10951. class JUCE_API TimeSliceThread : public Thread
  10952. {
  10953. public:
  10954. /**
  10955. Creates a TimeSliceThread.
  10956. When first created, the thread is not running. Use the startThread()
  10957. method to start it.
  10958. */
  10959. TimeSliceThread (const String& threadName);
  10960. /** Destructor.
  10961. Deleting a Thread object that is running will only give the thread a
  10962. brief opportunity to stop itself cleanly, so it's recommended that you
  10963. should always call stopThread() with a decent timeout before deleting,
  10964. to avoid the thread being forcibly killed (which is a Bad Thing).
  10965. */
  10966. ~TimeSliceThread();
  10967. /** Adds a client to the list.
  10968. The client's callbacks will start immediately (possibly before the method
  10969. has returned).
  10970. */
  10971. void addTimeSliceClient (TimeSliceClient* const client);
  10972. /** Removes a client from the list.
  10973. This method will make sure that all callbacks to the client have completely
  10974. finished before the method returns.
  10975. */
  10976. void removeTimeSliceClient (TimeSliceClient* const client);
  10977. /** Returns the number of registered clients. */
  10978. int getNumClients() const throw();
  10979. /** Returns one of the registered clients. */
  10980. TimeSliceClient* getClient (const int index) const throw();
  10981. /** @internal */
  10982. void run();
  10983. juce_UseDebuggingNewOperator
  10984. private:
  10985. CriticalSection callbackLock, listLock;
  10986. Array <TimeSliceClient*> clients;
  10987. int index;
  10988. TimeSliceClient* clientBeingCalled;
  10989. bool clientsChanged;
  10990. TimeSliceThread (const TimeSliceThread&);
  10991. const TimeSliceThread& operator= (const TimeSliceThread&);
  10992. };
  10993. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  10994. /********* End of inlined file: juce_TimeSliceThread.h *********/
  10995. #endif
  10996. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10997. #endif
  10998. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10999. #endif
  11000. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11001. /********* Start of inlined file: juce_InterProcessLock.h *********/
  11002. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11003. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11004. /**
  11005. Acts as a critical section which processes can use to block each other.
  11006. @see CriticalSection
  11007. */
  11008. class JUCE_API InterProcessLock
  11009. {
  11010. public:
  11011. /** Creates a lock object.
  11012. @param name a name that processes will use to identify this lock object
  11013. */
  11014. InterProcessLock (const String& name) throw();
  11015. /** Destructor.
  11016. This will also release the lock if it's currently held by this process.
  11017. */
  11018. ~InterProcessLock() throw();
  11019. /** Attempts to lock the critical section.
  11020. @param timeOutMillisecs how many milliseconds to wait if the lock
  11021. is already held by another process - a value of
  11022. 0 will return immediately, negative values will wait
  11023. forever
  11024. @returns true if the lock could be gained within the timeout period, or
  11025. false if the timeout expired.
  11026. */
  11027. bool enter (int timeOutMillisecs = -1) throw();
  11028. /** Releases the lock if it's currently held by this process.
  11029. */
  11030. void exit() throw();
  11031. juce_UseDebuggingNewOperator
  11032. private:
  11033. void* internal;
  11034. String name;
  11035. int reentrancyLevel;
  11036. InterProcessLock (const InterProcessLock&);
  11037. const InterProcessLock& operator= (const InterProcessLock&);
  11038. };
  11039. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11040. /********* End of inlined file: juce_InterProcessLock.h *********/
  11041. #endif
  11042. #ifndef __JUCE_PROCESS_JUCEHEADER__
  11043. /********* Start of inlined file: juce_Process.h *********/
  11044. #ifndef __JUCE_PROCESS_JUCEHEADER__
  11045. #define __JUCE_PROCESS_JUCEHEADER__
  11046. /** Represents the current executable's process.
  11047. This contains methods for controlling the current application at the
  11048. process-level.
  11049. @see Thread, JUCEApplication
  11050. */
  11051. class JUCE_API Process
  11052. {
  11053. public:
  11054. enum ProcessPriority
  11055. {
  11056. LowPriority = 0,
  11057. NormalPriority = 1,
  11058. HighPriority = 2,
  11059. RealtimePriority = 3
  11060. };
  11061. /** Changes the current process's priority.
  11062. @param priority the process priority, where
  11063. 0=low, 1=normal, 2=high, 3=realtime
  11064. */
  11065. static void setPriority (const ProcessPriority priority);
  11066. /** Kills the current process immediately.
  11067. This is an emergency process terminator that kills the application
  11068. immediately - it's intended only for use only when something goes
  11069. horribly wrong.
  11070. @see JUCEApplication::quit
  11071. */
  11072. static void terminate();
  11073. /** Returns true if this application process is the one that the user is
  11074. currently using.
  11075. */
  11076. static bool isForegroundProcess() throw();
  11077. /** Raises the current process's privilege level.
  11078. Does nothing if this isn't supported by the current OS, or if process
  11079. privilege level is fixed.
  11080. */
  11081. static void raisePrivilege();
  11082. /** Lowers the current process's privilege level.
  11083. Does nothing if this isn't supported by the current OS, or if process
  11084. privilege level is fixed.
  11085. */
  11086. static void lowerPrivilege();
  11087. /** Returns true if this process is being hosted by a debugger.
  11088. */
  11089. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  11090. };
  11091. #endif // __JUCE_PROCESS_JUCEHEADER__
  11092. /********* End of inlined file: juce_Process.h *********/
  11093. #endif
  11094. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11095. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  11096. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11097. #define __JUCE_READWRITELOCK_JUCEHEADER__
  11098. /**
  11099. A critical section that allows multiple simultaneous readers.
  11100. Features of this type of lock are:
  11101. - Multiple readers can hold the lock at the same time, but only one writer
  11102. can hold it at once.
  11103. - Writers trying to gain the lock will be blocked until all readers and writers
  11104. have released it
  11105. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  11106. blocked until the writer has obtained and released it
  11107. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  11108. there are no other readers
  11109. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  11110. - Recursive locking is supported.
  11111. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  11112. */
  11113. class JUCE_API ReadWriteLock
  11114. {
  11115. public:
  11116. /**
  11117. Creates a ReadWriteLock object.
  11118. */
  11119. ReadWriteLock() throw();
  11120. /** Destructor.
  11121. If the object is deleted whilst locked, any subsequent behaviour
  11122. is unpredictable.
  11123. */
  11124. ~ReadWriteLock() throw();
  11125. /** Locks this object for reading.
  11126. Multiple threads can simulaneously lock the object for reading, but if another
  11127. thread has it locked for writing, then this will block until it releases the
  11128. lock.
  11129. @see exitRead, ScopedReadLock
  11130. */
  11131. void enterRead() const throw();
  11132. /** Releases the read-lock.
  11133. If the caller thread hasn't got the lock, this can have unpredictable results.
  11134. If the enterRead() method has been called multiple times by the thread, each
  11135. call must be matched by a call to exitRead() before other threads will be allowed
  11136. to take over the lock.
  11137. @see enterRead, ScopedReadLock
  11138. */
  11139. void exitRead() const throw();
  11140. /** Locks this object for writing.
  11141. This will block until any other threads that have it locked for reading or
  11142. writing have released their lock.
  11143. @see exitWrite, ScopedWriteLock
  11144. */
  11145. void enterWrite() const throw();
  11146. /** Tries to lock this object for writing.
  11147. This is like enterWrite(), but doesn't block - it returns true if it manages
  11148. to obtain the lock.
  11149. @see enterWrite
  11150. */
  11151. bool tryEnterWrite() const throw();
  11152. /** Releases the write-lock.
  11153. If the caller thread hasn't got the lock, this can have unpredictable results.
  11154. If the enterWrite() method has been called multiple times by the thread, each
  11155. call must be matched by a call to exit() before other threads will be allowed
  11156. to take over the lock.
  11157. @see enterWrite, ScopedWriteLock
  11158. */
  11159. void exitWrite() const throw();
  11160. juce_UseDebuggingNewOperator
  11161. private:
  11162. CriticalSection accessLock;
  11163. WaitableEvent waitEvent;
  11164. mutable int numWaitingWriters, numWriters;
  11165. mutable Thread::ThreadID writerThreadId;
  11166. mutable Array <Thread::ThreadID> readerThreads;
  11167. ReadWriteLock (const ReadWriteLock&);
  11168. const ReadWriteLock& operator= (const ReadWriteLock&);
  11169. };
  11170. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  11171. /********* End of inlined file: juce_ReadWriteLock.h *********/
  11172. #endif
  11173. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  11174. #endif
  11175. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11176. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  11177. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11178. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11179. /**
  11180. Automatically locks and unlocks a ReadWriteLock object.
  11181. Use one of these as a local variable to control access to a ReadWriteLock.
  11182. e.g. @code
  11183. ReadWriteLock myLock;
  11184. for (;;)
  11185. {
  11186. const ScopedReadLock myScopedLock (myLock);
  11187. // myLock is now locked
  11188. ...do some stuff...
  11189. // myLock gets unlocked here.
  11190. }
  11191. @endcode
  11192. @see ReadWriteLock, ScopedWriteLock
  11193. */
  11194. class JUCE_API ScopedReadLock
  11195. {
  11196. public:
  11197. /** Creates a ScopedReadLock.
  11198. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  11199. when the ScopedReadLock object is deleted, the ReadWriteLock will
  11200. be unlocked.
  11201. Make sure this object is created and deleted by the same thread,
  11202. otherwise there are no guarantees what will happen! Best just to use it
  11203. as a local stack object, rather than creating one with the new() operator.
  11204. */
  11205. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  11206. /** Destructor.
  11207. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  11208. Make sure this object is created and deleted by the same thread,
  11209. otherwise there are no guarantees what will happen!
  11210. */
  11211. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  11212. private:
  11213. const ReadWriteLock& lock_;
  11214. ScopedReadLock (const ScopedReadLock&);
  11215. const ScopedReadLock& operator= (const ScopedReadLock&);
  11216. };
  11217. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11218. /********* End of inlined file: juce_ScopedReadLock.h *********/
  11219. #endif
  11220. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11221. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  11222. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11223. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11224. /**
  11225. Automatically tries to lock and unlock a CriticalSection object.
  11226. Use one of these as a local variable to control access to a CriticalSection.
  11227. e.g. @code
  11228. CriticalSection myCriticalSection;
  11229. for (;;)
  11230. {
  11231. const ScopedTryLock myScopedTryLock (myCriticalSection);
  11232. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  11233. // should test this with the isLocked() method before doing your thread-unsafe
  11234. // action..
  11235. if (myScopedTryLock.isLocked())
  11236. {
  11237. ...do some stuff...
  11238. }
  11239. else
  11240. {
  11241. ..our attempt at locking failed because another thread had already locked it..
  11242. }
  11243. // myCriticalSection gets unlocked here (if it was locked)
  11244. }
  11245. @endcode
  11246. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  11247. */
  11248. class JUCE_API ScopedTryLock
  11249. {
  11250. public:
  11251. /** Creates a ScopedTryLock.
  11252. As soon as it is created, this will try to lock the CriticalSection, and
  11253. when the ScopedTryLock object is deleted, the CriticalSection will
  11254. be unlocked if the lock was successful.
  11255. Make sure this object is created and deleted by the same thread,
  11256. otherwise there are no guarantees what will happen! Best just to use it
  11257. as a local stack object, rather than creating one with the new() operator.
  11258. */
  11259. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  11260. /** Destructor.
  11261. The CriticalSection will be unlocked (if locked) when the destructor is called.
  11262. Make sure this object is created and deleted by the same thread,
  11263. otherwise there are no guarantees what will happen!
  11264. */
  11265. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  11266. /** Lock state
  11267. @return True if the CriticalSection is locked.
  11268. */
  11269. bool isLocked() const throw() { return lockWasSuccessful; }
  11270. private:
  11271. const CriticalSection& lock_;
  11272. const bool lockWasSuccessful;
  11273. ScopedTryLock (const ScopedTryLock&);
  11274. const ScopedTryLock& operator= (const ScopedTryLock&);
  11275. };
  11276. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11277. /********* End of inlined file: juce_ScopedTryLock.h *********/
  11278. #endif
  11279. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11280. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  11281. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11282. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11283. /**
  11284. Automatically locks and unlocks a ReadWriteLock object.
  11285. Use one of these as a local variable to control access to a ReadWriteLock.
  11286. e.g. @code
  11287. ReadWriteLock myLock;
  11288. for (;;)
  11289. {
  11290. const ScopedWriteLock myScopedLock (myLock);
  11291. // myLock is now locked
  11292. ...do some stuff...
  11293. // myLock gets unlocked here.
  11294. }
  11295. @endcode
  11296. @see ReadWriteLock, ScopedReadLock
  11297. */
  11298. class JUCE_API ScopedWriteLock
  11299. {
  11300. public:
  11301. /** Creates a ScopedWriteLock.
  11302. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  11303. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  11304. be unlocked.
  11305. Make sure this object is created and deleted by the same thread,
  11306. otherwise there are no guarantees what will happen! Best just to use it
  11307. as a local stack object, rather than creating one with the new() operator.
  11308. */
  11309. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  11310. /** Destructor.
  11311. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  11312. Make sure this object is created and deleted by the same thread,
  11313. otherwise there are no guarantees what will happen!
  11314. */
  11315. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  11316. private:
  11317. const ReadWriteLock& lock_;
  11318. ScopedWriteLock (const ScopedWriteLock&);
  11319. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  11320. };
  11321. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11322. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  11323. #endif
  11324. #endif
  11325. /********* End of inlined file: juce_core_includes.h *********/
  11326. // if you're compiling a command-line app, you might want to just include the core headers,
  11327. // so you can set this macro before including juce.h
  11328. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11329. /********* Start of inlined file: juce_app_includes.h *********/
  11330. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11331. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11332. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11333. /********* Start of inlined file: juce_Application.h *********/
  11334. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11335. #define __JUCE_APPLICATION_JUCEHEADER__
  11336. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11337. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11338. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11339. /********* Start of inlined file: juce_Component.h *********/
  11340. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11341. #define __JUCE_COMPONENT_JUCEHEADER__
  11342. /********* Start of inlined file: juce_MouseCursor.h *********/
  11343. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11344. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11345. class Image;
  11346. class RefCountedMouseCursor;
  11347. class ComponentPeer;
  11348. class Component;
  11349. /**
  11350. Represents a mouse cursor image.
  11351. This object can either be used to represent one of the standard mouse
  11352. cursor shapes, or a custom one generated from an image.
  11353. */
  11354. class JUCE_API MouseCursor
  11355. {
  11356. public:
  11357. /** The set of available standard mouse cursors. */
  11358. enum StandardCursorType
  11359. {
  11360. NoCursor = 0, /**< An invisible cursor. */
  11361. NormalCursor, /**< The stardard arrow cursor. */
  11362. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11363. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11364. CrosshairCursor, /**< A pair of crosshairs. */
  11365. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11366. that you're dragging a copy of something. */
  11367. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11368. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11369. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11370. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11371. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11372. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11373. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11374. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11375. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11376. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11377. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11378. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11379. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11380. };
  11381. /** Creates the standard arrow cursor. */
  11382. MouseCursor() throw();
  11383. /** Creates one of the standard mouse cursor */
  11384. MouseCursor (const StandardCursorType type) throw();
  11385. /** Creates a custom cursor from an image.
  11386. @param image the image to use for the cursor - if this is bigger than the
  11387. system can manage, it might get scaled down first, and might
  11388. also have to be turned to black-and-white if it can't do colour
  11389. cursors.
  11390. @param hotSpotX the x position of the cursor's hotspot within the image
  11391. @param hotSpotY the y position of the cursor's hotspot within the image
  11392. */
  11393. MouseCursor (Image& image,
  11394. const int hotSpotX,
  11395. const int hotSpotY) throw();
  11396. /** Creates a copy of another cursor object. */
  11397. MouseCursor (const MouseCursor& other) throw();
  11398. /** Copies this cursor from another object. */
  11399. const MouseCursor& operator= (const MouseCursor& other) throw();
  11400. /** Destructor. */
  11401. ~MouseCursor() throw();
  11402. /** Checks whether two mouse cursors are the same.
  11403. For custom cursors, two cursors created from the same image won't be
  11404. recognised as the same, only MouseCursor objects that have been
  11405. copied from the same object.
  11406. */
  11407. bool operator== (const MouseCursor& other) const throw();
  11408. /** Checks whether two mouse cursors are the same.
  11409. For custom cursors, two cursors created from the same image won't be
  11410. recognised as the same, only MouseCursor objects that have been
  11411. copied from the same object.
  11412. */
  11413. bool operator!= (const MouseCursor& other) const throw();
  11414. /** Makes the system show its default 'busy' cursor.
  11415. This will turn the system cursor to an hourglass or spinning beachball
  11416. until the next time the mouse is moved, or hideWaitCursor() is called.
  11417. This is handy if the message loop is about to block for a couple of
  11418. seconds while busy and you want to give the user feedback about this.
  11419. @see MessageManager::setTimeBeforeShowingWaitCursor
  11420. */
  11421. static void showWaitCursor() throw();
  11422. /** If showWaitCursor has been called, this will return the mouse to its
  11423. normal state.
  11424. This will look at what component is under the mouse, and update the
  11425. cursor to be the correct one for that component.
  11426. @see showWaitCursor
  11427. */
  11428. static void hideWaitCursor() throw();
  11429. juce_UseDebuggingNewOperator
  11430. private:
  11431. RefCountedMouseCursor* cursorHandle;
  11432. friend class Component;
  11433. void showInWindow (ComponentPeer* window) const throw();
  11434. void showInAllWindows() const throw();
  11435. void* getHandle() const throw();
  11436. };
  11437. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11438. /********* End of inlined file: juce_MouseCursor.h *********/
  11439. /********* Start of inlined file: juce_MouseListener.h *********/
  11440. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11441. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11442. /********* Start of inlined file: juce_MouseEvent.h *********/
  11443. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11444. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11445. class Component;
  11446. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11447. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11448. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11449. /**
  11450. Represents the state of the mouse buttons and modifier keys.
  11451. This is used both by mouse events and by KeyPress objects to describe
  11452. the state of keys such as shift, control, alt, etc.
  11453. @see KeyPress, MouseEvent::mods
  11454. */
  11455. class JUCE_API ModifierKeys
  11456. {
  11457. public:
  11458. /** Creates a ModifierKeys object from a raw set of flags.
  11459. @param flags to represent the keys that are down
  11460. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11461. rightButtonModifier, commandModifier, popupMenuClickModifier
  11462. */
  11463. ModifierKeys (const int flags = 0) throw();
  11464. /** Creates a copy of another object. */
  11465. ModifierKeys (const ModifierKeys& other) throw();
  11466. /** Copies this object from another one. */
  11467. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11468. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11469. This is a platform-agnostic way of checking for the operating system's
  11470. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11471. Windows/Linux, it's actually checking for the CTRL key.
  11472. */
  11473. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11474. /** Checks whether the user is trying to launch a pop-up menu.
  11475. This checks for platform-specific modifiers that might indicate that the user
  11476. is following the operating system's normal method of showing a pop-up menu.
  11477. So on Windows/Linux, this method is really testing for a right-click.
  11478. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11479. */
  11480. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11481. /** Checks whether the flag is set for the left mouse-button. */
  11482. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11483. /** Checks whether the flag is set for the right mouse-button.
  11484. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11485. this is platform-independent (and makes your code more explanatory too).
  11486. */
  11487. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11488. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11489. /** Tests for any of the mouse-button flags. */
  11490. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11491. /** Tests for any of the modifier key flags. */
  11492. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11493. /** Checks whether the shift key's flag is set. */
  11494. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11495. /** Checks whether the CTRL key's flag is set.
  11496. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11497. popup-menu modifiers.
  11498. @see isCommandDown, isPopupMenu
  11499. */
  11500. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11501. /** Checks whether the shift key's flag is set. */
  11502. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11503. /** Flags that represent the different keys. */
  11504. enum Flags
  11505. {
  11506. /** Shift key flag. */
  11507. shiftModifier = 1,
  11508. /** CTRL key flag. */
  11509. ctrlModifier = 2,
  11510. /** ALT key flag. */
  11511. altModifier = 4,
  11512. /** Left mouse button flag. */
  11513. leftButtonModifier = 16,
  11514. /** Right mouse button flag. */
  11515. rightButtonModifier = 32,
  11516. /** Middle mouse button flag. */
  11517. middleButtonModifier = 64,
  11518. #if JUCE_MAC
  11519. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11520. commandModifier = 8,
  11521. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11522. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11523. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11524. #else
  11525. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11526. commandModifier = ctrlModifier,
  11527. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11528. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11529. popupMenuClickModifier = rightButtonModifier,
  11530. #endif
  11531. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11532. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11533. /** Represents a combination of all the mouse buttons at once. */
  11534. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11535. };
  11536. /** Returns the raw flags for direct testing. */
  11537. inline int getRawFlags() const throw() { return flags; }
  11538. /** Tests a combination of flags and returns true if any of them are set. */
  11539. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11540. /** Creates a ModifierKeys object to represent the last-known state of the
  11541. keyboard and mouse buttons.
  11542. @see getCurrentModifiersRealtime
  11543. */
  11544. static const ModifierKeys getCurrentModifiers() throw();
  11545. /** Creates a ModifierKeys object to represent the current state of the
  11546. keyboard and mouse buttons.
  11547. This isn't often needed and isn't recommended, but will actively check all the
  11548. mouse and key states rather than just returning their last-known state like
  11549. getCurrentModifiers() does.
  11550. This is only needed in special circumstances for up-to-date modifier information
  11551. at times when the app's event loop isn't running normally.
  11552. */
  11553. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11554. private:
  11555. int flags;
  11556. static int currentModifierFlags;
  11557. friend class ComponentPeer;
  11558. static void updateCurrentModifiers() throw();
  11559. };
  11560. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11561. /********* End of inlined file: juce_ModifierKeys.h *********/
  11562. /**
  11563. Contains position and status information about a mouse event.
  11564. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11565. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11566. */
  11567. class JUCE_API MouseEvent
  11568. {
  11569. public:
  11570. /** Creates a MouseEvent.
  11571. Normally an application will never need to use this.
  11572. @param x the x position of the mouse, relative to the component that is passed-in
  11573. @param y the y position of the mouse, relative to the component that is passed-in
  11574. @param modifiers the key modifiers at the time of the event
  11575. @param originator the component that the mouse event applies to
  11576. @param eventTime the time the event happened
  11577. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11578. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11579. the same as the current mouse-x position.
  11580. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11581. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11582. the same as the current mouse-y position.
  11583. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11584. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11585. the same as the current mouse-event time.
  11586. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11587. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11588. */
  11589. MouseEvent (const int x, const int y,
  11590. const ModifierKeys& modifiers,
  11591. Component* const originator,
  11592. const Time& eventTime,
  11593. const int mouseDownX,
  11594. const int mouseDownY,
  11595. const Time& mouseDownTime,
  11596. const int numberOfClicks,
  11597. const bool mouseWasDragged) throw();
  11598. /** Destructor. */
  11599. ~MouseEvent() throw();
  11600. /** The x-position of the mouse when the event occurred.
  11601. This value is relative to the top-left of the component to which the
  11602. event applies (as indicated by the MouseEvent::eventComponent field).
  11603. */
  11604. int x;
  11605. /** The y-position of the mouse when the event occurred.
  11606. This value is relative to the top-left of the component to which the
  11607. event applies (as indicated by the MouseEvent::eventComponent field).
  11608. */
  11609. int y;
  11610. /** The key modifiers associated with the event.
  11611. This will let you find out which mouse buttons were down, as well as which
  11612. modifier keys were held down.
  11613. When used for mouse-up events, this will indicate the state of the mouse buttons
  11614. just before they were released, so that you can tell which button they let go of.
  11615. */
  11616. ModifierKeys mods;
  11617. /** The component that this event applies to.
  11618. This is usually the component that the mouse was over at the time, but for mouse-drag
  11619. events the mouse could actually be over a different component and the events are
  11620. still sent to the component that the button was originally pressed on.
  11621. The x and y member variables are relative to this component's position.
  11622. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11623. component, this pointer will be updated, but originalComponent remains unchanged.
  11624. @see originalComponent
  11625. */
  11626. Component* eventComponent;
  11627. /** The component that the event first occurred on.
  11628. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11629. component, this value remains unchanged to indicate the first component that received it.
  11630. @see eventComponent
  11631. */
  11632. Component* originalComponent;
  11633. /** The time that this mouse-event occurred.
  11634. */
  11635. Time eventTime;
  11636. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11637. The co-ordinate is relative to the component specified in MouseEvent::component.
  11638. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11639. */
  11640. int getMouseDownX() const throw();
  11641. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11642. The co-ordinate is relative to the component specified in MouseEvent::component.
  11643. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11644. */
  11645. int getMouseDownY() const throw();
  11646. /** Returns the straight-line distance between where the mouse is now and where it
  11647. was the last time the button was pressed.
  11648. This is quite handy for things like deciding whether the user has moved far enough
  11649. for it to be considered a drag operation.
  11650. @see getDistanceFromDragStartX
  11651. */
  11652. int getDistanceFromDragStart() const throw();
  11653. /** Returns the difference between the mouse's current x postion and where it was
  11654. when the button was last pressed.
  11655. @see getDistanceFromDragStart
  11656. */
  11657. int getDistanceFromDragStartX() const throw();
  11658. /** Returns the difference between the mouse's current y postion and where it was
  11659. when the button was last pressed.
  11660. @see getDistanceFromDragStart
  11661. */
  11662. int getDistanceFromDragStartY() const throw();
  11663. /** Returns true if the mouse has just been clicked.
  11664. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11665. the user has dragged the mouse more than a few pixels from the place where the
  11666. mouse-down occurred.
  11667. Once they have dragged it far enough for this method to return false, it will continue
  11668. to return false until the mouse-up, even if they move the mouse back to the same
  11669. position where they originally pressed it. This means that it's very handy for
  11670. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11671. callback to ignore any small movements they might make while clicking.
  11672. @returns true if the mouse wasn't dragged by more than a few pixels between
  11673. the last time the button was pressed and released.
  11674. */
  11675. bool mouseWasClicked() const throw();
  11676. /** For a click event, the number of times the mouse was clicked in succession.
  11677. So for example a double-click event will return 2, a triple-click 3, etc.
  11678. */
  11679. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11680. /** Returns the time that the mouse button has been held down for.
  11681. If called from a mouseDrag or mouseUp callback, this will return the
  11682. number of milliseconds since the corresponding mouseDown event occurred.
  11683. If called in other contexts, e.g. a mouseMove, then the returned value
  11684. may be 0 or an undefined value.
  11685. */
  11686. int getLengthOfMousePress() const throw();
  11687. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11688. The co-ordinates are relative to the top-left of the main monitor.
  11689. @see getMouseDownScreenX, Desktop::getMousePosition
  11690. */
  11691. int getScreenX() const throw();
  11692. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11693. The co-ordinates are relative to the top-left of the main monitor.
  11694. @see getMouseDownScreenY, Desktop::getMousePosition
  11695. */
  11696. int getScreenY() const throw();
  11697. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11698. The co-ordinates are relative to the top-left of the main monitor.
  11699. @see getScreenX, Desktop::getMousePosition
  11700. */
  11701. int getMouseDownScreenX() const throw();
  11702. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11703. The co-ordinates are relative to the top-left of the main monitor.
  11704. @see getScreenY, Desktop::getMousePosition
  11705. */
  11706. int getMouseDownScreenY() const throw();
  11707. /** Creates a version of this event that is relative to a different component.
  11708. The x and y positions of the event that is returned will have been
  11709. adjusted to be relative to the new component.
  11710. */
  11711. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11712. /** Changes the application-wide setting for the double-click time limit.
  11713. This is the maximum length of time between mouse-clicks for it to be
  11714. considered a double-click. It's used by the Component class.
  11715. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11716. */
  11717. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11718. /** Returns the application-wide setting for the double-click time limit.
  11719. This is the maximum length of time between mouse-clicks for it to be
  11720. considered a double-click. It's used by the Component class.
  11721. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11722. */
  11723. static int getDoubleClickTimeout() throw();
  11724. juce_UseDebuggingNewOperator
  11725. private:
  11726. int mouseDownX, mouseDownY;
  11727. Time mouseDownTime;
  11728. int numberOfClicks;
  11729. bool wasMovedSinceMouseDown;
  11730. };
  11731. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11732. /********* End of inlined file: juce_MouseEvent.h *********/
  11733. /**
  11734. A MouseListener can be registered with a component to receive callbacks
  11735. about mouse events that happen to that component.
  11736. @see Component::addMouseListener, Component::removeMouseListener
  11737. */
  11738. class JUCE_API MouseListener
  11739. {
  11740. public:
  11741. /** Destructor. */
  11742. virtual ~MouseListener() {}
  11743. /** Called when the mouse moves inside a component.
  11744. If the mouse button isn't pressed and the mouse moves over a component,
  11745. this will be called to let the component react to this.
  11746. A component will always get a mouseEnter callback before a mouseMove.
  11747. @param e details about the position and status of the mouse event, including
  11748. the source component in which it occurred
  11749. @see mouseEnter, mouseExit, mouseDrag, contains
  11750. */
  11751. virtual void mouseMove (const MouseEvent& e);
  11752. /** Called when the mouse first enters a component.
  11753. If the mouse button isn't pressed and the mouse moves into a component,
  11754. this will be called to let the component react to this.
  11755. When the mouse button is pressed and held down while being moved in
  11756. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11757. mouseDrag messages are sent to the component that the mouse was originally
  11758. clicked on, until the button is released.
  11759. @param e details about the position and status of the mouse event, including
  11760. the source component in which it occurred
  11761. @see mouseExit, mouseDrag, mouseMove, contains
  11762. */
  11763. virtual void mouseEnter (const MouseEvent& e);
  11764. /** Called when the mouse moves out of a component.
  11765. This will be called when the mouse moves off the edge of this
  11766. component.
  11767. If the mouse button was pressed, and it was then dragged off the
  11768. edge of the component and released, then this callback will happen
  11769. when the button is released, after the mouseUp callback.
  11770. @param e details about the position and status of the mouse event, including
  11771. the source component in which it occurred
  11772. @see mouseEnter, mouseDrag, mouseMove, contains
  11773. */
  11774. virtual void mouseExit (const MouseEvent& e);
  11775. /** Called when a mouse button is pressed.
  11776. The MouseEvent object passed in contains lots of methods for finding out
  11777. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11778. were held down at the time.
  11779. Once a button is held down, the mouseDrag method will be called when the
  11780. mouse moves, until the button is released.
  11781. @param e details about the position and status of the mouse event, including
  11782. the source component in which it occurred
  11783. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11784. */
  11785. virtual void mouseDown (const MouseEvent& e);
  11786. /** Called when the mouse is moved while a button is held down.
  11787. When a mouse button is pressed inside a component, that component
  11788. receives mouseDrag callbacks each time the mouse moves, even if the
  11789. mouse strays outside the component's bounds.
  11790. @param e details about the position and status of the mouse event, including
  11791. the source component in which it occurred
  11792. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11793. */
  11794. virtual void mouseDrag (const MouseEvent& e);
  11795. /** Called when a mouse button is released.
  11796. A mouseUp callback is sent to the component in which a button was pressed
  11797. even if the mouse is actually over a different component when the
  11798. button is released.
  11799. The MouseEvent object passed in contains lots of methods for finding out
  11800. which buttons were down just before they were released.
  11801. @param e details about the position and status of the mouse event, including
  11802. the source component in which it occurred
  11803. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11804. */
  11805. virtual void mouseUp (const MouseEvent& e);
  11806. /** Called when a mouse button has been double-clicked on a component.
  11807. The MouseEvent object passed in contains lots of methods for finding out
  11808. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11809. were held down at the time.
  11810. @param e details about the position and status of the mouse event, including
  11811. the source component in which it occurred
  11812. @see mouseDown, mouseUp
  11813. */
  11814. virtual void mouseDoubleClick (const MouseEvent& e);
  11815. /** Called when the mouse-wheel is moved.
  11816. This callback is sent to the component that the mouse is over when the
  11817. wheel is moved.
  11818. If not overridden, the component will forward this message to its parent, so
  11819. that parent components can collect mouse-wheel messages that happen to
  11820. child components which aren't interested in them.
  11821. @param e details about the position and status of the mouse event, including
  11822. the source component in which it occurred
  11823. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11824. value means the wheel has been pushed to the right, negative means it
  11825. was pushed to the left
  11826. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11827. value means the wheel has been pushed upwards, negative means it
  11828. was pushed downwards
  11829. */
  11830. virtual void mouseWheelMove (const MouseEvent& e,
  11831. float wheelIncrementX,
  11832. float wheelIncrementY);
  11833. private:
  11834. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11835. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11836. // if that happens, update your code to use the new one above.
  11837. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11838. };
  11839. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11840. /********* End of inlined file: juce_MouseListener.h *********/
  11841. /********* Start of inlined file: juce_ComponentListener.h *********/
  11842. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11843. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11844. class Component;
  11845. /**
  11846. Gets informed about changes to a component's hierarchy or position.
  11847. To monitor a component for changes, register a subclass of ComponentListener
  11848. with the component using Component::addComponentListener().
  11849. Be sure to deregister listeners before you delete them!
  11850. @see Component::addComponentListener, Component::removeComponentListener
  11851. */
  11852. class JUCE_API ComponentListener
  11853. {
  11854. public:
  11855. /** Destructor. */
  11856. virtual ~ComponentListener() {}
  11857. /** Called when the component's position or size changes.
  11858. @param component the component that was moved or resized
  11859. @param wasMoved true if the component's top-left corner has just moved
  11860. @param wasResized true if the component's width or height has just changed
  11861. @see Component::setBounds, Component::resized, Component::moved
  11862. */
  11863. virtual void componentMovedOrResized (Component& component,
  11864. bool wasMoved,
  11865. bool wasResized);
  11866. /** Called when the component is brought to the top of the z-order.
  11867. @param component the component that was moved
  11868. @see Component::toFront, Component::broughtToFront
  11869. */
  11870. virtual void componentBroughtToFront (Component& component);
  11871. /** Called when the component is made visible or invisible.
  11872. @param component the component that changed
  11873. @see Component::setVisible
  11874. */
  11875. virtual void componentVisibilityChanged (Component& component);
  11876. /** Called when the component has children added or removed.
  11877. @param component the component whose children were changed
  11878. @see Component::childrenChanged, Component::addChildComponent,
  11879. Component::removeChildComponent
  11880. */
  11881. virtual void componentChildrenChanged (Component& component);
  11882. /** Called to indicate that the component's parents have changed.
  11883. When a component is added or removed from its parent, all of its children
  11884. will produce this notification (recursively - so all children of its
  11885. children will also be called as well).
  11886. @param component the component that this listener is registered with
  11887. @see Component::parentHierarchyChanged
  11888. */
  11889. virtual void componentParentHierarchyChanged (Component& component);
  11890. /** Called when the component's name is changed.
  11891. @see Component::setName, Component::getName
  11892. */
  11893. virtual void componentNameChanged (Component& component);
  11894. };
  11895. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11896. /********* End of inlined file: juce_ComponentListener.h *********/
  11897. /********* Start of inlined file: juce_KeyListener.h *********/
  11898. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11899. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11900. /********* Start of inlined file: juce_KeyPress.h *********/
  11901. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11902. #define __JUCE_KEYPRESS_JUCEHEADER__
  11903. /**
  11904. Represents a key press, including any modifier keys that are needed.
  11905. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11906. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11907. */
  11908. class JUCE_API KeyPress
  11909. {
  11910. public:
  11911. /** Creates an (invalid) KeyPress.
  11912. @see isValid
  11913. */
  11914. KeyPress() throw();
  11915. /** Creates a KeyPress for a key and some modifiers.
  11916. e.g.
  11917. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11918. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11919. @param keyCode a code that represents the key - this value must be
  11920. one of special constants listed in this class, or an
  11921. 8-bit character code such as a letter (case is ignored),
  11922. digit or a simple key like "," or ".". Note that this
  11923. isn't the same as the textCharacter parameter, so for example
  11924. a keyCode of 'a' and a shift-key modifier should have a
  11925. textCharacter value of 'A'.
  11926. @param modifiers the modifiers to associate with the keystroke
  11927. @param textCharacter the character that would be printed if someone typed
  11928. this keypress into a text editor. This value may be
  11929. null if the keypress is a non-printing character
  11930. @see getKeyCode, isKeyCode, getModifiers
  11931. */
  11932. KeyPress (const int keyCode,
  11933. const ModifierKeys& modifiers,
  11934. const juce_wchar textCharacter) throw();
  11935. /** Creates a keypress with a keyCode but no modifiers or text character.
  11936. */
  11937. KeyPress (const int keyCode) throw();
  11938. /** Creates a copy of another KeyPress. */
  11939. KeyPress (const KeyPress& other) throw();
  11940. /** Copies this KeyPress from another one. */
  11941. const KeyPress& operator= (const KeyPress& other) throw();
  11942. /** Compares two KeyPress objects. */
  11943. bool operator== (const KeyPress& other) const throw();
  11944. /** Compares two KeyPress objects. */
  11945. bool operator!= (const KeyPress& other) const throw();
  11946. /** Returns true if this is a valid KeyPress.
  11947. A null keypress can be created by the default constructor, in case it's
  11948. needed.
  11949. */
  11950. bool isValid() const throw() { return keyCode != 0; }
  11951. /** Returns the key code itself.
  11952. This will either be one of the special constants defined in this class,
  11953. or an 8-bit character code.
  11954. */
  11955. int getKeyCode() const throw() { return keyCode; }
  11956. /** Returns the key modifiers.
  11957. @see ModifierKeys
  11958. */
  11959. const ModifierKeys getModifiers() const throw() { return mods; }
  11960. /** Returns the character that is associated with this keypress.
  11961. This is the character that you'd expect to see printed if you press this
  11962. keypress in a text editor or similar component.
  11963. */
  11964. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11965. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11966. the modifiers.
  11967. The values for key codes can either be one of the special constants defined in
  11968. this class, or an 8-bit character code.
  11969. @see getKeyCode
  11970. */
  11971. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11972. /** Converts a textual key description to a KeyPress.
  11973. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11974. This isn't designed to cope with any kind of input, but should be given the
  11975. strings that are created by the getTextDescription() method.
  11976. If the string can't be parsed, the object returned will be invalid.
  11977. @see getTextDescription
  11978. */
  11979. static const KeyPress createFromDescription (const String& textVersion) throw();
  11980. /** Creates a textual description of the key combination.
  11981. e.g. "CTRL + C" or "DELETE".
  11982. To store a keypress in a file, use this method, along with createFromDescription()
  11983. to retrieve it later.
  11984. */
  11985. const String getTextDescription() const throw();
  11986. /** Checks whether the user is currently holding down the keys that make up this
  11987. KeyPress.
  11988. Note that this will return false if any extra modifier keys are
  11989. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11990. then it will be false.
  11991. */
  11992. bool isCurrentlyDown() const throw();
  11993. /** Checks whether a particular key is held down, irrespective of modifiers.
  11994. The values for key codes can either be one of the special constants defined in
  11995. this class, or an 8-bit character code.
  11996. */
  11997. static bool isKeyCurrentlyDown (int keyCode) throw();
  11998. // Key codes
  11999. //
  12000. // Note that the actual values of these are platform-specific and may change
  12001. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  12002. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  12003. //
  12004. static const int spaceKey; /**< key-code for the space bar */
  12005. static const int escapeKey; /**< key-code for the escape key */
  12006. static const int returnKey; /**< key-code for the return key*/
  12007. static const int tabKey; /**< key-code for the tab key*/
  12008. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  12009. static const int backspaceKey; /**< key-code for the backspace key */
  12010. static const int insertKey; /**< key-code for the insert key */
  12011. static const int upKey; /**< key-code for the cursor-up key */
  12012. static const int downKey; /**< key-code for the cursor-down key */
  12013. static const int leftKey; /**< key-code for the cursor-left key */
  12014. static const int rightKey; /**< key-code for the cursor-right key */
  12015. static const int pageUpKey; /**< key-code for the page-up key */
  12016. static const int pageDownKey; /**< key-code for the page-down key */
  12017. static const int homeKey; /**< key-code for the home key */
  12018. static const int endKey; /**< key-code for the end key */
  12019. static const int F1Key; /**< key-code for the F1 key */
  12020. static const int F2Key; /**< key-code for the F2 key */
  12021. static const int F3Key; /**< key-code for the F3 key */
  12022. static const int F4Key; /**< key-code for the F4 key */
  12023. static const int F5Key; /**< key-code for the F5 key */
  12024. static const int F6Key; /**< key-code for the F6 key */
  12025. static const int F7Key; /**< key-code for the F7 key */
  12026. static const int F8Key; /**< key-code for the F8 key */
  12027. static const int F9Key; /**< key-code for the F9 key */
  12028. static const int F10Key; /**< key-code for the F10 key */
  12029. static const int F11Key; /**< key-code for the F11 key */
  12030. static const int F12Key; /**< key-code for the F12 key */
  12031. static const int F13Key; /**< key-code for the F13 key */
  12032. static const int F14Key; /**< key-code for the F14 key */
  12033. static const int F15Key; /**< key-code for the F15 key */
  12034. static const int F16Key; /**< key-code for the F16 key */
  12035. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  12036. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  12037. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  12038. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  12039. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  12040. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  12041. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  12042. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  12043. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  12044. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  12045. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  12046. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  12047. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  12048. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  12049. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  12050. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  12051. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  12052. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  12053. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  12054. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  12055. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  12056. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  12057. juce_UseDebuggingNewOperator
  12058. private:
  12059. int keyCode;
  12060. ModifierKeys mods;
  12061. juce_wchar textCharacter;
  12062. };
  12063. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  12064. /********* End of inlined file: juce_KeyPress.h *********/
  12065. class Component;
  12066. /**
  12067. Receives callbacks when keys are pressed.
  12068. You can add a key listener to a component to be informed when that component
  12069. gets key events. See the Component::addListener method for more details.
  12070. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  12071. */
  12072. class JUCE_API KeyListener
  12073. {
  12074. public:
  12075. /** Destructor. */
  12076. virtual ~KeyListener() {}
  12077. /** Called to indicate that a key has been pressed.
  12078. If your implementation returns true, then the key event is considered to have
  12079. been consumed, and will not be passed on to any other components. If it returns
  12080. false, then the key will be passed to other components that might want to use it.
  12081. @param key the keystroke, including modifier keys
  12082. @param originatingComponent the component that received the key event
  12083. @see keyStateChanged, Component::keyPressed
  12084. */
  12085. virtual bool keyPressed (const KeyPress& key,
  12086. Component* originatingComponent) = 0;
  12087. /** Called when any key is pressed or released.
  12088. When this is called, classes that might be interested in
  12089. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  12090. check whether their key has changed.
  12091. If your implementation returns true, then the key event is considered to have
  12092. been consumed, and will not be passed on to any other components. If it returns
  12093. false, then the key will be passed to other components that might want to use it.
  12094. @param originatingComponent the component that received the key event
  12095. @see KeyPress, Component::keyStateChanged
  12096. */
  12097. virtual bool keyStateChanged (Component* originatingComponent);
  12098. };
  12099. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  12100. /********* End of inlined file: juce_KeyListener.h *********/
  12101. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  12102. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12103. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12104. class Component;
  12105. /**
  12106. Controls the order in which focus moves between components.
  12107. The default algorithm used by this class to work out the order of traversal
  12108. is as follows:
  12109. - if two components both have an explicit focus order specified, then the
  12110. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12111. method).
  12112. - any component with an explicit focus order greater than 0 comes before ones
  12113. that don't have an order specified.
  12114. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12115. order.
  12116. If you need traversal in a more customised way, you can create a subclass
  12117. of KeyboardFocusTraverser that uses your own algorithm, and use
  12118. Component::createFocusTraverser() to create it.
  12119. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12120. */
  12121. class JUCE_API KeyboardFocusTraverser
  12122. {
  12123. public:
  12124. KeyboardFocusTraverser();
  12125. /** Destructor. */
  12126. virtual ~KeyboardFocusTraverser();
  12127. /** Returns the component that should be given focus after the specified one
  12128. when moving "forwards".
  12129. The default implementation will return the next component which is to the
  12130. right of or below this one.
  12131. This may return 0 if there's no suitable candidate.
  12132. */
  12133. virtual Component* getNextComponent (Component* current);
  12134. /** Returns the component that should be given focus after the specified one
  12135. when moving "backwards".
  12136. The default implementation will return the next component which is to the
  12137. left of or above this one.
  12138. This may return 0 if there's no suitable candidate.
  12139. */
  12140. virtual Component* getPreviousComponent (Component* current);
  12141. /** Returns the component that should receive focus be default within the given
  12142. parent component.
  12143. The default implementation will just return the foremost child component that
  12144. wants focus.
  12145. This may return 0 if there's no suitable candidate.
  12146. */
  12147. virtual Component* getDefaultComponent (Component* parentComponent);
  12148. };
  12149. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12150. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12151. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12152. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12153. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12154. /********* Start of inlined file: juce_Graphics.h *********/
  12155. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12156. #define __JUCE_GRAPHICS_JUCEHEADER__
  12157. /********* Start of inlined file: juce_Font.h *********/
  12158. #ifndef __JUCE_FONT_JUCEHEADER__
  12159. #define __JUCE_FONT_JUCEHEADER__
  12160. /********* Start of inlined file: juce_Typeface.h *********/
  12161. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12162. #define __JUCE_TYPEFACE_JUCEHEADER__
  12163. /********* Start of inlined file: juce_Path.h *********/
  12164. #ifndef __JUCE_PATH_JUCEHEADER__
  12165. #define __JUCE_PATH_JUCEHEADER__
  12166. /********* Start of inlined file: juce_AffineTransform.h *********/
  12167. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12168. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12169. /**
  12170. Represents a 2D affine-transformation matrix.
  12171. An affine transformation is a transformation such as a rotation, scale, shear,
  12172. resize or translation.
  12173. These are used for various 2D transformation tasks, e.g. with Path objects.
  12174. @see Path, Point, Line
  12175. */
  12176. class JUCE_API AffineTransform
  12177. {
  12178. public:
  12179. /** Creates an identity transform. */
  12180. AffineTransform() throw();
  12181. /** Creates a copy of another transform. */
  12182. AffineTransform (const AffineTransform& other) throw();
  12183. /** Creates a transform from a set of raw matrix values.
  12184. The resulting matrix is:
  12185. (mat00 mat01 mat02)
  12186. (mat10 mat11 mat12)
  12187. ( 0 0 1 )
  12188. */
  12189. AffineTransform (const float mat00, const float mat01, const float mat02,
  12190. const float mat10, const float mat11, const float mat12) throw();
  12191. /** Copies from another AffineTransform object */
  12192. const AffineTransform& operator= (const AffineTransform& other) throw();
  12193. /** Compares two transforms. */
  12194. bool operator== (const AffineTransform& other) const throw();
  12195. /** Compares two transforms. */
  12196. bool operator!= (const AffineTransform& other) const throw();
  12197. /** A ready-to-use identity transform, which you can use to append other
  12198. transformations to.
  12199. e.g. @code
  12200. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12201. .scaled (2.0f);
  12202. @endcode
  12203. */
  12204. static const AffineTransform identity;
  12205. /** Transforms a 2D co-ordinate using this matrix. */
  12206. void transformPoint (float& x,
  12207. float& y) const throw();
  12208. /** Transforms a 2D co-ordinate using this matrix. */
  12209. void transformPoint (double& x,
  12210. double& y) const throw();
  12211. /** Returns a new transform which is the same as this one followed by a translation. */
  12212. const AffineTransform translated (const float deltaX,
  12213. const float deltaY) const throw();
  12214. /** Returns a new transform which is a translation. */
  12215. static const AffineTransform translation (const float deltaX,
  12216. const float deltaY) throw();
  12217. /** Returns a transform which is the same as this one followed by a rotation.
  12218. The rotation is specified by a number of radians to rotate clockwise, centred around
  12219. the origin (0, 0).
  12220. */
  12221. const AffineTransform rotated (const float angleInRadians) const throw();
  12222. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12223. The rotation is specified by a number of radians to rotate clockwise, centred around
  12224. the co-ordinates passed in.
  12225. */
  12226. const AffineTransform rotated (const float angleInRadians,
  12227. const float pivotX,
  12228. const float pivotY) const throw();
  12229. /** Returns a new transform which is a rotation about (0, 0). */
  12230. static const AffineTransform rotation (const float angleInRadians) throw();
  12231. /** Returns a new transform which is a rotation about a given point. */
  12232. static const AffineTransform rotation (const float angleInRadians,
  12233. const float pivotX,
  12234. const float pivotY) throw();
  12235. /** Returns a transform which is the same as this one followed by a re-scaling.
  12236. The scaling is centred around the origin (0, 0).
  12237. */
  12238. const AffineTransform scaled (const float factorX,
  12239. const float factorY) const throw();
  12240. /** Returns a new transform which is a re-scale about the origin. */
  12241. static const AffineTransform scale (const float factorX,
  12242. const float factorY) throw();
  12243. /** Returns a transform which is the same as this one followed by a shear.
  12244. The shear is centred around the origin (0, 0).
  12245. */
  12246. const AffineTransform sheared (const float shearX,
  12247. const float shearY) const throw();
  12248. /** Returns a matrix which is the inverse operation of this one.
  12249. Some matrices don't have an inverse - in this case, the method will just return
  12250. an identity transform.
  12251. */
  12252. const AffineTransform inverted() const throw();
  12253. /** Returns the result of concatenating another transformation after this one. */
  12254. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12255. /** Returns true if this transform has no effect on points. */
  12256. bool isIdentity() const throw();
  12257. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12258. bool isSingularity() const throw();
  12259. juce_UseDebuggingNewOperator
  12260. /* The transform matrix is:
  12261. (mat00 mat01 mat02)
  12262. (mat10 mat11 mat12)
  12263. ( 0 0 1 )
  12264. */
  12265. float mat00, mat01, mat02;
  12266. float mat10, mat11, mat12;
  12267. private:
  12268. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12269. const float mat10, const float mat11, const float mat12) const throw();
  12270. };
  12271. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12272. /********* End of inlined file: juce_AffineTransform.h *********/
  12273. /********* Start of inlined file: juce_Point.h *********/
  12274. #ifndef __JUCE_POINT_JUCEHEADER__
  12275. #define __JUCE_POINT_JUCEHEADER__
  12276. /**
  12277. A pair of (x, y) co-ordinates.
  12278. Uses 32-bit floating point accuracy.
  12279. @see Line, Path, AffineTransform
  12280. */
  12281. class JUCE_API Point
  12282. {
  12283. public:
  12284. /** Creates a point with co-ordinates (0, 0). */
  12285. Point() throw();
  12286. /** Creates a copy of another point. */
  12287. Point (const Point& other) throw();
  12288. /** Creates a point from an (x, y) position. */
  12289. Point (const float x, const float y) throw();
  12290. /** Copies this point from another one.
  12291. @see setXY
  12292. */
  12293. const Point& operator= (const Point& other) throw();
  12294. /** Destructor. */
  12295. ~Point() throw();
  12296. /** Returns the point's x co-ordinate. */
  12297. inline float getX() const throw() { return x; }
  12298. /** Returns the point's y co-ordinate. */
  12299. inline float getY() const throw() { return y; }
  12300. /** Changes the point's x and y co-ordinates. */
  12301. void setXY (const float x,
  12302. const float y) throw();
  12303. /** Uses a transform to change the point's co-ordinates.
  12304. @see AffineTransform::transformPoint
  12305. */
  12306. void applyTransform (const AffineTransform& transform) throw();
  12307. juce_UseDebuggingNewOperator
  12308. private:
  12309. float x, y;
  12310. };
  12311. #endif // __JUCE_POINT_JUCEHEADER__
  12312. /********* End of inlined file: juce_Point.h *********/
  12313. /********* Start of inlined file: juce_Justification.h *********/
  12314. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12315. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12316. /**
  12317. Represents a type of justification to be used when positioning graphical items.
  12318. e.g. it indicates whether something should be placed top-left, top-right,
  12319. centred, etc.
  12320. It is used in various places wherever this kind of information is needed.
  12321. */
  12322. class JUCE_API Justification
  12323. {
  12324. public:
  12325. /** Creates a Justification object using a combination of flags. */
  12326. inline Justification (const int flags_) throw() : flags (flags_) {}
  12327. /** Creates a copy of another Justification object. */
  12328. Justification (const Justification& other) throw();
  12329. /** Copies another Justification object. */
  12330. const Justification& operator= (const Justification& other) throw();
  12331. /** Returns the raw flags that are set for this Justification object. */
  12332. inline int getFlags() const throw() { return flags; }
  12333. /** Tests a set of flags for this object.
  12334. @returns true if any of the flags passed in are set on this object.
  12335. */
  12336. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12337. /** Returns just the flags from this object that deal with vertical layout. */
  12338. int getOnlyVerticalFlags() const throw();
  12339. /** Returns just the flags from this object that deal with horizontal layout. */
  12340. int getOnlyHorizontalFlags() const throw();
  12341. /** Adjusts the position of a rectangle to fit it into a space.
  12342. The (x, y) position of the rectangle will be updated to position it inside the
  12343. given space according to the justification flags.
  12344. */
  12345. void applyToRectangle (int& x, int& y,
  12346. const int w, const int h,
  12347. const int spaceX, const int spaceY,
  12348. const int spaceW, const int spaceH) const throw();
  12349. /** Flag values that can be combined and used in the constructor. */
  12350. enum
  12351. {
  12352. /** Indicates that the item should be aligned against the left edge of the available space. */
  12353. left = 1,
  12354. /** Indicates that the item should be aligned against the right edge of the available space. */
  12355. right = 2,
  12356. /** Indicates that the item should be placed in the centre between the left and right
  12357. sides of the available space. */
  12358. horizontallyCentred = 4,
  12359. /** Indicates that the item should be aligned against the top edge of the available space. */
  12360. top = 8,
  12361. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12362. bottom = 16,
  12363. /** Indicates that the item should be placed in the centre between the top and bottom
  12364. sides of the available space. */
  12365. verticallyCentred = 32,
  12366. /** Indicates that lines of text should be spread out to fill the maximum width
  12367. available, so that both margins are aligned vertically.
  12368. */
  12369. horizontallyJustified = 64,
  12370. /** Indicates that the item should be centred vertically and horizontally.
  12371. This is equivalent to (horizontallyCentred | verticallyCentred)
  12372. */
  12373. centred = 36,
  12374. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12375. This is equivalent to (left | verticallyCentred)
  12376. */
  12377. centredLeft = 33,
  12378. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12379. This is equivalent to (right | verticallyCentred)
  12380. */
  12381. centredRight = 34,
  12382. /** Indicates that the item should be centred horizontally and placed at the top.
  12383. This is equivalent to (horizontallyCentred | top)
  12384. */
  12385. centredTop = 12,
  12386. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12387. This is equivalent to (horizontallyCentred | bottom)
  12388. */
  12389. centredBottom = 20,
  12390. /** Indicates that the item should be placed in the top-left corner.
  12391. This is equivalent to (left | top)
  12392. */
  12393. topLeft = 9,
  12394. /** Indicates that the item should be placed in the top-right corner.
  12395. This is equivalent to (right | top)
  12396. */
  12397. topRight = 10,
  12398. /** Indicates that the item should be placed in the bottom-left corner.
  12399. This is equivalent to (left | bottom)
  12400. */
  12401. bottomLeft = 17,
  12402. /** Indicates that the item should be placed in the bottom-left corner.
  12403. This is equivalent to (right | bottom)
  12404. */
  12405. bottomRight = 18
  12406. };
  12407. private:
  12408. int flags;
  12409. };
  12410. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12411. /********* End of inlined file: juce_Justification.h *********/
  12412. /**
  12413. A path is a sequence of lines and curves that may either form a closed shape
  12414. or be open-ended.
  12415. To use a path, you can create an empty one, then add lines and curves to it
  12416. to create shapes, then it can be rendered by a Graphics context or used
  12417. for geometric operations.
  12418. e.g. @code
  12419. Path myPath;
  12420. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12421. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12422. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12423. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12424. // add an ellipse as well, which will form a second sub-path within the path..
  12425. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12426. // double the width of the whole thing..
  12427. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12428. // and draw it to a graphics context with a 5-pixel thick outline.
  12429. g.strokePath (myPath, PathStrokeType (5.0f));
  12430. @endcode
  12431. A path object can actually contain multiple sub-paths, which may themselves
  12432. be open or closed.
  12433. @see PathFlatteningIterator, PathStrokeType, Graphics
  12434. */
  12435. class JUCE_API Path : private ArrayAllocationBase <float>
  12436. {
  12437. public:
  12438. /** Creates an empty path. */
  12439. Path() throw();
  12440. /** Creates a copy of another path. */
  12441. Path (const Path& other) throw();
  12442. /** Destructor. */
  12443. ~Path() throw();
  12444. /** Copies this path from another one. */
  12445. const Path& operator= (const Path& other) throw();
  12446. /** Returns true if the path doesn't contain any lines or curves. */
  12447. bool isEmpty() const throw();
  12448. /** Returns the smallest rectangle that contains all points within the path.
  12449. */
  12450. void getBounds (float& x, float& y,
  12451. float& w, float& h) const throw();
  12452. /** Returns the smallest rectangle that contains all points within the path
  12453. after it's been transformed with the given tranasform matrix.
  12454. */
  12455. void getBoundsTransformed (const AffineTransform& transform,
  12456. float& x, float& y,
  12457. float& w, float& h) const throw();
  12458. /** Checks whether a point lies within the path.
  12459. This is only relevent for closed paths (see closeSubPath()), and
  12460. may produce false results if used on a path which has open sub-paths.
  12461. The path's winding rule is taken into account by this method.
  12462. The tolerence parameter is passed to the PathFlatteningIterator that
  12463. is used to trace the path - for more info about it, see the notes for
  12464. the PathFlatteningIterator constructor.
  12465. @see closeSubPath, setUsingNonZeroWinding
  12466. */
  12467. bool contains (const float x,
  12468. const float y,
  12469. const float tolerence = 10.0f) const throw();
  12470. /** Checks whether a line crosses the path.
  12471. This will return positive if the line crosses any of the paths constituent
  12472. lines or curves. It doesn't take into account whether the line is inside
  12473. or outside the path, or whether the path is open or closed.
  12474. The tolerence parameter is passed to the PathFlatteningIterator that
  12475. is used to trace the path - for more info about it, see the notes for
  12476. the PathFlatteningIterator constructor.
  12477. */
  12478. bool intersectsLine (const float x1, const float y1,
  12479. const float x2, const float y2,
  12480. const float tolerence = 10.0f) throw();
  12481. /** Removes all lines and curves, resetting the path completely. */
  12482. void clear() throw();
  12483. /** Begins a new subpath with a given starting position.
  12484. This will move the path's current position to the co-ordinates passed in and
  12485. make it ready to draw lines or curves starting from this position.
  12486. After adding whatever lines and curves are needed, you can either
  12487. close the current sub-path using closeSubPath() or call startNewSubPath()
  12488. to move to a new sub-path, leaving the old one open-ended.
  12489. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12490. */
  12491. void startNewSubPath (const float startX,
  12492. const float startY) throw();
  12493. /** Closes a the current sub-path with a line back to its start-point.
  12494. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12495. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12496. to join the final point back to the start.
  12497. This ensures that closes shapes are recognised as such, and this is
  12498. important for tasks like drawing strokes, which needs to know whether to
  12499. draw end-caps or not.
  12500. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12501. */
  12502. void closeSubPath() throw();
  12503. /** Adds a line from the shape's last position to a new end-point.
  12504. This will connect the end-point of the last line or curve that was added
  12505. to a new point, using a straight line.
  12506. See the class description for an example of how to add lines and curves to a path.
  12507. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12508. */
  12509. void lineTo (const float endX,
  12510. const float endY) throw();
  12511. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12512. This will connect the end-point of the last line or curve that was added
  12513. to a new point, using a quadratic spline with one control-point.
  12514. See the class description for an example of how to add lines and curves to a path.
  12515. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12516. */
  12517. void quadraticTo (const float controlPointX,
  12518. const float controlPointY,
  12519. const float endPointX,
  12520. const float endPointY) throw();
  12521. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12522. This will connect the end-point of the last line or curve that was added
  12523. to a new point, using a cubic spline with two control-points.
  12524. See the class description for an example of how to add lines and curves to a path.
  12525. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12526. */
  12527. void cubicTo (const float controlPoint1X,
  12528. const float controlPoint1Y,
  12529. const float controlPoint2X,
  12530. const float controlPoint2Y,
  12531. const float endPointX,
  12532. const float endPointY) throw();
  12533. /** Returns the last point that was added to the path by one of the drawing methods.
  12534. */
  12535. const Point getCurrentPosition() const;
  12536. /** Adds a rectangle to the path.
  12537. The rectangle is added as a new sub-path. (Any currently open paths will be
  12538. left open).
  12539. @see addRoundedRectangle, addTriangle
  12540. */
  12541. void addRectangle (const float x, const float y,
  12542. const float w, const float h) throw();
  12543. /** Adds a rectangle with rounded corners to the path.
  12544. The rectangle is added as a new sub-path. (Any currently open paths will be
  12545. left open).
  12546. @see addRectangle, addTriangle
  12547. */
  12548. void addRoundedRectangle (const float x, const float y,
  12549. const float w, const float h,
  12550. float cornerSize) throw();
  12551. /** Adds a rectangle with rounded corners to the path.
  12552. The rectangle is added as a new sub-path. (Any currently open paths will be
  12553. left open).
  12554. @see addRectangle, addTriangle
  12555. */
  12556. void addRoundedRectangle (const float x, const float y,
  12557. const float w, const float h,
  12558. float cornerSizeX,
  12559. float cornerSizeY) throw();
  12560. /** Adds a triangle to the path.
  12561. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12562. left open).
  12563. Note that whether the vertices are specified in clockwise or anticlockwise
  12564. order will affect how the triangle is filled when it overlaps other
  12565. shapes (the winding order setting will affect this of course).
  12566. */
  12567. void addTriangle (const float x1, const float y1,
  12568. const float x2, const float y2,
  12569. const float x3, const float y3) throw();
  12570. /** Adds a quadrilateral to the path.
  12571. The quad is added as a new closed sub-path. (Any currently open paths will be
  12572. left open).
  12573. Note that whether the vertices are specified in clockwise or anticlockwise
  12574. order will affect how the quad is filled when it overlaps other
  12575. shapes (the winding order setting will affect this of course).
  12576. */
  12577. void addQuadrilateral (const float x1, const float y1,
  12578. const float x2, const float y2,
  12579. const float x3, const float y3,
  12580. const float x4, const float y4) throw();
  12581. /** Adds an ellipse to the path.
  12582. The shape is added as a new sub-path. (Any currently open paths will be
  12583. left open).
  12584. @see addArc
  12585. */
  12586. void addEllipse (const float x, const float y,
  12587. const float width, const float height) throw();
  12588. /** Adds an elliptical arc to the current path.
  12589. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12590. or anti-clockwise according to whether the end angle is greater than the start. This means
  12591. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12592. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12593. @param y the top edge of the rectangle in which the elliptical outline fits
  12594. @param width the width of the rectangle in which the elliptical outline fits
  12595. @param height the height of the rectangle in which the elliptical outline fits
  12596. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12597. top-centre of the ellipse)
  12598. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12599. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12600. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12601. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12602. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12603. it will be added to the current sub-path, continuing from the current postition
  12604. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12605. */
  12606. void addArc (const float x, const float y,
  12607. const float width, const float height,
  12608. const float fromRadians,
  12609. const float toRadians,
  12610. const bool startAsNewSubPath = false) throw();
  12611. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12612. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12613. or anti-clockwise according to whether the end angle is greater than the start. This means
  12614. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12615. @param centreX the centre x of the ellipse
  12616. @param centreY the centre y of the ellipse
  12617. @param radiusX the horizontal radius of the ellipse
  12618. @param radiusY the vertical radius of the ellipse
  12619. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12620. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12621. top-centre of the ellipse)
  12622. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12623. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12624. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12625. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12626. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12627. it will be added to the current sub-path, continuing from the current postition
  12628. @see addArc, arcTo
  12629. */
  12630. void addCentredArc (const float centreX, const float centreY,
  12631. const float radiusX, const float radiusY,
  12632. const float rotationOfEllipse,
  12633. const float fromRadians,
  12634. const float toRadians,
  12635. const bool startAsNewSubPath = false) throw();
  12636. /** Adds a "pie-chart" shape to the path.
  12637. The shape is added as a new sub-path. (Any currently open paths will be
  12638. left open).
  12639. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12640. or anti-clockwise according to whether the end angle is greater than the start. This means
  12641. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12642. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12643. @param y the top edge of the rectangle in which the elliptical outline fits
  12644. @param width the width of the rectangle in which the elliptical outline fits
  12645. @param height the height of the rectangle in which the elliptical outline fits
  12646. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12647. top-centre of the ellipse)
  12648. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12649. top-centre of the ellipse)
  12650. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12651. ellipse at its centre, where this value indicates the inner ellipse's size with
  12652. respect to the outer one.
  12653. @see addArc
  12654. */
  12655. void addPieSegment (const float x, const float y,
  12656. const float width, const float height,
  12657. const float fromRadians,
  12658. const float toRadians,
  12659. const float innerCircleProportionalSize);
  12660. /** Adds a line with a specified thickness.
  12661. The line is added as a new closed sub-path. (Any currently open paths will be
  12662. left open).
  12663. @see addArrow
  12664. */
  12665. void addLineSegment (const float startX, const float startY,
  12666. const float endX, const float endY,
  12667. float lineThickness) throw();
  12668. /** Adds a line with an arrowhead on the end.
  12669. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12670. left open).
  12671. */
  12672. void addArrow (const float startX, const float startY,
  12673. const float endX, const float endY,
  12674. float lineThickness,
  12675. float arrowheadWidth,
  12676. float arrowheadLength) throw();
  12677. /** Adds a star shape to the path.
  12678. */
  12679. void addStar (const float centreX,
  12680. const float centreY,
  12681. const int numberOfPoints,
  12682. const float innerRadius,
  12683. const float outerRadius,
  12684. const float startAngle = 0.0f);
  12685. /** Adds a speech-bubble shape to the path.
  12686. @param bodyX the left of the main body area of the bubble
  12687. @param bodyY the top of the main body area of the bubble
  12688. @param bodyW the width of the main body area of the bubble
  12689. @param bodyH the height of the main body area of the bubble
  12690. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12691. @param arrowTipX the x position that the tip of the arrow should connect to
  12692. @param arrowTipY the y position that the tip of the arrow should connect to
  12693. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12694. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12695. arrow's base should be - this is a proportional distance between 0 and 1.0
  12696. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12697. */
  12698. void addBubble (float bodyX, float bodyY,
  12699. float bodyW, float bodyH,
  12700. float cornerSize,
  12701. float arrowTipX,
  12702. float arrowTipY,
  12703. int whichSide,
  12704. float arrowPositionAlongEdgeProportional,
  12705. float arrowWidth);
  12706. /** Adds another path to this one.
  12707. The new path is added as a new sub-path. (Any currently open paths in this
  12708. path will be left open).
  12709. @param pathToAppend the path to add
  12710. */
  12711. void addPath (const Path& pathToAppend) throw();
  12712. /** Adds another path to this one, transforming it on the way in.
  12713. The new path is added as a new sub-path, its points being transformed by the given
  12714. matrix before being added.
  12715. @param pathToAppend the path to add
  12716. @param transformToApply an optional transform to apply to the incoming vertices
  12717. */
  12718. void addPath (const Path& pathToAppend,
  12719. const AffineTransform& transformToApply) throw();
  12720. /** Swaps the contents of this path with another one.
  12721. The internal data of the two paths is swapped over, so this is much faster than
  12722. copying it to a temp variable and back.
  12723. */
  12724. void swapWithPath (Path& other);
  12725. /** Applies a 2D transform to all the vertices in the path.
  12726. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12727. */
  12728. void applyTransform (const AffineTransform& transform) throw();
  12729. /** Rescales this path to make it fit neatly into a given space.
  12730. This is effectively a quick way of calling
  12731. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12732. @param x the x position of the rectangle to fit the path inside
  12733. @param y the y position of the rectangle to fit the path inside
  12734. @param width the width of the rectangle to fit the path inside
  12735. @param height the height of the rectangle to fit the path inside
  12736. @param preserveProportions if true, it will fit the path into the space without altering its
  12737. horizontal/vertical scale ratio; if false, it will distort the
  12738. path to fill the specified ratio both horizontally and vertically
  12739. @see applyTransform, getTransformToScaleToFit
  12740. */
  12741. void scaleToFit (const float x, const float y,
  12742. const float width, const float height,
  12743. const bool preserveProportions) throw();
  12744. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12745. @param x the x position of the rectangle to fit the path inside
  12746. @param y the y position of the rectangle to fit the path inside
  12747. @param width the width of the rectangle to fit the path inside
  12748. @param height the height of the rectangle to fit the path inside
  12749. @param preserveProportions if true, it will fit the path into the space without altering its
  12750. horizontal/vertical scale ratio; if false, it will distort the
  12751. path to fill the specified ratio both horizontally and vertically
  12752. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12753. than the available rectangle, so this describes how it should be
  12754. positioned within the space.
  12755. @returns an appropriate transformation
  12756. @see applyTransform, scaleToFit
  12757. */
  12758. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12759. const float width, const float height,
  12760. const bool preserveProportions,
  12761. const Justification& justificationType = Justification::centred) const throw();
  12762. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12763. Wherever two lines meet at an angle, this will replace the corner with a curve
  12764. of the given radius.
  12765. */
  12766. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12767. /** Changes the winding-rule to be used when filling the path.
  12768. If set to true (which is the default), then the path uses a non-zero-winding rule
  12769. to determine which points are inside the path. If set to false, it uses an
  12770. alternate-winding rule.
  12771. The winding-rule comes into play when areas of the shape overlap other
  12772. areas, and determines whether the overlapping regions are considered to be
  12773. inside or outside.
  12774. Changing this value just sets a flag - it doesn't affect the contents of the
  12775. path.
  12776. @see isUsingNonZeroWinding
  12777. */
  12778. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12779. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12780. The default for a new path is true.
  12781. @see setUsingNonZeroWinding
  12782. */
  12783. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12784. /** Iterates the lines and curves that a path contains.
  12785. @see Path, PathFlatteningIterator
  12786. */
  12787. class JUCE_API Iterator
  12788. {
  12789. public:
  12790. Iterator (const Path& path);
  12791. ~Iterator();
  12792. /** Moves onto the next element in the path.
  12793. If this returns false, there are no more elements. If it returns true,
  12794. the elementType variable will be set to the type of the current element,
  12795. and some of the x and y variables will be filled in with values.
  12796. */
  12797. bool next();
  12798. enum PathElementType
  12799. {
  12800. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12801. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12802. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12803. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12804. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12805. };
  12806. PathElementType elementType;
  12807. float x1, y1, x2, y2, x3, y3;
  12808. private:
  12809. const Path& path;
  12810. int index;
  12811. Iterator (const Iterator&);
  12812. const Iterator& operator= (const Iterator&);
  12813. };
  12814. /** Loads a stored path from a data stream.
  12815. The data in the stream must have been written using writePathToStream().
  12816. Note that this will append the stored path to whatever is currently in
  12817. this path, so you might need to call clear() beforehand.
  12818. @see loadPathFromData, writePathToStream
  12819. */
  12820. void loadPathFromStream (InputStream& source);
  12821. /** Loads a stored path from a block of data.
  12822. This is similar to loadPathFromStream(), but just reads from a block
  12823. of data. Useful if you're including stored shapes in your code as a
  12824. block of static data.
  12825. @see loadPathFromStream, writePathToStream
  12826. */
  12827. void loadPathFromData (const unsigned char* const data,
  12828. const int numberOfBytes) throw();
  12829. /** Stores the path by writing it out to a stream.
  12830. After writing out a path, you can reload it using loadPathFromStream().
  12831. @see loadPathFromStream, loadPathFromData
  12832. */
  12833. void writePathToStream (OutputStream& destination) const;
  12834. /** Creates a string containing a textual representation of this path.
  12835. @see restoreFromString
  12836. */
  12837. const String toString() const;
  12838. /** Restores this path from a string that was created with the toString() method.
  12839. @see toString()
  12840. */
  12841. void restoreFromString (const String& stringVersion);
  12842. juce_UseDebuggingNewOperator
  12843. private:
  12844. friend class PathFlatteningIterator;
  12845. friend class Path::Iterator;
  12846. int numElements;
  12847. float pathXMin, pathXMax, pathYMin, pathYMax;
  12848. bool useNonZeroWinding;
  12849. static const float lineMarker;
  12850. static const float moveMarker;
  12851. static const float quadMarker;
  12852. static const float cubicMarker;
  12853. static const float closeSubPathMarker;
  12854. };
  12855. #endif // __JUCE_PATH_JUCEHEADER__
  12856. /********* End of inlined file: juce_Path.h *********/
  12857. class Font;
  12858. class Typeface;
  12859. /**
  12860. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12861. @see Typeface, PositionedGlyph, GlyphArrangement
  12862. */
  12863. class JUCE_API TypefaceGlyphInfo
  12864. {
  12865. public:
  12866. /** Returns the path that describes the glyph's outline.
  12867. This is normalised to a height of 1.0, and its origin is the
  12868. left-hand edge of the glyph's baseline.
  12869. */
  12870. const Path& getPath() const throw() { return path; }
  12871. /** Returns the unicode character that this glyph represents. */
  12872. juce_wchar getCharacter() const throw() { return character; }
  12873. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12874. /** Returns the distance to leave between this and a following character.
  12875. The value returned is expressed as a proportion of the font's height.
  12876. */
  12877. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12878. /** Returns the typeface that this glyph belongs to. */
  12879. Typeface* getTypeface() const throw() { return typeface; }
  12880. private:
  12881. friend class Typeface;
  12882. struct KerningPair
  12883. {
  12884. juce_wchar character2;
  12885. float kerningAmount;
  12886. };
  12887. const juce_wchar character;
  12888. const Path path;
  12889. float width;
  12890. MemoryBlock kerningPairs;
  12891. Typeface* const typeface;
  12892. TypefaceGlyphInfo (const juce_wchar character,
  12893. const Path& shape,
  12894. const float horizontalSeparation,
  12895. Typeface* const typeface) throw();
  12896. ~TypefaceGlyphInfo() throw();
  12897. KerningPair& getKerningPair (const int index) const throw();
  12898. int getNumKerningPairs() const throw();
  12899. void addKerningPair (const juce_wchar subsequentCharacter,
  12900. const float extraKerningAmount) throw();
  12901. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12902. };
  12903. /**
  12904. Represents a size-independent system font.
  12905. A Font object represents a particular Typeface along with a specific size,
  12906. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12907. of the shapes of the glyphs and their properties.
  12908. */
  12909. class JUCE_API Typeface : public ReferenceCountedObject
  12910. {
  12911. public:
  12912. /** Tries to load a named system font and to initialise all the glyphs
  12913. appropriately from it.
  12914. @param faceName the name of the typeface, e.g. "Times"
  12915. @param bold whether to try to find a bold version of the font (may not always be available)
  12916. @param italic whether to try to find an italicised version of the font (may not always be available)
  12917. */
  12918. Typeface (const String& faceName,
  12919. const bool bold,
  12920. const bool italic);
  12921. /** Creates a copy of another typeface */
  12922. Typeface (const Typeface& other);
  12923. /** Destructor. */
  12924. ~Typeface();
  12925. /** Copies another typeface over this one. */
  12926. const Typeface& operator= (const Typeface& other) throw();
  12927. /** Returns a unique ID for the typeface.
  12928. This is based on the name and style, so can be used to compare two Typeface objects.
  12929. */
  12930. int hashCode() const throw() { return hash; }
  12931. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12932. const String& getName() const throw() { return typefaceName; }
  12933. /** Returns the font's ascent as a proportion of its height. */
  12934. float getAscent() const throw() { return ascent; }
  12935. /** Returns true if the font is flagged as being bold. */
  12936. bool isBold() const throw() { return bold; }
  12937. /** Returns true if the typeface's 'italic' flag is set. */
  12938. bool isItalic() const throw() { return italic; }
  12939. /** Finds the Path that describes the outline shape of a character.
  12940. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12941. height of the font).
  12942. This may return 0 if the typeface has no characters, but if the character
  12943. that is asked for is not found, it will first try to return a default
  12944. character instead.
  12945. */
  12946. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12947. /** Tries to find the information describing a glyph for this character.
  12948. If there isn't a glyph specifically for the character it will return
  12949. a default glyph instead; if the typeface is empty, it may return a null
  12950. pointer.
  12951. */
  12952. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12953. /** Deletes all the glyphs and kerning data fom the typeface. */
  12954. void clear() throw();
  12955. /** Adds a glyph to the typeface.
  12956. This is typically only called by the platform-specific code that generates
  12957. the typeface from a system font.
  12958. */
  12959. void addGlyph (const juce_wchar character,
  12960. const Path& path,
  12961. const float horizontalSpacing) throw();
  12962. /** Adds a kerning distance to the typeface.
  12963. The extra amount passed in is expressed as a proportion of the font's
  12964. height, normalised to 1.0.
  12965. This is typically only called by the platform-specific code that generates
  12966. the typeface from a system font.
  12967. */
  12968. void addKerningPair (const juce_wchar firstChar,
  12969. const juce_wchar secondChar,
  12970. const float extraAmount) throw();
  12971. /** Sets the typeface's name.
  12972. This is typically only called by the platform-specific code that generates
  12973. the typeface from a system font. Calling this method won't actually affect
  12974. the underlying font being used.
  12975. */
  12976. void setName (const String& name) throw();
  12977. /** Sets the font's ascent value, as a proportion of the font height.
  12978. This is typically only called by the platform-specific code that generates
  12979. the typeface from a system font.
  12980. */
  12981. void setAscent (const float newAscent) throw();
  12982. /** Sets the typeface's 'bold' flag.
  12983. This is typically only called by the platform-specific code that generates
  12984. the typeface from a system font.
  12985. */
  12986. void setBold (const bool shouldBeBold) throw();
  12987. /** Sets the typeface's 'italic' flag.
  12988. This is typically only called by the platform-specific code that generates
  12989. the typeface from a system font.
  12990. */
  12991. void setItalic (const bool shouldBeItalic) throw();
  12992. /** Changes the character index to use as the default character.
  12993. This is the character that gets returned for characters which don't have a
  12994. glyph set for them.
  12995. */
  12996. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12997. /** Creates a typeface from data created using Typeface::serialise().
  12998. This will attempt to load a compressed typeface that was created using
  12999. the Typeface::serialise() method. This is handy if you want to store
  13000. a typeface in your application as a binary blob, and use it without
  13001. having to actually install it on the computer.
  13002. @see Typeface::serialise()
  13003. */
  13004. Typeface (InputStream& serialisedTypefaceStream);
  13005. /** Writes the typeface to a stream (using a proprietary format).
  13006. This lets you save a typeface and reload it using the
  13007. Typeface::Typeface (InputStream&) constructor. The data's saved in
  13008. a compressed format.
  13009. @see Typeface::Typeface (InputStream&)
  13010. */
  13011. void serialise (OutputStream& outputStream);
  13012. /** A name that represents the default sans-serif typeface name.
  13013. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13014. is a generic string that represents whatever that font is, such as "DefaultSans".
  13015. If you try to create a typeface with this name, the global default LookAndFeel
  13016. object will be asked to provide an appropriate typeface.
  13017. */
  13018. static const tchar* defaultTypefaceNameSans;
  13019. /** A name that represents the default serif typeface name.
  13020. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13021. is a generic string that represents it, such as "DefaultSans".
  13022. If you try to create a typeface with this name, the global default LookAndFeel
  13023. object will be asked to provide an appropriate typeface.
  13024. */
  13025. static const tchar* defaultTypefaceNameSerif;
  13026. /** A name that represents the default monospaced typeface name.
  13027. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13028. is a generic string that represents it, such as "DefaultSans".
  13029. If you try to create a typeface with this name, the global default LookAndFeel
  13030. object will be asked to provide an appropriate typeface.
  13031. */
  13032. static const tchar* defaultTypefaceNameMono;
  13033. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  13034. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  13035. juce_UseDebuggingNewOperator
  13036. private:
  13037. VoidArray glyphs;
  13038. short lookupTable [128];
  13039. String typefaceName;
  13040. int hash;
  13041. float ascent; // as a proportion of the height
  13042. bool bold, italic, isFullyPopulated;
  13043. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  13044. Typeface() throw();
  13045. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  13046. friend class Font;
  13047. friend class TypefaceCache;
  13048. friend class FontGlyphAlphaMap;
  13049. static const Ptr getTypefaceFor (const Font& font) throw();
  13050. // this is a platform-dependent method that will look for the given typeface
  13051. // and set up its kerning tables, etc. accordingly.
  13052. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  13053. // to the typeface immediately, rather than having to add them later on-demand.
  13054. void initialiseTypefaceCharacteristics (const String& fontName,
  13055. bool bold, bool italic,
  13056. bool addAllGlyphsToFont) throw();
  13057. // platform-specific routine to look up and add a glyph to this typeface
  13058. bool findAndAddSystemGlyph (juce_wchar character) throw();
  13059. void updateHashCode() throw();
  13060. friend class LookAndFeel;
  13061. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13062. };
  13063. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  13064. /********* End of inlined file: juce_Typeface.h *********/
  13065. /**
  13066. Represents a particular font, including its size, style, etc.
  13067. Apart from the typeface to be used, a Font object also dictates whether
  13068. the font is bold, italic, underlined, how big it is, and its kerning and
  13069. horizontal scale factor.
  13070. @see Typeface
  13071. */
  13072. class JUCE_API Font
  13073. {
  13074. public:
  13075. /** A combination of these values is used by the constructor to specify the
  13076. style of font to use.
  13077. */
  13078. enum FontStyleFlags
  13079. {
  13080. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  13081. bold = 1, /**< boldens the font. @see setStyleFlags */
  13082. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  13083. underlined = 4 /**< underlines the font. @see setStyleFlags */
  13084. };
  13085. /** Creates a sans-serif font in a given size.
  13086. @param fontHeight the height in pixels (can be fractional)
  13087. @param styleFlags the style to use - this can be a combination of the
  13088. Font::bold, Font::italic and Font::underlined, or
  13089. just Font::plain for the normal style.
  13090. @see FontStyleFlags, getDefaultSansSerifFontName
  13091. */
  13092. Font (const float fontHeight,
  13093. const int styleFlags = plain) throw();
  13094. /** Creates a font with a given typeface and parameters.
  13095. @param typefaceName the name of the typeface to use
  13096. @param fontHeight the height in pixels (can be fractional)
  13097. @param styleFlags the style to use - this can be a combination of the
  13098. Font::bold, Font::italic and Font::underlined, or
  13099. just Font::plain for the normal style.
  13100. @see FontStyleFlags, getDefaultSansSerifFontName
  13101. */
  13102. Font (const String& typefaceName,
  13103. const float fontHeight,
  13104. const int styleFlags) throw();
  13105. /** Creates a copy of another Font object. */
  13106. Font (const Font& other) throw();
  13107. /** Creates a font based on a typeface.
  13108. The font object stores its own internal copy of the typeface, so you can safely
  13109. delete the one passed in after calling this.
  13110. */
  13111. Font (const Typeface& typeface) throw();
  13112. /** Creates a basic sans-serif font at a default height.
  13113. You should use one of the other constructors for creating a font that you're planning
  13114. on drawing with - this constructor is here to help initialise objects before changing
  13115. the font's settings later.
  13116. */
  13117. Font() throw();
  13118. /** Copies this font from another one. */
  13119. const Font& operator= (const Font& other) throw();
  13120. bool operator== (const Font& other) const throw();
  13121. bool operator!= (const Font& other) const throw();
  13122. /** Destructor. */
  13123. ~Font() throw();
  13124. /** Changes the name of the typeface family.
  13125. e.g. "Arial", "Courier", etc.
  13126. This may also be set to Typeface::defaultTypefaceNameSans, Typeface::defaultTypefaceNameSerif,
  13127. or Typeface::defaultTypefaceNameMono, which are not actual platform-specific font names, but
  13128. are generic names that are used to represent the various default fonts.
  13129. If a suitable font isn't found on the machine, it'll just use a default instead.
  13130. */
  13131. void setTypefaceName (const String& faceName) throw();
  13132. /** Returns the name of the typeface family that this font uses.
  13133. e.g. "Arial", "Courier", etc.
  13134. Note that this may also be one of the values: Typeface::defaultTypefaceNameSans,
  13135. Typeface::defaultTypefaceNameSerif, or Typeface::defaultTypefaceNameMono, which are not actual
  13136. platform-specific font names, but are generic names that are used to represent the various
  13137. default fonts. If you need to know the exact typeface name being used, you can call
  13138. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  13139. */
  13140. const String& getTypefaceName() const throw() { return typefaceName; }
  13141. /** Returns a typeface name that represents the default sans-serif font.
  13142. This is also the typeface that will be used when a font is created without
  13143. specifying any typeface details.
  13144. Note that this method just returns the same value as Typeface::defaultTypefaceNameSans,
  13145. which is a generic placeholder string, and not a platform-specific font name.
  13146. @see Typeface::defaultTypefaceNameSans, setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  13147. */
  13148. static const String getDefaultSansSerifFontName() throw() { return Typeface::defaultTypefaceNameSans; }
  13149. /** Returns a typeface name that represents the default sans-serif font.
  13150. Note that this method just returns the same value as Typeface::defaultTypefaceNameSerif,
  13151. which is a generic placeholder string, and not a platform-specific font name.
  13152. @see Typeface::defaultTypefaceNameSerif, setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13153. */
  13154. static const String getDefaultSerifFontName() throw() { return Typeface::defaultTypefaceNameSerif; }
  13155. /** Returns a typeface name that represents the default sans-serif font.
  13156. Note that this method just returns the same value as Typeface::defaultTypefaceNameMono,
  13157. which is a generic placeholder string, and not a platform-specific font name.
  13158. @see Typeface::defaultTypefaceNameMono, setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13159. */
  13160. static const String getDefaultMonospacedFontName() throw() { return Typeface::defaultTypefaceNameMono; }
  13161. /** Returns the total height of this font.
  13162. This is the maximum height, from the top of the ascent to the bottom of the
  13163. descenders.
  13164. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13165. */
  13166. float getHeight() const throw() { return height; }
  13167. /** Changes the font's height.
  13168. @see getHeight, setHeightWithoutChangingWidth
  13169. */
  13170. void setHeight (float newHeight) throw();
  13171. /** Changes the font's height without changing its width.
  13172. This alters the horizontal scale to compensate for the change in height.
  13173. */
  13174. void setHeightWithoutChangingWidth (float newHeight) throw();
  13175. /** Returns the height of the font above its baseline.
  13176. This is the maximum height from the baseline to the top.
  13177. @see getHeight, getDescent
  13178. */
  13179. float getAscent() const throw();
  13180. /** Returns the amount that the font descends below its baseline.
  13181. This is calculated as (getHeight() - getAscent()).
  13182. @see getAscent, getHeight
  13183. */
  13184. float getDescent() const throw();
  13185. /** Returns the font's style flags.
  13186. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13187. enum, to describe whether the font is bold, italic, etc.
  13188. @see FontStyleFlags
  13189. */
  13190. int getStyleFlags() const throw() { return styleFlags; }
  13191. /** Changes the font's style.
  13192. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13193. enum, to set the font's properties
  13194. @see FontStyleFlags
  13195. */
  13196. void setStyleFlags (const int newFlags) throw();
  13197. /** Makes the font bold or non-bold. */
  13198. void setBold (const bool shouldBeBold) throw();
  13199. /** Returns true if the font is bold. */
  13200. bool isBold() const throw();
  13201. /** Makes the font italic or non-italic. */
  13202. void setItalic (const bool shouldBeItalic) throw();
  13203. /** Returns true if the font is italic. */
  13204. bool isItalic() const throw();
  13205. /** Makes the font underlined or non-underlined. */
  13206. void setUnderline (const bool shouldBeUnderlined) throw();
  13207. /** Returns true if the font is underlined. */
  13208. bool isUnderlined() const throw();
  13209. /** Changes the font's horizontal scale factor.
  13210. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13211. narrower, greater than 1.0 will be stretched out.
  13212. */
  13213. void setHorizontalScale (const float scaleFactor) throw();
  13214. /** Returns the font's horizontal scale.
  13215. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13216. than 1.0 will be stretched out.
  13217. @see setHorizontalScale
  13218. */
  13219. float getHorizontalScale() const throw() { return horizontalScale; }
  13220. /** Changes the font's kerning.
  13221. @param extraKerning a multiple of the font's height that will be added
  13222. to space between the characters. So a value of zero is
  13223. normal spacing, positive values spread the letters out,
  13224. negative values make them closer together.
  13225. */
  13226. void setExtraKerningFactor (const float extraKerning) throw();
  13227. /** Returns the font's kerning.
  13228. This is the extra space added between adjacent characters, as a proportion
  13229. of the font's height.
  13230. A value of zero is normal spacing, positive values will spread the letters
  13231. out more, and negative values make them closer together.
  13232. */
  13233. float getExtraKerningFactor() const throw() { return kerning; }
  13234. /** Changes all the font's characteristics with one call. */
  13235. void setSizeAndStyle (const float newHeight,
  13236. const int newStyleFlags,
  13237. const float newHorizontalScale,
  13238. const float newKerningAmount) throw();
  13239. /** Resets this font's characteristics.
  13240. This is basically like saying "myFont = Font();", because it resets the
  13241. typeface, size, style, etc to a default state. Not very useful to most
  13242. people, its raison d'etre is to help the Graphics class be more efficient.
  13243. */
  13244. void resetToDefaultState() throw();
  13245. /** Returns the total width of a string as it would be drawn using this font.
  13246. For a more accurate floating-point result, use getStringWidthFloat().
  13247. */
  13248. int getStringWidth (const String& text) const throw();
  13249. /** Returns the total width of a string as it would be drawn using this font.
  13250. @see getStringWidth
  13251. */
  13252. float getStringWidthFloat (const String& text) const throw();
  13253. /** Returns the typeface used by this font.
  13254. Note that the object returned may go out of scope if this font is deleted
  13255. or has its style changed.
  13256. */
  13257. Typeface* getTypeface() const throw();
  13258. /** Creates an array of Font objects to represent all the fonts on the system.
  13259. If you just need the names of the typefaces, you can also use
  13260. findAllTypefaceNames() instead.
  13261. @param results the array to which new Font objects will be added.
  13262. */
  13263. static void findFonts (OwnedArray<Font>& results) throw();
  13264. /** Returns a list of all the available typeface names.
  13265. The names returned can be passed into setTypefaceName().
  13266. You can use this instead of findFonts() if you only need their names, and not
  13267. font objects.
  13268. */
  13269. static const StringArray findAllTypefaceNames() throw();
  13270. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13271. in the requested typeface.
  13272. */
  13273. static const String getFallbackFontName() throw();
  13274. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13275. available in whatever font you're trying to use.
  13276. */
  13277. static void setFallbackFontName (const String& name) throw();
  13278. juce_UseDebuggingNewOperator
  13279. private:
  13280. friend class FontGlyphAlphaMap;
  13281. friend class TypefaceCache;
  13282. String typefaceName;
  13283. float height, horizontalScale, kerning;
  13284. mutable float ascent;
  13285. int styleFlags;
  13286. mutable Typeface::Ptr typeface;
  13287. };
  13288. #endif // __JUCE_FONT_JUCEHEADER__
  13289. /********* End of inlined file: juce_Font.h *********/
  13290. /********* Start of inlined file: juce_Rectangle.h *********/
  13291. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13292. #define __JUCE_RECTANGLE_JUCEHEADER__
  13293. /**
  13294. A rectangle, specified using integer co-ordinates.
  13295. @see RectangleList, Path, Line, Point
  13296. */
  13297. class JUCE_API Rectangle
  13298. {
  13299. public:
  13300. /** Creates a rectangle of zero size.
  13301. The default co-ordinates will be (0, 0, 0, 0).
  13302. */
  13303. Rectangle() throw();
  13304. /** Creates a copy of another rectangle. */
  13305. Rectangle (const Rectangle& other) throw();
  13306. /** Creates a rectangle with a given position and size. */
  13307. Rectangle (const int x, const int y,
  13308. const int width, const int height) throw();
  13309. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13310. Rectangle (const int width, const int height) throw();
  13311. /** Destructor. */
  13312. ~Rectangle() throw();
  13313. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13314. inline int getX() const throw() { return x; }
  13315. /** Returns the y co-ordinate of the rectangle's top edge. */
  13316. inline int getY() const throw() { return y; }
  13317. /** Returns the width of the rectangle. */
  13318. inline int getWidth() const throw() { return w; }
  13319. /** Returns the height of the rectangle. */
  13320. inline int getHeight() const throw() { return h; }
  13321. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13322. inline int getRight() const throw() { return x + w; }
  13323. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13324. inline int getBottom() const throw() { return y + h; }
  13325. /** Returns the x co-ordinate of the rectangle's centre. */
  13326. inline int getCentreX() const throw() { return x + (w >> 1); }
  13327. /** Returns the y co-ordinate of the rectangle's centre. */
  13328. inline int getCentreY() const throw() { return y + (h >> 1); }
  13329. /** Returns true if the rectangle's width and height are both zero or less */
  13330. bool isEmpty() const throw();
  13331. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13332. void setPosition (const int x, const int y) throw();
  13333. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13334. void setSize (const int w, const int h) throw();
  13335. /** Changes all the rectangle's co-ordinates. */
  13336. void setBounds (const int newX, const int newY,
  13337. const int newWidth, const int newHeight) throw();
  13338. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  13339. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  13340. */
  13341. void setLeft (const int newLeft) throw();
  13342. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  13343. If the y is moved to be below the current bottom edge, the height will be set to zero.
  13344. */
  13345. void setTop (const int newTop) throw();
  13346. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  13347. If the new right is below the current X value, the X will be pushed down to match it.
  13348. @see getRight
  13349. */
  13350. void setRight (const int newRight) throw();
  13351. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  13352. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  13353. @see getBottom
  13354. */
  13355. void setBottom (const int newBottom) throw();
  13356. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13357. void translate (const int deltaX,
  13358. const int deltaY) throw();
  13359. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13360. const Rectangle translated (const int deltaX,
  13361. const int deltaY) const throw();
  13362. /** Expands the rectangle by a given amount.
  13363. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13364. @see expanded, reduce, reduced
  13365. */
  13366. void expand (const int deltaX,
  13367. const int deltaY) throw();
  13368. /** Returns a rectangle that is larger than this one by a given amount.
  13369. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13370. @see expand, reduce, reduced
  13371. */
  13372. const Rectangle expanded (const int deltaX,
  13373. const int deltaY) const throw();
  13374. /** Shrinks the rectangle by a given amount.
  13375. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13376. @see reduced, expand, expanded
  13377. */
  13378. void reduce (const int deltaX,
  13379. const int deltaY) throw();
  13380. /** Returns a rectangle that is smaller than this one by a given amount.
  13381. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13382. @see reduce, expand, expanded
  13383. */
  13384. const Rectangle reduced (const int deltaX,
  13385. const int deltaY) const throw();
  13386. /** Returns true if the two rectangles are identical. */
  13387. bool operator== (const Rectangle& other) const throw();
  13388. /** Returns true if the two rectangles are not identical. */
  13389. bool operator!= (const Rectangle& other) const throw();
  13390. /** Returns true if this co-ordinate is inside the rectangle. */
  13391. bool contains (const int x, const int y) const throw();
  13392. /** Returns true if this other rectangle is completely inside this one. */
  13393. bool contains (const Rectangle& other) const throw();
  13394. /** Returns true if any part of another rectangle overlaps this one. */
  13395. bool intersects (const Rectangle& other) const throw();
  13396. /** Returns the region that is the overlap between this and another rectangle.
  13397. If the two rectangles don't overlap, the rectangle returned will be empty.
  13398. */
  13399. const Rectangle getIntersection (const Rectangle& other) const throw();
  13400. /** Clips a rectangle so that it lies only within this one.
  13401. This is a non-static version of intersectRectangles().
  13402. Returns false if the two regions didn't overlap.
  13403. */
  13404. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13405. /** Returns the smallest rectangle that contains both this one and the one
  13406. passed-in.
  13407. */
  13408. const Rectangle getUnion (const Rectangle& other) const throw();
  13409. /** If this rectangle merged with another one results in a simple rectangle, this
  13410. will set this rectangle to the result, and return true.
  13411. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13412. or if they form a complex region.
  13413. */
  13414. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13415. /** If after removing another rectangle from this one the result is a simple rectangle,
  13416. this will set this object's bounds to be the result, and return true.
  13417. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13418. or if removing the other one would form a complex region.
  13419. */
  13420. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13421. /** Static utility to intersect two sets of rectangular co-ordinates.
  13422. Returns false if the two regions didn't overlap.
  13423. @see intersectRectangle
  13424. */
  13425. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13426. int x2, int y2, int w2, int h2) throw();
  13427. /** Creates a string describing this rectangle.
  13428. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13429. Coupled with the fromString() method, this is very handy for things like
  13430. storing rectangles (particularly component positions) in XML attributes.
  13431. @see fromString
  13432. */
  13433. const String toString() const throw();
  13434. /** Parses a string containing a rectangle's details.
  13435. The string should contain 4 integer tokens, in the form "x y width height". They
  13436. can be comma or whitespace separated.
  13437. This method is intended to go with the toString() method, to form an easy way
  13438. of saving/loading rectangles as strings.
  13439. @see toString
  13440. */
  13441. static const Rectangle fromString (const String& stringVersion);
  13442. juce_UseDebuggingNewOperator
  13443. private:
  13444. friend class RectangleList;
  13445. int x, y, w, h;
  13446. };
  13447. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13448. /********* End of inlined file: juce_Rectangle.h *********/
  13449. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13450. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13451. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13452. /**
  13453. Describes a type of stroke used to render a solid outline along a path.
  13454. A PathStrokeType object can be used directly to create the shape of an outline
  13455. around a path, and is used by Graphics::strokePath to specify the type of
  13456. stroke to draw.
  13457. @see Path, Graphics::strokePath
  13458. */
  13459. class JUCE_API PathStrokeType
  13460. {
  13461. public:
  13462. /** The type of shape to use for the corners between two adjacent line segments. */
  13463. enum JointStyle
  13464. {
  13465. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13466. Note that for angles that curve back on themselves, drawing a
  13467. mitre could require extending the point too far away from the
  13468. path, so a mitre limit is imposed and any corners that exceed it
  13469. are drawn as bevelled instead. */
  13470. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13471. beveled /**< Indicates that corners should be drawn with a line flattening their
  13472. outside edge. */
  13473. };
  13474. /** The type shape to use for the ends of lines. */
  13475. enum EndCapStyle
  13476. {
  13477. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13478. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13479. the thickness of the stroke. */
  13480. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13481. };
  13482. /** Creates a stroke type.
  13483. @param strokeThickness the width of the line to use
  13484. @param jointStyle the type of joints to use for corners
  13485. @param endStyle the type of end-caps to use for the ends of open paths.
  13486. */
  13487. PathStrokeType (const float strokeThickness,
  13488. const JointStyle jointStyle = mitered,
  13489. const EndCapStyle endStyle = butt) throw();
  13490. /** Createes a copy of another stroke type. */
  13491. PathStrokeType (const PathStrokeType& other) throw();
  13492. /** Copies another stroke onto this one. */
  13493. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13494. /** Destructor. */
  13495. ~PathStrokeType() throw();
  13496. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13497. @param destPath the resultant stroked outline shape will be copied into this path.
  13498. Note that it's ok for the source and destination Paths to be
  13499. the same object, so you can easily turn a path into a stroked version
  13500. of itself.
  13501. @param sourcePath the path to use as the source
  13502. @param transform an optional transform to apply to the points from the source path
  13503. as they are being used
  13504. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13505. a higher resolution, which improved the quality if you'll later want
  13506. to enlarge the stroked path
  13507. @see createDashedStroke
  13508. */
  13509. void createStrokedPath (Path& destPath,
  13510. const Path& sourcePath,
  13511. const AffineTransform& transform = AffineTransform::identity,
  13512. const float extraAccuracy = 1.0f) const throw();
  13513. /** Applies this stroke type to a path, creating a dashed line.
  13514. This is similar to createStrokedPath, but uses the array passed in to
  13515. break the stroke up into a series of dashes.
  13516. @param destPath the resultant stroked outline shape will be copied into this path.
  13517. Note that it's ok for the source and destination Paths to be
  13518. the same object, so you can easily turn a path into a stroked version
  13519. of itself.
  13520. @param sourcePath the path to use as the source
  13521. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13522. a line of length 2, then skip a length of 3, then add a line of length 4,
  13523. skip 5, and keep repeating this pattern.
  13524. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13525. an even number, otherwise the pattern will get out of step as it
  13526. repeats.
  13527. @param transform an optional transform to apply to the points from the source path
  13528. as they are being used
  13529. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13530. a higher resolution, which improved the quality if you'll later want
  13531. to enlarge the stroked path
  13532. */
  13533. void createDashedStroke (Path& destPath,
  13534. const Path& sourcePath,
  13535. const float* dashLengths,
  13536. int numDashLengths,
  13537. const AffineTransform& transform = AffineTransform::identity,
  13538. const float extraAccuracy = 1.0f) const throw();
  13539. /** Returns the stroke thickness. */
  13540. float getStrokeThickness() const throw() { return thickness; }
  13541. /** Returns the joint style. */
  13542. JointStyle getJointStyle() const throw() { return jointStyle; }
  13543. /** Returns the end-cap style. */
  13544. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13545. juce_UseDebuggingNewOperator
  13546. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13547. bool operator== (const PathStrokeType& other) const throw();
  13548. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13549. bool operator!= (const PathStrokeType& other) const throw();
  13550. private:
  13551. float thickness;
  13552. JointStyle jointStyle;
  13553. EndCapStyle endStyle;
  13554. };
  13555. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13556. /********* End of inlined file: juce_PathStrokeType.h *********/
  13557. /********* Start of inlined file: juce_Line.h *********/
  13558. #ifndef __JUCE_LINE_JUCEHEADER__
  13559. #define __JUCE_LINE_JUCEHEADER__
  13560. /**
  13561. Represents a line, using 32-bit float co-ordinates.
  13562. This class contains a bunch of useful methods for various geometric
  13563. tasks.
  13564. @see Point, Rectangle, Path, Graphics::drawLine
  13565. */
  13566. class JUCE_API Line
  13567. {
  13568. public:
  13569. /** Creates a line, using (0, 0) as its start and end points. */
  13570. Line() throw();
  13571. /** Creates a copy of another line. */
  13572. Line (const Line& other) throw();
  13573. /** Creates a line based on the co-ordinates of its start and end points. */
  13574. Line (const float startX,
  13575. const float startY,
  13576. const float endX,
  13577. const float endY) throw();
  13578. /** Creates a line from its start and end points. */
  13579. Line (const Point& start,
  13580. const Point& end) throw();
  13581. /** Copies a line from another one. */
  13582. const Line& operator= (const Line& other) throw();
  13583. /** Destructor. */
  13584. ~Line() throw();
  13585. /** Returns the x co-ordinate of the line's start point. */
  13586. inline float getStartX() const throw() { return startX; }
  13587. /** Returns the y co-ordinate of the line's start point. */
  13588. inline float getStartY() const throw() { return startY; }
  13589. /** Returns the x co-ordinate of the line's end point. */
  13590. inline float getEndX() const throw() { return endX; }
  13591. /** Returns the y co-ordinate of the line's end point. */
  13592. inline float getEndY() const throw() { return endY; }
  13593. /** Returns the line's start point. */
  13594. const Point getStart() const throw();
  13595. /** Returns the line's end point. */
  13596. const Point getEnd() const throw();
  13597. /** Changes this line's start point */
  13598. void setStart (const float newStartX,
  13599. const float newStartY) throw();
  13600. /** Changes this line's end point */
  13601. void setEnd (const float newEndX,
  13602. const float newEndY) throw();
  13603. /** Changes this line's start point */
  13604. void setStart (const Point& newStart) throw();
  13605. /** Changes this line's end point */
  13606. void setEnd (const Point& newEnd) throw();
  13607. /** Applies an affine transform to the line's start and end points. */
  13608. void applyTransform (const AffineTransform& transform) throw();
  13609. /** Returns the length of the line. */
  13610. float getLength() const throw();
  13611. /** Returns true if the line's start and end x co-ordinates are the same. */
  13612. bool isVertical() const throw();
  13613. /** Returns true if the line's start and end y co-ordinates are the same. */
  13614. bool isHorizontal() const throw();
  13615. /** Returns the line's angle.
  13616. This value is the number of radians clockwise from the 3 o'clock direction,
  13617. where the line's start point is considered to be at the centre.
  13618. */
  13619. float getAngle() const throw();
  13620. /** Compares two lines. */
  13621. bool operator== (const Line& other) const throw();
  13622. /** Compares two lines. */
  13623. bool operator!= (const Line& other) const throw();
  13624. /** Finds the intersection between two lines.
  13625. @param line the other line
  13626. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13627. where they would meet if they were infinitely long)
  13628. the intersection (if the lines intersect). If the lines
  13629. are parallel, this will just be set to the position
  13630. of one of the line's endpoints.
  13631. @param intersectionY the y co-ordinate of the point where the lines meet
  13632. @returns true if the line segments intersect; false if they dont. Even if they
  13633. don't intersect, the intersection co-ordinates returned will still
  13634. be valid
  13635. */
  13636. bool intersects (const Line& line,
  13637. float& intersectionX,
  13638. float& intersectionY) const throw();
  13639. /** Returns the location of the point which is a given distance along this line.
  13640. @param distanceFromStart the distance to move along the line from its
  13641. start point. This value can be negative or longer
  13642. than the line itself
  13643. @see getPointAlongLineProportionally
  13644. */
  13645. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13646. /** Returns a point which is a certain distance along and to the side of this line.
  13647. This effectively moves a given distance along the line, then another distance
  13648. perpendicularly to this, and returns the resulting position.
  13649. @param distanceFromStart the distance to move along the line from its
  13650. start point. This value can be negative or longer
  13651. than the line itself
  13652. @param perpendicularDistance how far to move sideways from the line. If you're
  13653. looking along the line from its start towards its
  13654. end, then a positive value here will move to the
  13655. right, negative value move to the left.
  13656. */
  13657. const Point getPointAlongLine (const float distanceFromStart,
  13658. const float perpendicularDistance) const throw();
  13659. /** Returns the location of the point which is a given distance along this line
  13660. proportional to the line's length.
  13661. @param proportionOfLength the distance to move along the line from its
  13662. start point, in multiples of the line's length.
  13663. So a value of 0.0 will return the line's start point
  13664. and a value of 1.0 will return its end point. (This value
  13665. can be negative or greater than 1.0).
  13666. @see getPointAlongLine
  13667. */
  13668. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13669. /** Returns the smallest distance between this line segment and a given point.
  13670. So if the point is close to the line, this will return the perpendicular
  13671. distance from the line; if the point is a long way beyond one of the line's
  13672. end-point's, it'll return the straight-line distance to the nearest end-point.
  13673. @param x x position of the point to test
  13674. @param y y position of the point to test
  13675. @returns the point's distance from the line
  13676. @see getPositionAlongLineOfNearestPoint
  13677. */
  13678. float getDistanceFromLine (const float x,
  13679. const float y) const throw();
  13680. /** Finds the point on this line which is nearest to a given point, and
  13681. returns its position as a proportional position along the line.
  13682. @param x x position of the point to test
  13683. @param y y position of the point to test
  13684. @returns a value 0 to 1.0 which is the distance along this line from the
  13685. line's start to the point which is nearest to the point passed-in. To
  13686. turn this number into a position, use getPointAlongLineProportionally().
  13687. @see getDistanceFromLine, getPointAlongLineProportionally
  13688. */
  13689. float findNearestPointTo (const float x,
  13690. const float y) const throw();
  13691. /** Returns true if the given point lies above this line.
  13692. The return value is true if the point's y coordinate is less than the y
  13693. coordinate of this line at the given x (assuming the line extends infinitely
  13694. in both directions).
  13695. */
  13696. bool isPointAbove (const float x, const float y) const throw();
  13697. /** Returns a shortened copy of this line.
  13698. This will chop off part of the start of this line by a certain amount, (leaving the
  13699. end-point the same), and return the new line.
  13700. */
  13701. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13702. /** Returns a shortened copy of this line.
  13703. This will chop off part of the end of this line by a certain amount, (leaving the
  13704. start-point the same), and return the new line.
  13705. */
  13706. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13707. /** Cuts off parts of this line to keep the parts that are either inside or
  13708. outside a path.
  13709. Note that this isn't smart enough to cope with situations where the
  13710. line would need to be cut into multiple pieces to correctly clip against
  13711. a re-entrant shape.
  13712. @param path the path to clip against
  13713. @param keepSectionOutsidePath if true, it's the section outside the path
  13714. that will be kept; if false its the section inside
  13715. the path
  13716. @returns true if the line was changed.
  13717. */
  13718. bool clipToPath (const Path& path,
  13719. const bool keepSectionOutsidePath) throw();
  13720. juce_UseDebuggingNewOperator
  13721. private:
  13722. float startX, startY, endX, endY;
  13723. };
  13724. #endif // __JUCE_LINE_JUCEHEADER__
  13725. /********* End of inlined file: juce_Line.h *********/
  13726. /********* Start of inlined file: juce_Colours.h *********/
  13727. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13728. #define __JUCE_COLOURS_JUCEHEADER__
  13729. /********* Start of inlined file: juce_Colour.h *********/
  13730. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13731. #define __JUCE_COLOUR_JUCEHEADER__
  13732. /********* Start of inlined file: juce_PixelFormats.h *********/
  13733. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13734. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13735. #if JUCE_MSVC
  13736. #pragma pack (push, 1)
  13737. #define PACKED
  13738. #elif JUCE_GCC
  13739. #define PACKED __attribute__((packed))
  13740. #else
  13741. #define PACKED
  13742. #endif
  13743. /**
  13744. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13745. operations with it.
  13746. This is used internally by the imaging classes.
  13747. @see PixelRGB
  13748. */
  13749. class JUCE_API PixelARGB
  13750. {
  13751. public:
  13752. /** Creates a pixel without defining its colour. */
  13753. PixelARGB() throw() {}
  13754. ~PixelARGB() throw() {}
  13755. /** Creates a pixel from a 32-bit argb value.
  13756. */
  13757. PixelARGB (const uint32 argb_) throw()
  13758. : argb (argb_)
  13759. {
  13760. }
  13761. forcedinline uint32 getARGB() const throw() { return argb; }
  13762. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13763. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13764. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13765. forcedinline uint8 getRed() const throw() { return components.r; }
  13766. forcedinline uint8 getGreen() const throw() { return components.g; }
  13767. forcedinline uint8 getBlue() const throw() { return components.b; }
  13768. /** Blends another pixel onto this one.
  13769. This takes into account the opacity of the pixel being overlaid, and blends
  13770. it accordingly.
  13771. */
  13772. template <class Pixel>
  13773. forcedinline void blend (const Pixel& src) throw()
  13774. {
  13775. uint32 sargb = src.getARGB();
  13776. const uint32 alpha = 0x100 - (sargb >> 24);
  13777. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13778. sargb += 0xff00ff00 & (getAG() * alpha);
  13779. argb = sargb;
  13780. }
  13781. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13782. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13783. being used, so this can blend semi-transparently from a PixelRGB argument.
  13784. */
  13785. template <class Pixel>
  13786. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13787. {
  13788. ++extraAlpha;
  13789. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13790. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13791. const uint32 alpha = 0x100 - (sargb >> 24);
  13792. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13793. sargb += 0xff00ff00 & (getAG() * alpha);
  13794. argb = sargb;
  13795. }
  13796. /** Blends another pixel with this one, creating a colour that is somewhere
  13797. between the two, as specified by the amount.
  13798. */
  13799. template <class Pixel>
  13800. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13801. {
  13802. uint32 drb = getRB();
  13803. drb += (((src.getRB() - drb) * amount) >> 8);
  13804. drb &= 0x00ff00ff;
  13805. uint32 dag = getAG();
  13806. dag += (((src.getAG() - dag) * amount) >> 8);
  13807. dag &= 0x00ff00ff;
  13808. dag <<= 8;
  13809. dag |= drb;
  13810. argb = dag;
  13811. }
  13812. /** Copies another pixel colour over this one.
  13813. This doesn't blend it - this colour is simply replaced by the other one.
  13814. */
  13815. template <class Pixel>
  13816. forcedinline void set (const Pixel& src) throw()
  13817. {
  13818. argb = src.getARGB();
  13819. }
  13820. /** Replaces the colour's alpha value with another one. */
  13821. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13822. {
  13823. components.a = newAlpha;
  13824. }
  13825. /** Multiplies the colour's alpha value with another one. */
  13826. forcedinline void multiplyAlpha (int multiplier) throw()
  13827. {
  13828. ++multiplier;
  13829. argb = ((multiplier * getAG()) & 0xff00ff00)
  13830. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13831. }
  13832. forcedinline void multiplyAlpha (const float multiplier) throw()
  13833. {
  13834. multiplyAlpha ((int) (multiplier * 256.0f));
  13835. }
  13836. /** Sets the pixel's colour from individual components. */
  13837. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13838. {
  13839. components.b = b;
  13840. components.g = g;
  13841. components.r = r;
  13842. components.a = a;
  13843. }
  13844. /** Premultiplies the pixel's RGB values by its alpha. */
  13845. forcedinline void premultiply() throw()
  13846. {
  13847. const uint32 alpha = components.a;
  13848. if (alpha < 0xff)
  13849. {
  13850. if (alpha == 0)
  13851. {
  13852. components.b = 0;
  13853. components.g = 0;
  13854. components.r = 0;
  13855. }
  13856. else
  13857. {
  13858. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13859. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13860. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13861. }
  13862. }
  13863. }
  13864. /** Unpremultiplies the pixel's RGB values. */
  13865. forcedinline void unpremultiply() throw()
  13866. {
  13867. const uint32 alpha = components.a;
  13868. if (alpha < 0xff)
  13869. {
  13870. if (alpha == 0)
  13871. {
  13872. components.b = 0;
  13873. components.g = 0;
  13874. components.r = 0;
  13875. }
  13876. else
  13877. {
  13878. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13879. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13880. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13881. }
  13882. }
  13883. }
  13884. forcedinline void desaturate() throw()
  13885. {
  13886. if (components.a < 0xff && components.a > 0)
  13887. {
  13888. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13889. components.r = components.g = components.b
  13890. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13891. }
  13892. else
  13893. {
  13894. components.r = components.g = components.b
  13895. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13896. }
  13897. }
  13898. private:
  13899. union
  13900. {
  13901. uint32 argb;
  13902. struct
  13903. {
  13904. #if JUCE_BIG_ENDIAN
  13905. uint8 a : 8, r : 8, g : 8, b : 8;
  13906. #else
  13907. uint8 b, g, r, a;
  13908. #endif
  13909. } PACKED components;
  13910. };
  13911. } PACKED;
  13912. /**
  13913. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13914. This is used internally by the imaging classes.
  13915. @see PixelARGB
  13916. */
  13917. class JUCE_API PixelRGB
  13918. {
  13919. public:
  13920. /** Creates a pixel without defining its colour. */
  13921. PixelRGB() throw() {}
  13922. ~PixelRGB() throw() {}
  13923. /** Creates a pixel from a 32-bit argb value.
  13924. (The argb format is that used by PixelARGB)
  13925. */
  13926. PixelRGB (const uint32 argb) throw()
  13927. {
  13928. r = (uint8) (argb >> 16);
  13929. g = (uint8) (argb >> 8);
  13930. b = (uint8) (argb);
  13931. }
  13932. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13933. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13934. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13935. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13936. forcedinline uint8 getRed() const throw() { return r; }
  13937. forcedinline uint8 getGreen() const throw() { return g; }
  13938. forcedinline uint8 getBlue() const throw() { return b; }
  13939. /** Blends another pixel onto this one.
  13940. This takes into account the opacity of the pixel being overlaid, and blends
  13941. it accordingly.
  13942. */
  13943. forcedinline void blend (const PixelARGB& src) throw()
  13944. {
  13945. uint32 sargb = src.getARGB();
  13946. const uint32 alpha = 0x100 - (sargb >> 24);
  13947. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13948. sargb += 0x0000ff00 & (g * alpha);
  13949. r = (uint8) (sargb >> 16);
  13950. g = (uint8) (sargb >> 8);
  13951. b = (uint8) sargb;
  13952. }
  13953. forcedinline void blend (const PixelRGB& src) throw()
  13954. {
  13955. set (src);
  13956. }
  13957. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13958. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13959. being used, so this can blend semi-transparently from a PixelRGB argument.
  13960. */
  13961. template <class Pixel>
  13962. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13963. {
  13964. ++extraAlpha;
  13965. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13966. const uint32 sag = extraAlpha * src.getAG();
  13967. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13968. const uint32 alpha = 0x100 - (sargb >> 24);
  13969. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13970. sargb += 0x0000ff00 & (g * alpha);
  13971. b = (uint8) sargb;
  13972. g = (uint8) (sargb >> 8);
  13973. r = (uint8) (sargb >> 16);
  13974. }
  13975. /** Blends another pixel with this one, creating a colour that is somewhere
  13976. between the two, as specified by the amount.
  13977. */
  13978. template <class Pixel>
  13979. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13980. {
  13981. uint32 drb = getRB();
  13982. drb += (((src.getRB() - drb) * amount) >> 8);
  13983. uint32 dag = getAG();
  13984. dag += (((src.getAG() - dag) * amount) >> 8);
  13985. b = (uint8) drb;
  13986. g = (uint8) dag;
  13987. r = (uint8) (drb >> 16);
  13988. }
  13989. /** Copies another pixel colour over this one.
  13990. This doesn't blend it - this colour is simply replaced by the other one.
  13991. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13992. is thrown away.
  13993. */
  13994. template <class Pixel>
  13995. forcedinline void set (const Pixel& src) throw()
  13996. {
  13997. b = src.getBlue();
  13998. g = src.getGreen();
  13999. r = src.getRed();
  14000. }
  14001. /** This method is included for compatibility with the PixelARGB class. */
  14002. forcedinline void setAlpha (const uint8) throw() {}
  14003. /** Multiplies the colour's alpha value with another one. */
  14004. forcedinline void multiplyAlpha (int) throw() {}
  14005. /** Sets the pixel's colour from individual components. */
  14006. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  14007. {
  14008. r = r_;
  14009. g = g_;
  14010. b = b_;
  14011. }
  14012. /** Premultiplies the pixel's RGB values by its alpha. */
  14013. forcedinline void premultiply() throw() {}
  14014. /** Unpremultiplies the pixel's RGB values. */
  14015. forcedinline void unpremultiply() throw() {}
  14016. forcedinline void desaturate() throw()
  14017. {
  14018. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  14019. }
  14020. private:
  14021. #if JUCE_MAC
  14022. uint8 r, g, b;
  14023. #else
  14024. uint8 b, g, r;
  14025. #endif
  14026. } PACKED;
  14027. #if JUCE_MSVC
  14028. #pragma pack (pop)
  14029. #endif
  14030. #undef PACKED
  14031. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  14032. /********* End of inlined file: juce_PixelFormats.h *********/
  14033. /**
  14034. Represents a colour, also including a transparency value.
  14035. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  14036. */
  14037. class JUCE_API Colour
  14038. {
  14039. public:
  14040. /** Creates a transparent black colour. */
  14041. Colour() throw();
  14042. /** Creates a copy of another Colour object. */
  14043. Colour (const Colour& other) throw();
  14044. /** Creates a colour from a 32-bit ARGB value.
  14045. The format of this number is:
  14046. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14047. All components in the range 0x00 to 0xff.
  14048. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14049. @see getPixelARGB
  14050. */
  14051. explicit Colour (const uint32 argb) throw();
  14052. /** Creates an opaque colour using 8-bit red, green and blue values */
  14053. Colour (const uint8 red,
  14054. const uint8 green,
  14055. const uint8 blue) throw();
  14056. /** Creates an opaque colour using 8-bit red, green and blue values */
  14057. static const Colour fromRGB (const uint8 red,
  14058. const uint8 green,
  14059. const uint8 blue) throw();
  14060. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14061. Colour (const uint8 red,
  14062. const uint8 green,
  14063. const uint8 blue,
  14064. const uint8 alpha) throw();
  14065. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14066. static const Colour fromRGBA (const uint8 red,
  14067. const uint8 green,
  14068. const uint8 blue,
  14069. const uint8 alpha) throw();
  14070. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  14071. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  14072. Values outside the valid range will be clipped.
  14073. */
  14074. Colour (const uint8 red,
  14075. const uint8 green,
  14076. const uint8 blue,
  14077. const float alpha) throw();
  14078. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  14079. static const Colour fromRGBAFloat (const uint8 red,
  14080. const uint8 green,
  14081. const uint8 blue,
  14082. const float alpha) throw();
  14083. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14084. The floating point values must be between 0.0 and 1.0.
  14085. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14086. Values outside the valid range will be clipped.
  14087. */
  14088. Colour (const float hue,
  14089. const float saturation,
  14090. const float brightness,
  14091. const uint8 alpha) throw();
  14092. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  14093. All values must be between 0.0 and 1.0.
  14094. Numbers outside the valid range will be clipped.
  14095. */
  14096. Colour (const float hue,
  14097. const float saturation,
  14098. const float brightness,
  14099. const float alpha) throw();
  14100. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14101. The floating point values must be between 0.0 and 1.0.
  14102. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14103. Values outside the valid range will be clipped.
  14104. */
  14105. static const Colour fromHSV (const float hue,
  14106. const float saturation,
  14107. const float brightness,
  14108. const float alpha) throw();
  14109. /** Destructor. */
  14110. ~Colour() throw();
  14111. /** Copies another Colour object. */
  14112. const Colour& operator= (const Colour& other) throw();
  14113. /** Compares two colours. */
  14114. bool operator== (const Colour& other) const throw();
  14115. /** Compares two colours. */
  14116. bool operator!= (const Colour& other) const throw();
  14117. /** Returns the red component of this colour.
  14118. @returns a value between 0x00 and 0xff.
  14119. */
  14120. uint8 getRed() const throw() { return argb.getRed(); }
  14121. /** Returns the green component of this colour.
  14122. @returns a value between 0x00 and 0xff.
  14123. */
  14124. uint8 getGreen() const throw() { return argb.getGreen(); }
  14125. /** Returns the blue component of this colour.
  14126. @returns a value between 0x00 and 0xff.
  14127. */
  14128. uint8 getBlue() const throw() { return argb.getBlue(); }
  14129. /** Returns the red component of this colour as a floating point value.
  14130. @returns a value between 0.0 and 1.0
  14131. */
  14132. float getFloatRed() const throw();
  14133. /** Returns the green component of this colour as a floating point value.
  14134. @returns a value between 0.0 and 1.0
  14135. */
  14136. float getFloatGreen() const throw();
  14137. /** Returns the blue component of this colour as a floating point value.
  14138. @returns a value between 0.0 and 1.0
  14139. */
  14140. float getFloatBlue() const throw();
  14141. /** Returns a premultiplied ARGB pixel object that represents this colour.
  14142. */
  14143. const PixelARGB getPixelARGB() const throw();
  14144. /** Returns a 32-bit integer that represents this colour.
  14145. The format of this number is:
  14146. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14147. */
  14148. uint32 getARGB() const throw();
  14149. /** Returns the colour's alpha (opacity).
  14150. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  14151. */
  14152. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  14153. /** Returns the colour's alpha (opacity) as a floating point value.
  14154. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  14155. */
  14156. float getFloatAlpha() const throw();
  14157. /** Returns true if this colour is completely opaque.
  14158. Equivalent to (getAlpha() == 0xff).
  14159. */
  14160. bool isOpaque() const throw();
  14161. /** Returns true if this colour is completely transparent.
  14162. Equivalent to (getAlpha() == 0x00).
  14163. */
  14164. bool isTransparent() const throw();
  14165. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14166. const Colour withAlpha (const uint8 newAlpha) const throw();
  14167. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14168. const Colour withAlpha (const float newAlpha) const throw();
  14169. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14170. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14171. */
  14172. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14173. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14174. If the foreground colour is semi-transparent, it is blended onto this colour
  14175. accordingly.
  14176. */
  14177. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14178. /** Returns the colour's hue component.
  14179. The value returned is in the range 0.0 to 1.0
  14180. */
  14181. float getHue() const throw();
  14182. /** Returns the colour's saturation component.
  14183. The value returned is in the range 0.0 to 1.0
  14184. */
  14185. float getSaturation() const throw();
  14186. /** Returns the colour's brightness component.
  14187. The value returned is in the range 0.0 to 1.0
  14188. */
  14189. float getBrightness() const throw();
  14190. /** Returns the colour's hue, saturation and brightness components all at once.
  14191. The values returned are in the range 0.0 to 1.0
  14192. */
  14193. void getHSB (float& hue,
  14194. float& saturation,
  14195. float& brightness) const throw();
  14196. /** Returns a copy of this colour with a different hue. */
  14197. const Colour withHue (const float newHue) const throw();
  14198. /** Returns a copy of this colour with a different saturation. */
  14199. const Colour withSaturation (const float newSaturation) const throw();
  14200. /** Returns a copy of this colour with a different brightness.
  14201. @see brighter, darker, withMultipliedBrightness
  14202. */
  14203. const Colour withBrightness (const float newBrightness) const throw();
  14204. /** Returns a copy of this colour with it hue rotated.
  14205. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14206. @see brighter, darker, withMultipliedBrightness
  14207. */
  14208. const Colour withRotatedHue (const float amountToRotate) const throw();
  14209. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14210. The new colour's saturation is (this->getSaturation() * multiplier)
  14211. (the result is clipped to legal limits).
  14212. */
  14213. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14214. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14215. The new colour's saturation is (this->getBrightness() * multiplier)
  14216. (the result is clipped to legal limits).
  14217. */
  14218. const Colour withMultipliedBrightness (const float amount) const throw();
  14219. /** Returns a brighter version of this colour.
  14220. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14221. unchanged, and higher values make it brighter
  14222. @see withMultipliedBrightness
  14223. */
  14224. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14225. /** Returns a darker version of this colour.
  14226. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14227. unchanged, and higher values make it darker
  14228. @see withMultipliedBrightness
  14229. */
  14230. const Colour darker (float amountDarker = 0.4f) const throw();
  14231. /** Returns a colour that will be clearly visible against this colour.
  14232. The amount parameter indicates how contrasting the new colour should
  14233. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14234. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14235. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14236. */
  14237. const Colour contrasting (const float amount = 1.0f) const throw();
  14238. /** Returns a colour that contrasts against two colours.
  14239. Looks for a colour that contrasts with both of the colours passed-in.
  14240. Handy for things like choosing a highlight colour in text editors, etc.
  14241. */
  14242. static const Colour contrasting (const Colour& colour1,
  14243. const Colour& colour2) throw();
  14244. /** Returns an opaque shade of grey.
  14245. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14246. */
  14247. static const Colour greyLevel (const float brightness) throw();
  14248. /** Returns a stringified version of this colour.
  14249. The string can be turned back into a colour using the fromString() method.
  14250. */
  14251. const String toString() const throw();
  14252. /** Reads the colour from a string that was created with toString().
  14253. */
  14254. static const Colour fromString (const String& encodedColourString);
  14255. juce_UseDebuggingNewOperator
  14256. private:
  14257. PixelARGB argb;
  14258. };
  14259. #endif // __JUCE_COLOUR_JUCEHEADER__
  14260. /********* End of inlined file: juce_Colour.h *********/
  14261. /**
  14262. Contains a set of predefined named colours (mostly standard HTML colours)
  14263. @see Colour, Colours::greyLevel
  14264. */
  14265. class Colours
  14266. {
  14267. public:
  14268. static JUCE_API const Colour
  14269. transparentBlack, /**< ARGB = 0x00000000 */
  14270. transparentWhite, /**< ARGB = 0x00ffffff */
  14271. black, /**< ARGB = 0xff000000 */
  14272. white, /**< ARGB = 0xffffffff */
  14273. blue, /**< ARGB = 0xff0000ff */
  14274. grey, /**< ARGB = 0xff808080 */
  14275. green, /**< ARGB = 0xff008000 */
  14276. red, /**< ARGB = 0xffff0000 */
  14277. yellow, /**< ARGB = 0xffffff00 */
  14278. aliceblue, antiquewhite, aqua, aquamarine,
  14279. azure, beige, bisque, blanchedalmond,
  14280. blueviolet, brown, burlywood, cadetblue,
  14281. chartreuse, chocolate, coral, cornflowerblue,
  14282. cornsilk, crimson, cyan, darkblue,
  14283. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14284. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14285. darkorchid, darkred, darksalmon, darkseagreen,
  14286. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14287. deeppink, deepskyblue, dimgrey, dodgerblue,
  14288. firebrick, floralwhite, forestgreen, fuchsia,
  14289. gainsboro, gold, goldenrod, greenyellow,
  14290. honeydew, hotpink, indianred, indigo,
  14291. ivory, khaki, lavender, lavenderblush,
  14292. lemonchiffon, lightblue, lightcoral, lightcyan,
  14293. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14294. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14295. lightsteelblue, lightyellow, lime, limegreen,
  14296. linen, magenta, maroon, mediumaquamarine,
  14297. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14298. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14299. midnightblue, mintcream, mistyrose, navajowhite,
  14300. navy, oldlace, olive, olivedrab,
  14301. orange, orangered, orchid, palegoldenrod,
  14302. palegreen, paleturquoise, palevioletred, papayawhip,
  14303. peachpuff, peru, pink, plum,
  14304. powderblue, purple, rosybrown, royalblue,
  14305. saddlebrown, salmon, sandybrown, seagreen,
  14306. seashell, sienna, silver, skyblue,
  14307. slateblue, slategrey, snow, springgreen,
  14308. steelblue, tan, teal, thistle,
  14309. tomato, turquoise, violet, wheat,
  14310. whitesmoke, yellowgreen;
  14311. /** Attempts to look up a string in the list of known colour names, and return
  14312. the appropriate colour.
  14313. A non-case-sensitive search is made of the list of predefined colours, and
  14314. if a match is found, that colour is returned. If no match is found, the
  14315. colour passed in as the defaultColour parameter is returned.
  14316. */
  14317. static JUCE_API const Colour findColourForName (const String& colourName,
  14318. const Colour& defaultColour);
  14319. private:
  14320. // this isn't a class you should ever instantiate - it's just here for the
  14321. // static values in it.
  14322. Colours();
  14323. };
  14324. #endif // __JUCE_COLOURS_JUCEHEADER__
  14325. /********* End of inlined file: juce_Colours.h *********/
  14326. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14327. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14328. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14329. /********* Start of inlined file: juce_Brush.h *********/
  14330. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14331. #define __JUCE_BRUSH_JUCEHEADER__
  14332. class Path;
  14333. class AffineTransform;
  14334. class LowLevelGraphicsContext;
  14335. class Image;
  14336. class Graphics;
  14337. /**
  14338. A brush is used to fill areas with colours, patterns, or images.
  14339. The Graphics class has an idea of a current brush which it uses to render
  14340. shapes, rectangles, lines, text, etc.
  14341. This is the base class - there are subclasses for useful types of fill pattern,
  14342. and applications can define their own brushes too.
  14343. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14344. */
  14345. class JUCE_API Brush
  14346. {
  14347. protected:
  14348. /** Creates a Brush.
  14349. (Nothing much happens in the base class).
  14350. */
  14351. Brush() throw();
  14352. public:
  14353. /** Destructor. */
  14354. virtual ~Brush() throw();
  14355. /** Creates a copy of whatever class of Brush this is. */
  14356. virtual Brush* createCopy() const throw() = 0;
  14357. /** Does whatever is relevent to transform the geometry of this brush. */
  14358. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14359. /** Does whatever is relevent to change the opacity of this brush. */
  14360. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14361. /** Must return true if this brush won't draw any pixels. */
  14362. virtual bool isInvisible() const throw() = 0;
  14363. virtual void paintPath (LowLevelGraphicsContext& context,
  14364. const Path& path, const AffineTransform& transform) throw() = 0;
  14365. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14366. int x, int y, int w, int h) throw() = 0;
  14367. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14368. const Image& alphaChannelImage, int imageX, int imageY,
  14369. int x, int y, int w, int h) throw() = 0;
  14370. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14371. int x, float y1, float y2) throw();
  14372. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14373. int y, float x1, float x2) throw();
  14374. virtual void paintLine (LowLevelGraphicsContext& context,
  14375. float x1, float y1, float x2, float y2) throw();
  14376. private:
  14377. Brush (const Brush&);
  14378. const Brush& operator= (const Brush&);
  14379. };
  14380. #endif // __JUCE_BRUSH_JUCEHEADER__
  14381. /********* End of inlined file: juce_Brush.h *********/
  14382. /**
  14383. A Brush that fills its area with a solid (or semi-transparent) colour.
  14384. An application won't normally need to use this class directly, as drawing
  14385. with solid colours is taken care of automatically by the Graphics class
  14386. (it actually uses one of these brushes internally when you set the colour
  14387. with the Graphics::setColour() method).
  14388. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14389. */
  14390. class JUCE_API SolidColourBrush : public Brush
  14391. {
  14392. public:
  14393. /** Creates a SolidColourBrush to draw with the given colour.
  14394. The colour can be changed later with the setColour() method.
  14395. */
  14396. SolidColourBrush (const Colour& colour) throw();
  14397. /** Creates a SolidColourBrush set to black.
  14398. The colour can be changed later with the setColour() method.
  14399. */
  14400. SolidColourBrush() throw();
  14401. /** Destructor. */
  14402. ~SolidColourBrush() throw();
  14403. /** Returns the colour currently being used. */
  14404. const Colour& getColour() const throw() { return colour; }
  14405. /** Sets the colour to use for drawing. */
  14406. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14407. Brush* createCopy() const throw();
  14408. void applyTransform (const AffineTransform& transform) throw();
  14409. bool isInvisible() const throw();
  14410. void multiplyOpacity (const float multiple) throw();
  14411. void paintPath (LowLevelGraphicsContext& context,
  14412. const Path& path, const AffineTransform& transform) throw();
  14413. void paintRectangle (LowLevelGraphicsContext& context,
  14414. int x, int y, int w, int h) throw();
  14415. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14416. const Image& alphaChannelImage, int imageX, int imageY,
  14417. int x, int y, int w, int h) throw();
  14418. void paintVerticalLine (LowLevelGraphicsContext& context,
  14419. int x, float y1, float y2) throw();
  14420. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14421. int y, float x1, float x2) throw();
  14422. void paintLine (LowLevelGraphicsContext& context,
  14423. float x1, float y1, float x2, float y2) throw();
  14424. juce_UseDebuggingNewOperator
  14425. private:
  14426. Colour colour;
  14427. SolidColourBrush (const SolidColourBrush&);
  14428. const SolidColourBrush& operator= (const SolidColourBrush&);
  14429. };
  14430. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14431. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14432. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14433. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14434. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14435. /**
  14436. Defines the method used to postion some kind of rectangular object within
  14437. a rectangular viewport.
  14438. Although similar to Justification, this is more specific, and has some extra
  14439. options.
  14440. */
  14441. class JUCE_API RectanglePlacement
  14442. {
  14443. public:
  14444. /** Creates a RectanglePlacement object using a combination of flags. */
  14445. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14446. /** Creates a copy of another Justification object. */
  14447. RectanglePlacement (const RectanglePlacement& other) throw();
  14448. /** Copies another Justification object. */
  14449. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14450. /** Flag values that can be combined and used in the constructor. */
  14451. enum
  14452. {
  14453. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14454. xLeft = 1,
  14455. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14456. xRight = 2,
  14457. /** Indicates that the source should be placed in the centre between the left and right
  14458. sides of the available space. */
  14459. xMid = 4,
  14460. /** Indicates that the source's top edge should be aligned with the top edge of the
  14461. destination rectangle. */
  14462. yTop = 8,
  14463. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14464. destination rectangle. */
  14465. yBottom = 16,
  14466. /** Indicates that the source should be placed in the centre between the top and bottom
  14467. sides of the available space. */
  14468. yMid = 32,
  14469. /** If this flag is set, then the source rectangle will be resized to completely fill
  14470. the destination rectangle, and all other flags are ignored.
  14471. */
  14472. stretchToFit = 64,
  14473. /** If this flag is set, then the source rectangle will be resized so that it is the
  14474. minimum size to completely fill the destination rectangle. This means that some
  14475. of the source rectangle may fall outside the destination.
  14476. If this flag is not set, the source will be given the maximum size at which none
  14477. of it falls outside the destination rectangle.
  14478. */
  14479. fillDestination = 128,
  14480. /** Indicates that the source rectangle can be reduced in size if required, but should
  14481. never be made larger than its original size.
  14482. */
  14483. onlyReduceInSize = 256,
  14484. /** Indicates that the source rectangle can be enlarged if required, but should
  14485. never be made smaller than its original size.
  14486. */
  14487. onlyIncreaseInSize = 512,
  14488. /** Indicates that the source rectangle's size should be left unchanged.
  14489. */
  14490. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14491. /** A shorthand value that is equivalent to (xMid | yMid). */
  14492. centred = 4 + 32
  14493. };
  14494. /** Returns the raw flags that are set for this object. */
  14495. inline int getFlags() const throw() { return flags; }
  14496. /** Tests a set of flags for this object.
  14497. @returns true if any of the flags passed in are set on this object.
  14498. */
  14499. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14500. /** Adjusts the position and size of a rectangle to fit it into a space.
  14501. The source rectangle co-ordinates will be adjusted so that they fit into
  14502. the destination rectangle based on this object's flags.
  14503. */
  14504. void applyTo (double& sourceX,
  14505. double& sourceY,
  14506. double& sourceW,
  14507. double& sourceH,
  14508. const double destinationX,
  14509. const double destinationY,
  14510. const double destinationW,
  14511. const double destinationH) const throw();
  14512. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14513. into the destination rectangle using the current flags.
  14514. */
  14515. const AffineTransform getTransformToFit (float sourceX,
  14516. float sourceY,
  14517. float sourceW,
  14518. float sourceH,
  14519. const float destinationX,
  14520. const float destinationY,
  14521. const float destinationW,
  14522. const float destinationH) const throw();
  14523. private:
  14524. int flags;
  14525. };
  14526. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14527. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14528. class LowLevelGraphicsContext;
  14529. class Image;
  14530. class RectangleList;
  14531. /**
  14532. A graphics context, used for drawing a component or image.
  14533. When a Component needs painting, a Graphics context is passed to its
  14534. Component::paint() method, and this you then call methods within this
  14535. object to actually draw the component's content.
  14536. A Graphics can also be created from an image, to allow drawing directly onto
  14537. that image.
  14538. @see Component::paint
  14539. */
  14540. class JUCE_API Graphics
  14541. {
  14542. public:
  14543. /** Creates a Graphics object to draw directly onto the given image.
  14544. The graphics object that is created will be set up to draw onto the image,
  14545. with the context's clipping area being the entire size of the image, and its
  14546. origin being the image's origin. To draw into a subsection of an image, use the
  14547. reduceClipRegion() and setOrigin() methods.
  14548. Obviously you shouldn't delete the image before this context is deleted.
  14549. */
  14550. Graphics (Image& imageToDrawOnto) throw();
  14551. /** Destructor. */
  14552. ~Graphics() throw();
  14553. /** Changes the current drawing colour.
  14554. This sets the colour that will now be used for drawing operations - it also
  14555. sets the opacity to that of the colour passed-in.
  14556. If a brush is being used when this method is called, the brush will be deselected,
  14557. and any subsequent drawing will be done with a solid colour brush instead.
  14558. @see setOpacity, setBrush, getColour
  14559. */
  14560. void setColour (const Colour& newColour) throw();
  14561. /** Returns the colour that's currently being used.
  14562. This will return the last colour set by setColour(), even if the colour's not
  14563. currently being used for drawing because a brush has been selected instead.
  14564. @see setColour
  14565. */
  14566. const Colour& getCurrentColour() const throw();
  14567. /** Changes the opacity to use with the current colour.
  14568. If a solid colour is being used for drawing, this changes its opacity (and this
  14569. will be reflected by calls to the getColour() method).
  14570. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14571. */
  14572. void setOpacity (const float newOpacity) throw();
  14573. /** Changes the current brush to use for drawing.
  14574. If a null pointer is passed in, the context will revert to using a solid
  14575. colour for drawing (using the last colour set by setColour()).
  14576. If a brush is passed in, a copy of it will be used for subsequent drawing
  14577. operations until setColour() or setBrush() is called.
  14578. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14579. */
  14580. void setBrush (const Brush* const newBrush) throw();
  14581. /** Changes the font to use for subsequent text-drawing functions.
  14582. Note there's also a setFont (float, int) method to quickly change the size and
  14583. style of the current font.
  14584. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14585. */
  14586. void setFont (const Font& newFont) throw();
  14587. /** Changes the size and style of the currently-selected font.
  14588. This is a convenient shortcut that changes the context's current font to a
  14589. different size or style. The typeface won't be changed.
  14590. @see Font
  14591. */
  14592. void setFont (const float newFontHeight,
  14593. const int fontStyleFlags = Font::plain) throw();
  14594. /** Returns the font that's currently being used for text operations.
  14595. @see setFont
  14596. */
  14597. const Font& getCurrentFont() const throw();
  14598. /** Draws a one-line text string.
  14599. This will use the current colour (or brush) to fill the text. The font is the last
  14600. one specified by setFont().
  14601. @param text the string to draw
  14602. @param startX the position to draw the left-hand edge of the text
  14603. @param baselineY the position of the text's baseline
  14604. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14605. */
  14606. void drawSingleLineText (const String& text,
  14607. const int startX,
  14608. const int baselineY) const throw();
  14609. /** Draws text across multiple lines.
  14610. This will break the text onto a new line where there's a new-line or
  14611. carriage-return character, or at a word-boundary when the text becomes wider
  14612. than the size specified by the maximumLineWidth parameter.
  14613. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14614. */
  14615. void drawMultiLineText (const String& text,
  14616. const int startX,
  14617. const int baselineY,
  14618. const int maximumLineWidth) const throw();
  14619. /** Renders a string of text as a vector path.
  14620. This allows a string to be transformed with an arbitrary AffineTransform and
  14621. rendered using the current colour/brush. It's much slower than the normal text methods
  14622. but more accurate.
  14623. @see setFont
  14624. */
  14625. void drawTextAsPath (const String& text,
  14626. const AffineTransform& transform) const throw();
  14627. /** Draws a line of text within a specified rectangle.
  14628. The text will be positioned within the rectangle based on the justification
  14629. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14630. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14631. flag is true).
  14632. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14633. */
  14634. void drawText (const String& text,
  14635. const int x,
  14636. const int y,
  14637. const int width,
  14638. const int height,
  14639. const Justification& justificationType,
  14640. const bool useEllipsesIfTooBig) const throw();
  14641. /** Tries to draw a text string inside a given space.
  14642. This does its best to make the given text readable within the specified rectangle,
  14643. so it useful for labelling things.
  14644. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14645. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14646. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14647. it's been truncated.
  14648. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14649. both horizontally and vertically.
  14650. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14651. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14652. can set this value to 1.0f.
  14653. @see GlyphArrangement::addFittedText
  14654. */
  14655. void drawFittedText (const String& text,
  14656. const int x,
  14657. const int y,
  14658. const int width,
  14659. const int height,
  14660. const Justification& justificationFlags,
  14661. const int maximumNumberOfLines,
  14662. const float minimumHorizontalScale = 0.7f) const throw();
  14663. /** Fills the context's entire clip region with the current colour or brush.
  14664. (See also the fillAll (const Colour&) method which is a quick way of filling
  14665. it with a given colour).
  14666. */
  14667. void fillAll() const throw();
  14668. /** Fills the context's entire clip region with a given colour.
  14669. This leaves the context's current colour and brush unchanged, it just
  14670. uses the specified colour temporarily.
  14671. */
  14672. void fillAll (const Colour& colourToUse) const throw();
  14673. /** Fills a rectangle with the current colour or brush.
  14674. @see drawRect, fillRoundedRectangle
  14675. */
  14676. void fillRect (int x,
  14677. int y,
  14678. int width,
  14679. int height) const throw();
  14680. /** Fills a rectangle with the current colour or brush. */
  14681. void fillRect (const Rectangle& rectangle) const throw();
  14682. /** Fills a rectangle with the current colour or brush.
  14683. This uses sub-pixel positioning so is slower than the fillRect method which
  14684. takes integer co-ordinates.
  14685. */
  14686. void fillRect (const float x,
  14687. const float y,
  14688. const float width,
  14689. const float height) const throw();
  14690. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14691. @see drawRoundedRectangle, Path::addRoundedRectangle
  14692. */
  14693. void fillRoundedRectangle (const float x,
  14694. const float y,
  14695. const float width,
  14696. const float height,
  14697. const float cornerSize) const throw();
  14698. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14699. @see drawRoundedRectangle, Path::addRoundedRectangle
  14700. */
  14701. void fillRoundedRectangle (const Rectangle& rectangle,
  14702. const float cornerSize) const throw();
  14703. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14704. */
  14705. void fillCheckerBoard (int x, int y,
  14706. int width, int height,
  14707. const int checkWidth,
  14708. const int checkHeight,
  14709. const Colour& colour1,
  14710. const Colour& colour2) const throw();
  14711. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14712. The lines are drawn inside the given rectangle, and greater line thicknesses
  14713. extend inwards.
  14714. @see fillRect
  14715. */
  14716. void drawRect (const int x,
  14717. const int y,
  14718. const int width,
  14719. const int height,
  14720. const int lineThickness = 1) const throw();
  14721. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14722. The lines are drawn inside the given rectangle, and greater line thicknesses
  14723. extend inwards.
  14724. @see fillRect
  14725. */
  14726. void drawRect (const float x,
  14727. const float y,
  14728. const float width,
  14729. const float height,
  14730. const float lineThickness = 1.0f) const throw();
  14731. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14732. The lines are drawn inside the given rectangle, and greater line thicknesses
  14733. extend inwards.
  14734. @see fillRect
  14735. */
  14736. void drawRect (const Rectangle& rectangle,
  14737. const int lineThickness = 1) const throw();
  14738. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14739. @see fillRoundedRectangle, Path::addRoundedRectangle
  14740. */
  14741. void drawRoundedRectangle (const float x,
  14742. const float y,
  14743. const float width,
  14744. const float height,
  14745. const float cornerSize,
  14746. const float lineThickness) const throw();
  14747. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14748. @see fillRoundedRectangle, Path::addRoundedRectangle
  14749. */
  14750. void drawRoundedRectangle (const Rectangle& rectangle,
  14751. const float cornerSize,
  14752. const float lineThickness) const throw();
  14753. /** Draws a 3D raised (or indented) bevel using two colours.
  14754. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14755. extend inwards.
  14756. The top-left colour is used for the top- and left-hand edges of the
  14757. bevel; the bottom-right colour is used for the bottom- and right-hand
  14758. edges.
  14759. If useGradient is true, then the bevel fades out to make it look more curved
  14760. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  14761. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  14762. the centre edges are sharp and it fades towards the outside.
  14763. */
  14764. void drawBevel (const int x,
  14765. const int y,
  14766. const int width,
  14767. const int height,
  14768. const int bevelThickness,
  14769. const Colour& topLeftColour = Colours::white,
  14770. const Colour& bottomRightColour = Colours::black,
  14771. const bool useGradient = true,
  14772. const bool sharpEdgeOnOutside = true) const throw();
  14773. /** Draws a pixel using the current colour or brush.
  14774. */
  14775. void setPixel (int x, int y) const throw();
  14776. /** Fills an ellipse with the current colour or brush.
  14777. The ellipse is drawn to fit inside the given rectangle.
  14778. @see drawEllipse, Path::addEllipse
  14779. */
  14780. void fillEllipse (const float x,
  14781. const float y,
  14782. const float width,
  14783. const float height) const throw();
  14784. /** Draws an elliptical stroke using the current colour or brush.
  14785. @see fillEllipse, Path::addEllipse
  14786. */
  14787. void drawEllipse (const float x,
  14788. const float y,
  14789. const float width,
  14790. const float height,
  14791. const float lineThickness) const throw();
  14792. /** Draws a line between two points.
  14793. The line is 1 pixel wide and drawn with the current colour or brush.
  14794. */
  14795. void drawLine (float startX,
  14796. float startY,
  14797. float endX,
  14798. float endY) const throw();
  14799. /** Draws a line between two points with a given thickness.
  14800. @see Path::addLineSegment
  14801. */
  14802. void drawLine (const float startX,
  14803. const float startY,
  14804. const float endX,
  14805. const float endY,
  14806. const float lineThickness) const throw();
  14807. /** Draws a line between two points.
  14808. The line is 1 pixel wide and drawn with the current colour or brush.
  14809. */
  14810. void drawLine (const Line& line) const throw();
  14811. /** Draws a line between two points with a given thickness.
  14812. @see Path::addLineSegment
  14813. */
  14814. void drawLine (const Line& line,
  14815. const float lineThickness) const throw();
  14816. /** Draws a dashed line using a custom set of dash-lengths.
  14817. @param startX the line's start x co-ordinate
  14818. @param startY the line's start y co-ordinate
  14819. @param endX the line's end x co-ordinate
  14820. @param endY the line's end y co-ordinate
  14821. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14822. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14823. draw 6 pixels, skip 7 pixels, and then repeat.
  14824. @param numDashLengths the number of elements in the array (this must be an even number).
  14825. @param lineThickness the thickness of the line to draw
  14826. @see PathStrokeType::createDashedStroke
  14827. */
  14828. void drawDashedLine (const float startX,
  14829. const float startY,
  14830. const float endX,
  14831. const float endY,
  14832. const float* const dashLengths,
  14833. const int numDashLengths,
  14834. const float lineThickness = 1.0f) const throw();
  14835. /** Draws a vertical line of pixels at a given x position.
  14836. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14837. positions, and these will be anti-aliased if necessary.
  14838. */
  14839. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14840. /** Draws a horizontal line of pixels at a given y position.
  14841. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14842. positions, and these will be anti-aliased if necessary.
  14843. */
  14844. void drawHorizontalLine (const int y, float left, float right) const throw();
  14845. /** Fills a path using the currently selected colour or brush.
  14846. */
  14847. void fillPath (const Path& path,
  14848. const AffineTransform& transform = AffineTransform::identity) const throw();
  14849. /** Draws a path's outline using the currently selected colour or brush.
  14850. */
  14851. void strokePath (const Path& path,
  14852. const PathStrokeType& strokeType,
  14853. const AffineTransform& transform = AffineTransform::identity) const throw();
  14854. /** Draws a line with an arrowhead.
  14855. @param startX the line's start x co-ordinate
  14856. @param startY the line's start y co-ordinate
  14857. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14858. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14859. @param lineThickness the thickness of the line
  14860. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14861. @param arrowheadLength the length of the arrow head (along the length of the line)
  14862. */
  14863. void drawArrow (const float startX,
  14864. const float startY,
  14865. const float endX,
  14866. const float endY,
  14867. const float lineThickness,
  14868. const float arrowheadWidth,
  14869. const float arrowheadLength) const throw();
  14870. /** Types of rendering quality that can be specified when drawing images.
  14871. @see blendImage, Graphics::setImageResamplingQuality
  14872. */
  14873. enum ResamplingQuality
  14874. {
  14875. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14876. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14877. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14878. };
  14879. /** Changes the quality that will be used when resampling images.
  14880. By default a Graphics object will be set to mediumRenderingQuality.
  14881. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14882. */
  14883. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14884. /** Draws an image.
  14885. This will draw the whole of an image, positioning its top-left corner at the
  14886. given co-ordinates, and keeping its size the same. This is the simplest image
  14887. drawing method - the others give more control over the scaling and clipping
  14888. of the images.
  14889. Images are composited using the context's current opacity, so if you
  14890. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14891. (or setColour() with an opaque colour) before drawing images.
  14892. */
  14893. void drawImageAt (const Image* const imageToDraw,
  14894. const int topLeftX,
  14895. const int topLeftY,
  14896. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14897. /** Draws part of an image, rescaling it to fit in a given target region.
  14898. The specified area of the source image is rescaled and drawn to fill the
  14899. specifed destination rectangle.
  14900. Images are composited using the context's current opacity, so if you
  14901. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14902. (or setColour() with an opaque colour) before drawing images.
  14903. @param imageToDraw the image to overlay
  14904. @param destX the left of the destination rectangle
  14905. @param destY the top of the destination rectangle
  14906. @param destWidth the width of the destination rectangle
  14907. @param destHeight the height of the destination rectangle
  14908. @param sourceX the left of the rectangle to copy from the source image
  14909. @param sourceY the top of the rectangle to copy from the source image
  14910. @param sourceWidth the width of the rectangle to copy from the source image
  14911. @param sourceHeight the height of the rectangle to copy from the source image
  14912. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14913. the source image's alpha channel is used as a mask with
  14914. which to fill the destination using the current colour
  14915. or brush. (If the source is has no alpha channel, then
  14916. it will just fill the target with a solid rectangle)
  14917. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14918. */
  14919. void drawImage (const Image* const imageToDraw,
  14920. int destX,
  14921. int destY,
  14922. int destWidth,
  14923. int destHeight,
  14924. int sourceX,
  14925. int sourceY,
  14926. int sourceWidth,
  14927. int sourceHeight,
  14928. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14929. /** Draws part of an image, having applied an affine transform to it.
  14930. This lets you throw the image around in some wacky ways, rotate it, shear,
  14931. scale it, etc.
  14932. A clipping subregion is specified within the source image and no pixels
  14933. outside this region will be used.
  14934. Images are composited using the context's current opacity, so if you
  14935. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14936. (or setColour() with an opaque colour) before drawing images.
  14937. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14938. are ignored and it is filled with the current brush, masked by its alpha channel.
  14939. @see setImageResamplingQuality, drawImage
  14940. */
  14941. void drawImageTransformed (const Image* const imageToDraw,
  14942. int sourceClipX,
  14943. int sourceClipY,
  14944. int sourceClipWidth,
  14945. int sourceClipHeight,
  14946. const AffineTransform& transform,
  14947. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14948. /** Draws an image to fit within a designated rectangle.
  14949. If the image is too big or too small for the space, it will be rescaled
  14950. to fit as nicely as it can do without affecting its aspect ratio. It will
  14951. then be placed within the target rectangle according to the justification flags
  14952. specified.
  14953. @param imageToDraw the source image to draw
  14954. @param destX top-left of the target rectangle to fit it into
  14955. @param destY top-left of the target rectangle to fit it into
  14956. @param destWidth size of the target rectangle to fit the image into
  14957. @param destHeight size of the target rectangle to fit the image into
  14958. @param placementWithinTarget this specifies how the image should be positioned
  14959. within the target rectangle - see the RectanglePlacement
  14960. class for more details about this.
  14961. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14962. alpha channel will be used as a mask with which to
  14963. draw with the current brush or colour. This is
  14964. similar to fillAlphaMap(), and see also drawImage()
  14965. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14966. */
  14967. void drawImageWithin (const Image* const imageToDraw,
  14968. const int destX,
  14969. const int destY,
  14970. const int destWidth,
  14971. const int destHeight,
  14972. const RectanglePlacement& placementWithinTarget,
  14973. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14974. /** Returns the position of the bounding box for the current clipping region.
  14975. @see getClipRegion, clipRegionIntersects
  14976. */
  14977. const Rectangle getClipBounds() const throw();
  14978. /** Checks whether a rectangle overlaps the context's clipping region.
  14979. If this returns false, no part of the given area can be drawn onto, so this
  14980. method can be used to optimise a component's paint() method, by letting it
  14981. avoid drawing complex objects that aren't within the region being repainted.
  14982. */
  14983. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14984. /** Intersects the current clipping region with another region.
  14985. @returns true if the resulting clipping region is non-zero in size
  14986. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14987. */
  14988. bool reduceClipRegion (const int x, const int y,
  14989. const int width, const int height) throw();
  14990. /** Intersects the current clipping region with a rectangle list region.
  14991. @returns true if the resulting clipping region is non-zero in size
  14992. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14993. */
  14994. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14995. /** Excludes a rectangle to stop it being drawn into. */
  14996. void excludeClipRegion (const int x, const int y,
  14997. const int width, const int height) throw();
  14998. /** Returns true if no drawing can be done because the clip region is zero. */
  14999. bool isClipEmpty() const throw();
  15000. /** Saves the current graphics state on an internal stack.
  15001. To restore the state, use restoreState().
  15002. */
  15003. void saveState() throw();
  15004. /** Restores a graphics state that was previously saved with saveState().
  15005. */
  15006. void restoreState() throw();
  15007. /** Moves the position of the context's origin.
  15008. This changes the position that the context considers to be (0, 0) to
  15009. the specified position.
  15010. So if you call setOrigin (100, 100), then the position that was previously
  15011. referred to as (100, 100) will subsequently be considered to be (0, 0).
  15012. @see reduceClipRegion
  15013. */
  15014. void setOrigin (const int newOriginX,
  15015. const int newOriginY) throw();
  15016. /** Resets the current colour, brush, and font to default settings. */
  15017. void resetToDefaultState() throw();
  15018. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  15019. bool isVectorDevice() const throw();
  15020. juce_UseDebuggingNewOperator
  15021. /** Create a graphics that uses a given low-level renderer.
  15022. For internal use only.
  15023. NB. The context will NOT be deleted by this object when it is deleted.
  15024. */
  15025. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  15026. /** @internal */
  15027. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  15028. private:
  15029. LowLevelGraphicsContext* const context;
  15030. const bool ownsContext;
  15031. struct GraphicsState
  15032. {
  15033. GraphicsState() throw();
  15034. GraphicsState (const GraphicsState&) throw();
  15035. ~GraphicsState() throw();
  15036. Colour colour;
  15037. Brush* brush;
  15038. Font font;
  15039. ResamplingQuality quality;
  15040. };
  15041. GraphicsState* state;
  15042. OwnedArray <GraphicsState> stateStack;
  15043. bool saveStatePending;
  15044. void saveStateIfPending() throw();
  15045. const Graphics& operator= (const Graphics& other);
  15046. Graphics (const Graphics&);
  15047. };
  15048. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  15049. /********* End of inlined file: juce_Graphics.h *********/
  15050. /**
  15051. A graphical effect filter that can be applied to components.
  15052. An ImageEffectFilter can be applied to the image that a component
  15053. paints before it hits the screen.
  15054. This is used for adding effects like shadows, blurs, etc.
  15055. @see Component::setComponentEffect
  15056. */
  15057. class JUCE_API ImageEffectFilter
  15058. {
  15059. public:
  15060. /** Overridden to render the effect.
  15061. The implementation of this method must use the image that is passed in
  15062. as its source, and should render its output to the graphics context passed in.
  15063. @param sourceImage the image that the source component has just rendered with
  15064. its paint() method. The image may or may not have an alpha
  15065. channel, depending on whether the component is opaque.
  15066. @param destContext the graphics context to use to draw the resultant image.
  15067. */
  15068. virtual void applyEffect (Image& sourceImage,
  15069. Graphics& destContext) = 0;
  15070. /** Destructor. */
  15071. virtual ~ImageEffectFilter() {}
  15072. };
  15073. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15074. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  15075. /********* Start of inlined file: juce_RectangleList.h *********/
  15076. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  15077. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  15078. /**
  15079. Maintains a set of rectangles as a complex region.
  15080. This class allows a set of rectangles to be treated as a solid shape, and can
  15081. add and remove rectangular sections of it, and simplify overlapping or
  15082. adjacent rectangles.
  15083. @see Rectangle
  15084. */
  15085. class JUCE_API RectangleList
  15086. {
  15087. public:
  15088. /** Creates an empty RectangleList */
  15089. RectangleList() throw();
  15090. /** Creates a copy of another list */
  15091. RectangleList (const RectangleList& other) throw();
  15092. /** Creates a list containing just one rectangle. */
  15093. RectangleList (const Rectangle& rect) throw();
  15094. /** Copies this list from another one. */
  15095. const RectangleList& operator= (const RectangleList& other) throw();
  15096. /** Destructor. */
  15097. ~RectangleList() throw();
  15098. /** Returns true if the region is empty. */
  15099. bool isEmpty() const throw();
  15100. /** Returns the number of rectangles in the list. */
  15101. int getNumRectangles() const throw() { return rects.size(); }
  15102. /** Returns one of the rectangles at a particular index.
  15103. @returns the rectangle at the index, or an empty rectangle if the
  15104. index is out-of-range.
  15105. */
  15106. const Rectangle getRectangle (const int index) const throw();
  15107. /** Removes all rectangles to leave an empty region. */
  15108. void clear() throw();
  15109. /** Merges a new rectangle into the list.
  15110. The rectangle being added will first be clipped to remove any parts of it
  15111. that overlap existing rectangles in the list.
  15112. */
  15113. void add (const int x, const int y,
  15114. const int w, const int h) throw();
  15115. /** Merges a new rectangle into the list.
  15116. The rectangle being added will first be clipped to remove any parts of it
  15117. that overlap existing rectangles in the list, and adjacent rectangles will be
  15118. merged into it.
  15119. */
  15120. void add (const Rectangle& rect) throw();
  15121. /** Dumbly adds a rectangle to the list without checking for overlaps.
  15122. This simply adds the rectangle to the end, it doesn't merge it or remove
  15123. any overlapping bits.
  15124. */
  15125. void addWithoutMerging (const Rectangle& rect) throw();
  15126. /** Merges another rectangle list into this one.
  15127. Any overlaps between the two lists will be clipped, so that the result is
  15128. the union of both lists.
  15129. */
  15130. void add (const RectangleList& other) throw();
  15131. /** Removes a rectangular region from the list.
  15132. Any rectangles in the list which overlap this will be clipped and subdivided
  15133. if necessary.
  15134. */
  15135. void subtract (const Rectangle& rect) throw();
  15136. /** Removes all areas in another RectangleList from this one.
  15137. Any rectangles in the list which overlap this will be clipped and subdivided
  15138. if necessary.
  15139. */
  15140. void subtract (const RectangleList& otherList) throw();
  15141. /** Removes any areas of the region that lie outside a given rectangle.
  15142. Any rectangles in the list which overlap this will be clipped and subdivided
  15143. if necessary.
  15144. Returns true if the resulting region is not empty, false if it is empty.
  15145. @see getIntersectionWith
  15146. */
  15147. bool clipTo (const Rectangle& rect) throw();
  15148. /** Removes any areas of the region that lie outside a given rectangle list.
  15149. Any rectangles in this object which overlap the specified list will be clipped
  15150. and subdivided if necessary.
  15151. Returns true if the resulting region is not empty, false if it is empty.
  15152. @see getIntersectionWith
  15153. */
  15154. bool clipTo (const RectangleList& other) throw();
  15155. /** Creates a region which is the result of clipping this one to a given rectangle.
  15156. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  15157. resulting region into the list whose reference is passed-in.
  15158. Returns true if the resulting region is not empty, false if it is empty.
  15159. @see clipTo
  15160. */
  15161. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15162. /** Swaps the contents of this and another list.
  15163. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15164. to swap them.
  15165. */
  15166. void swapWith (RectangleList& otherList) throw();
  15167. /** Checks whether the region contains a given point.
  15168. @returns true if the point lies within one of the rectangles in the list
  15169. */
  15170. bool containsPoint (const int x, const int y) const throw();
  15171. /** Checks whether the region contains the whole of a given rectangle.
  15172. @returns true all parts of the rectangle passed in lie within the region
  15173. defined by this object
  15174. @see intersectsRectangle, containsPoint
  15175. */
  15176. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15177. /** Checks whether the region contains any part of a given rectangle.
  15178. @returns true if any part of the rectangle passed in lies within the region
  15179. defined by this object
  15180. @see containsRectangle
  15181. */
  15182. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15183. /** Checks whether this region intersects any part of another one.
  15184. @see intersectsRectangle
  15185. */
  15186. bool intersects (const RectangleList& other) const throw();
  15187. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15188. const Rectangle getBounds() const throw();
  15189. /** Optimises the list into a minimum number of constituent rectangles.
  15190. This will try to combine any adjacent rectangles into larger ones where
  15191. possible, to simplify lists that might have been fragmented by repeated
  15192. add/subtract calls.
  15193. */
  15194. void consolidate() throw();
  15195. /** Adds an x and y value to all the co-ordinates. */
  15196. void offsetAll (const int dx, const int dy) throw();
  15197. /** Creates a Path object to represent this region. */
  15198. const Path toPath() const throw();
  15199. /** An iterator for accessing all the rectangles in a RectangleList. */
  15200. class Iterator
  15201. {
  15202. public:
  15203. Iterator (const RectangleList& list) throw();
  15204. ~Iterator() throw();
  15205. /** Advances to the next rectangle, and returns true if it's not finished.
  15206. Call this before using getRectangle() to find the rectangle that was returned.
  15207. */
  15208. bool next() throw();
  15209. /** Returns the current rectangle. */
  15210. const Rectangle* getRectangle() const throw() { return current; }
  15211. juce_UseDebuggingNewOperator
  15212. private:
  15213. const Rectangle* current;
  15214. const RectangleList& owner;
  15215. int index;
  15216. Iterator (const Iterator&);
  15217. const Iterator& operator= (const Iterator&);
  15218. };
  15219. juce_UseDebuggingNewOperator
  15220. private:
  15221. friend class Iterator;
  15222. Array <Rectangle> rects;
  15223. };
  15224. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15225. /********* End of inlined file: juce_RectangleList.h *********/
  15226. /********* Start of inlined file: juce_BorderSize.h *********/
  15227. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15228. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15229. /**
  15230. Specifies a set of gaps to be left around the sides of a rectangle.
  15231. This is basically the size of the spaces at the top, bottom, left and right of
  15232. a rectangle. It's used by various component classes to specify borders.
  15233. @see Rectangle
  15234. */
  15235. class JUCE_API BorderSize
  15236. {
  15237. public:
  15238. /** Creates a null border.
  15239. All sizes are left as 0.
  15240. */
  15241. BorderSize() throw();
  15242. /** Creates a copy of another border. */
  15243. BorderSize (const BorderSize& other) throw();
  15244. /** Creates a border with the given gaps. */
  15245. BorderSize (const int topGap,
  15246. const int leftGap,
  15247. const int bottomGap,
  15248. const int rightGap) throw();
  15249. /** Creates a border with the given gap on all sides. */
  15250. BorderSize (const int allGaps) throw();
  15251. /** Destructor. */
  15252. ~BorderSize() throw();
  15253. /** Returns the gap that should be left at the top of the region. */
  15254. int getTop() const throw() { return top; }
  15255. /** Returns the gap that should be left at the top of the region. */
  15256. int getLeft() const throw() { return left; }
  15257. /** Returns the gap that should be left at the top of the region. */
  15258. int getBottom() const throw() { return bottom; }
  15259. /** Returns the gap that should be left at the top of the region. */
  15260. int getRight() const throw() { return right; }
  15261. /** Returns the sum of the top and bottom gaps. */
  15262. int getTopAndBottom() const throw() { return top + bottom; }
  15263. /** Returns the sum of the left and right gaps. */
  15264. int getLeftAndRight() const throw() { return left + right; }
  15265. /** Changes the top gap. */
  15266. void setTop (const int newTopGap) throw();
  15267. /** Changes the left gap. */
  15268. void setLeft (const int newLeftGap) throw();
  15269. /** Changes the bottom gap. */
  15270. void setBottom (const int newBottomGap) throw();
  15271. /** Changes the right gap. */
  15272. void setRight (const int newRightGap) throw();
  15273. /** Returns a rectangle with these borders removed from it. */
  15274. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15275. /** Removes this border from a given rectangle. */
  15276. void subtractFrom (Rectangle& rectangle) const throw();
  15277. /** Returns a rectangle with these borders added around it. */
  15278. const Rectangle addedTo (const Rectangle& original) const throw();
  15279. /** Adds this border around a given rectangle. */
  15280. void addTo (Rectangle& original) const throw();
  15281. bool operator== (const BorderSize& other) const throw();
  15282. bool operator!= (const BorderSize& other) const throw();
  15283. juce_UseDebuggingNewOperator
  15284. private:
  15285. int top, left, bottom, right;
  15286. };
  15287. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15288. /********* End of inlined file: juce_BorderSize.h *********/
  15289. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15290. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15291. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15292. class Component;
  15293. class Graphics;
  15294. /********* Start of inlined file: juce_MessageListener.h *********/
  15295. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15296. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15297. /********* Start of inlined file: juce_Message.h *********/
  15298. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15299. #define __JUCE_MESSAGE_JUCEHEADER__
  15300. class MessageListener;
  15301. class MessageManager;
  15302. /** The base class for objects that can be delivered to a MessageListener.
  15303. The simplest Message object contains a few integer and pointer parameters
  15304. that the user can set, and this is enough for a lot of purposes. For passing more
  15305. complex data, subclasses of Message can also be used.
  15306. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15307. */
  15308. class JUCE_API Message
  15309. {
  15310. public:
  15311. /** Creates an uninitialised message.
  15312. The class's variables will also be left uninitialised.
  15313. */
  15314. Message() throw();
  15315. /** Creates a message object, filling in the member variables.
  15316. The corresponding public member variables will be set from the parameters
  15317. passed in.
  15318. */
  15319. Message (const int intParameter1,
  15320. const int intParameter2,
  15321. const int intParameter3,
  15322. void* const pointerParameter) throw();
  15323. /** Destructor. */
  15324. virtual ~Message() throw();
  15325. // These values can be used for carrying simple data that the application needs to
  15326. // pass around. For more complex messages, just create a subclass.
  15327. int intParameter1; /**< user-defined integer value. */
  15328. int intParameter2; /**< user-defined integer value. */
  15329. int intParameter3; /**< user-defined integer value. */
  15330. void* pointerParameter; /**< user-defined pointer value. */
  15331. juce_UseDebuggingNewOperator
  15332. private:
  15333. friend class MessageListener;
  15334. friend class MessageManager;
  15335. MessageListener* messageRecipient;
  15336. Message (const Message&);
  15337. const Message& operator= (const Message&);
  15338. };
  15339. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15340. /********* End of inlined file: juce_Message.h *********/
  15341. /**
  15342. MessageListener subclasses can post and receive Message objects.
  15343. @see Message, MessageManager, ActionListener, ChangeListener
  15344. */
  15345. class JUCE_API MessageListener
  15346. {
  15347. protected:
  15348. /** Creates a MessageListener. */
  15349. MessageListener() throw();
  15350. public:
  15351. /** Destructor.
  15352. When a MessageListener is deleted, it removes itself from a global list
  15353. of registered listeners, so that the isValidMessageListener() method
  15354. will no longer return true.
  15355. */
  15356. virtual ~MessageListener();
  15357. /** This is the callback method that receives incoming messages.
  15358. This is called by the MessageManager from its dispatch loop.
  15359. @see postMessage
  15360. */
  15361. virtual void handleMessage (const Message& message) = 0;
  15362. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15363. later on.
  15364. This method can be called safely by any thread.
  15365. @param message the message object to send - this will be deleted
  15366. automatically by the message queue, so don't keep any
  15367. references to it after calling this method.
  15368. @see handleMessage
  15369. */
  15370. void postMessage (Message* const message) const throw();
  15371. /** Checks whether this MessageListener has been deleted.
  15372. Although not foolproof, this method is safe to call on dangling or null
  15373. pointers. A list of active MessageListeners is kept internally, so this
  15374. checks whether the object is on this list or not.
  15375. Note that it's possible to get a false-positive here, if an object is
  15376. deleted and another is subsequently created that happens to be at the
  15377. exact same memory location, but I can't think of a good way of avoiding
  15378. this.
  15379. */
  15380. bool isValidMessageListener() const throw();
  15381. };
  15382. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15383. /********* End of inlined file: juce_MessageListener.h *********/
  15384. class ComponentBoundsConstrainer;
  15385. class ComponentDeletionWatcher;
  15386. /**
  15387. The base class for window objects that wrap a component as a real operating
  15388. system object.
  15389. This is an abstract base class - the platform specific code contains default
  15390. implementations of it that create and manage windows.
  15391. @see Component::createNewPeer
  15392. */
  15393. class JUCE_API ComponentPeer : public MessageListener
  15394. {
  15395. public:
  15396. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15397. enum StyleFlags
  15398. {
  15399. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15400. entry on the taskbar (ignored on MacOSX) */
  15401. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15402. tooltip, etc. */
  15403. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15404. through it (may not be possible on some platforms). */
  15405. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15406. title bar and frame\. if not specified, the window will be
  15407. borderless. */
  15408. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15409. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15410. minimise button on it. */
  15411. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15412. maximise button on it. */
  15413. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15414. close button on it. */
  15415. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15416. not be possible on all platforms). */
  15417. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15418. do its own repainting, but only to repaint when the
  15419. performAnyPendingRepaintsNow() method is called. */
  15420. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15421. be used for things like plugin windows, to stop them interfering
  15422. with the host's shortcut keys */
  15423. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15424. };
  15425. /** Creates a peer.
  15426. The component is the one that we intend to represent, and the style flags are
  15427. a combination of the values in the StyleFlags enum
  15428. */
  15429. ComponentPeer (Component* const component,
  15430. const int styleFlags) throw();
  15431. /** Destructor. */
  15432. virtual ~ComponentPeer();
  15433. /** Returns the component being represented by this peer. */
  15434. Component* getComponent() const throw() { return component; }
  15435. /** Returns the set of style flags that were set when the window was created.
  15436. @see Component::addToDesktop
  15437. */
  15438. int getStyleFlags() const throw() { return styleFlags; }
  15439. /** Returns the raw handle to whatever kind of window is being used.
  15440. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15441. but rememeber there's no guarantees what you'll get back.
  15442. */
  15443. virtual void* getNativeHandle() const = 0;
  15444. /** Shows or hides the window. */
  15445. virtual void setVisible (bool shouldBeVisible) = 0;
  15446. /** Changes the title of the window. */
  15447. virtual void setTitle (const String& title) = 0;
  15448. /** Moves the window without changing its size.
  15449. If the native window is contained in another window, then the co-ordinates are
  15450. relative to the parent window's origin, not the screen origin.
  15451. This should result in a callback to handleMovedOrResized().
  15452. */
  15453. virtual void setPosition (int x, int y) = 0;
  15454. /** Resizes the window without changing its position.
  15455. This should result in a callback to handleMovedOrResized().
  15456. */
  15457. virtual void setSize (int w, int h) = 0;
  15458. /** Moves and resizes the window.
  15459. If the native window is contained in another window, then the co-ordinates are
  15460. relative to the parent window's origin, not the screen origin.
  15461. This should result in a callback to handleMovedOrResized().
  15462. */
  15463. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15464. /** Returns the current position and size of the window.
  15465. If the native window is contained in another window, then the co-ordinates are
  15466. relative to the parent window's origin, not the screen origin.
  15467. */
  15468. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15469. /** Returns the x-position of this window, relative to the screen's origin. */
  15470. virtual int getScreenX() const = 0;
  15471. /** Returns the y-position of this window, relative to the screen's origin. */
  15472. virtual int getScreenY() const = 0;
  15473. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15474. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15475. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15476. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15477. /** Minimises the window. */
  15478. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15479. /** True if the window is currently minimised. */
  15480. virtual bool isMinimised() const = 0;
  15481. /** Enable/disable fullscreen mode for the window. */
  15482. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15483. /** True if the window is currently full-screen. */
  15484. virtual bool isFullScreen() const = 0;
  15485. /** Sets the size to restore to if fullscreen mode is turned off. */
  15486. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15487. /** Returns the size to restore to if fullscreen mode is turned off. */
  15488. const Rectangle& getNonFullScreenBounds() const throw();
  15489. /** Attempts to change the icon associated with this window.
  15490. */
  15491. virtual void setIcon (const Image& newIcon) = 0;
  15492. /** Sets a constrainer to use if the peer can resize itself.
  15493. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15494. */
  15495. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15496. /** Returns the current constrainer, if one has been set. */
  15497. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15498. /** Checks if a point is in the window.
  15499. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15500. is false, then this returns false if the point is actually inside a child of this
  15501. window.
  15502. */
  15503. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15504. /** Returns the size of the window frame that's around this window.
  15505. Whether or not the window has a normal window frame depends on the flags
  15506. that were set when the window was created by Component::addToDesktop()
  15507. */
  15508. virtual const BorderSize getFrameSize() const = 0;
  15509. /** This is called when the window's bounds change.
  15510. A peer implementation must call this when the window is moved and resized, so that
  15511. this method can pass the message on to the component.
  15512. */
  15513. void handleMovedOrResized();
  15514. /** This is called if the screen resolution changes.
  15515. A peer implementation must call this if the monitor arrangement changes or the available
  15516. screen size changes.
  15517. */
  15518. void handleScreenSizeChange();
  15519. /** This is called to repaint the component into the given context. */
  15520. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15521. /** Sets this window to either be always-on-top or normal.
  15522. Some kinds of window might not be able to do this, so should return false.
  15523. */
  15524. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15525. /** Brings the window to the top, optionally also giving it focus. */
  15526. virtual void toFront (bool makeActive) = 0;
  15527. /** Moves the window to be just behind another one. */
  15528. virtual void toBehind (ComponentPeer* other) = 0;
  15529. /** Called when the window is brought to the front, either by the OS or by a call
  15530. to toFront().
  15531. */
  15532. void handleBroughtToFront();
  15533. /** True if the window has the keyboard focus. */
  15534. virtual bool isFocused() const = 0;
  15535. /** Tries to give the window keyboard focus. */
  15536. virtual void grabFocus() = 0;
  15537. /** Tells the window that text input may be required at the given position.
  15538. This may cause things like a virtual on-screen keyboard to appear, depending
  15539. on the OS.
  15540. */
  15541. virtual void textInputRequired (int x, int y) = 0;
  15542. /** Called when the window gains keyboard focus. */
  15543. void handleFocusGain();
  15544. /** Called when the window loses keyboard focus. */
  15545. void handleFocusLoss();
  15546. Component* getLastFocusedSubcomponent() const throw();
  15547. /** Called when a key is pressed.
  15548. For keycode info, see the KeyPress class.
  15549. Returns true if the keystroke was used.
  15550. */
  15551. bool handleKeyPress (const int keyCode,
  15552. const juce_wchar textCharacter);
  15553. /** Called whenever a key is pressed or released.
  15554. Returns true if the keystroke was used.
  15555. */
  15556. bool handleKeyUpOrDown();
  15557. /** Called whenever a modifier key is pressed or released. */
  15558. void handleModifierKeysChange();
  15559. /** Invalidates a region of the window to be repainted asynchronously. */
  15560. virtual void repaint (int x, int y, int w, int h) = 0;
  15561. /** This can be called (from the message thread) to cause the immediate redrawing
  15562. of any areas of this window that need repainting.
  15563. You shouldn't ever really need to use this, it's mainly for special purposes
  15564. like supporting audio plugins where the host's event loop is out of our control.
  15565. */
  15566. virtual void performAnyPendingRepaintsNow() = 0;
  15567. void handleMouseEnter (int x, int y, const int64 time);
  15568. void handleMouseMove (int x, int y, const int64 time);
  15569. void handleMouseDown (int x, int y, const int64 time);
  15570. void handleMouseDrag (int x, int y, const int64 time);
  15571. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15572. void handleMouseExit (int x, int y, const int64 time);
  15573. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15574. /** Causes a mouse-move callback to be made asynchronously. */
  15575. void sendFakeMouseMove() throw();
  15576. void handleUserClosingWindow();
  15577. void handleFileDragMove (const StringArray& files, int x, int y);
  15578. void handleFileDragExit (const StringArray& files);
  15579. void handleFileDragDrop (const StringArray& files, int x, int y);
  15580. /** Resets the masking region.
  15581. The subclass should call this every time it's about to call the handlePaint
  15582. method.
  15583. @see addMaskedRegion
  15584. */
  15585. void clearMaskedRegion() throw();
  15586. /** Adds a rectangle to the set of areas not to paint over.
  15587. A component can call this on its peer during its paint() method, to signal
  15588. that the painting code should ignore a given region. The reason
  15589. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15590. The masked region is cleared each time before a paint happens, so a component
  15591. will have to make sure it calls this every time it's painted.
  15592. */
  15593. void addMaskedRegion (int x, int y, int w, int h) throw();
  15594. /** Returns the number of currently-active peers.
  15595. @see getPeer
  15596. */
  15597. static int getNumPeers() throw();
  15598. /** Returns one of the currently-active peers.
  15599. @see getNumPeers
  15600. */
  15601. static ComponentPeer* getPeer (const int index) throw();
  15602. /** Checks if this peer object is valid.
  15603. @see getNumPeers
  15604. */
  15605. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15606. juce_UseDebuggingNewOperator
  15607. protected:
  15608. Component* const component;
  15609. const int styleFlags;
  15610. RectangleList maskedRegion;
  15611. Rectangle lastNonFullscreenBounds;
  15612. uint32 lastPaintTime;
  15613. ComponentBoundsConstrainer* constrainer;
  15614. static void updateCurrentModifiers() throw();
  15615. /** @internal */
  15616. void handleMessage (const Message& message);
  15617. private:
  15618. Component* lastFocusedComponent;
  15619. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15620. Component* lastDragAndDropCompUnderMouse;
  15621. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15622. friend class Component;
  15623. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15624. void setLastDragDropTarget (Component* comp);
  15625. ComponentPeer (const ComponentPeer&);
  15626. const ComponentPeer& operator= (const ComponentPeer&);
  15627. };
  15628. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15629. /********* End of inlined file: juce_ComponentPeer.h *********/
  15630. class LookAndFeel;
  15631. /**
  15632. The base class for all JUCE user-interface objects.
  15633. */
  15634. class JUCE_API Component : public MouseListener,
  15635. protected MessageListener
  15636. {
  15637. public:
  15638. /** Creates a component.
  15639. To get it to actually appear, you'll also need to:
  15640. - Either add it to a parent component or use the addToDesktop() method to
  15641. make it a desktop window
  15642. - Set its size and position to something sensible
  15643. - Use setVisible() to make it visible
  15644. And for it to serve any useful purpose, you'll need to write a
  15645. subclass of Component or use one of the other types of component from
  15646. the library.
  15647. */
  15648. Component() throw();
  15649. /** Destructor.
  15650. Note that when a component is deleted, any child components it might
  15651. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15652. */
  15653. virtual ~Component();
  15654. /** Creates a component, setting its name at the same time.
  15655. @see getName, setName
  15656. */
  15657. Component (const String& componentName) throw();
  15658. /** Returns the name of this component.
  15659. @see setName
  15660. */
  15661. const String& getName() const throw() { return componentName_; }
  15662. /** Sets the name of this component.
  15663. When the name changes, all registered ComponentListeners will receive a
  15664. ComponentListener::componentNameChanged() callback.
  15665. @see getName
  15666. */
  15667. virtual void setName (const String& newName);
  15668. /** Checks whether this Component object has been deleted.
  15669. This will check whether this object is still a valid component, or whether
  15670. it's been deleted.
  15671. It's safe to call this on null or dangling pointers, but note that there is a
  15672. small risk if another new (but different) component has been created at the
  15673. same memory address which this one occupied, this methods can return a
  15674. false positive.
  15675. */
  15676. bool isValidComponent() const throw();
  15677. /** Makes the component visible or invisible.
  15678. This method will show or hide the component.
  15679. Note that components default to being non-visible when first created.
  15680. Also note that visible components won't be seen unless all their parent components
  15681. are also visible.
  15682. This method will call visibilityChanged() and also componentVisibilityChanged()
  15683. for any component listeners that are interested in this component.
  15684. @param shouldBeVisible whether to show or hide the component
  15685. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15686. */
  15687. virtual void setVisible (bool shouldBeVisible);
  15688. /** Tests whether the component is visible or not.
  15689. this doesn't necessarily tell you whether this comp is actually on the screen
  15690. because this depends on whether all the parent components are also visible - use
  15691. isShowing() to find this out.
  15692. @see isShowing, setVisible
  15693. */
  15694. bool isVisible() const throw() { return flags.visibleFlag; }
  15695. /** Called when this component's visiblility changes.
  15696. @see setVisible, isVisible
  15697. */
  15698. virtual void visibilityChanged();
  15699. /** Tests whether this component and all its parents are visible.
  15700. @returns true only if this component and all its parents are visible.
  15701. @see isVisible
  15702. */
  15703. bool isShowing() const throw();
  15704. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15705. To do this, this function will cunningly:
  15706. - take a snapshot of the component as it currently looks
  15707. - call setVisible(false) on the component
  15708. - replace it with a special component that will continue drawing the
  15709. snapshot, animating it and gradually making it more transparent
  15710. - when it's gone, the special component will also be deleted
  15711. As soon as this method returns, the component can be safely removed and deleted
  15712. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15713. component's destructor.
  15714. Passing non-zero x and y values will cause the ghostly component image to
  15715. also whizz off by this distance while fading out. If the scale factor is
  15716. not 1.0, it will also zoom from the component's current size to this new size.
  15717. One thing to be careful about is that the parent component must be able to cope
  15718. with this unknown component type being added to it.
  15719. */
  15720. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15721. const int deltaXToMove = 0,
  15722. const int deltaYToMove = 0,
  15723. const float scaleFactorAtEnd = 1.0f);
  15724. /** Makes this component appear as a window on the desktop.
  15725. Note that before calling this, you should make sure that the component's opacity is
  15726. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15727. system will try to create a special transparent window for it, which will generally take
  15728. a lot more CPU to operate (and might not even be possible on some platforms).
  15729. If the component is inside a parent component at the time this method is called, it
  15730. will be first be removed from that parent. Likewise if a component on the desktop
  15731. is subsequently added to another component, it'll be removed from the desktop.
  15732. @param windowStyleFlags a combination of the flags specified in the
  15733. ComponentPeer::StyleFlags enum, which define the
  15734. window's characteristics.
  15735. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15736. in which the juce component should place itself. On Windows,
  15737. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15738. supported on all platforms, and best left as 0 unless you know
  15739. what you're doing
  15740. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15741. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15742. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15743. */
  15744. virtual void addToDesktop (int windowStyleFlags,
  15745. void* nativeWindowToAttachTo = 0);
  15746. /** If the component is currently showing on the desktop, this will hide it.
  15747. You can also use setVisible() to hide a desktop window temporarily, but
  15748. removeFromDesktop() will free any system resources that are being used up.
  15749. @see addToDesktop, isOnDesktop
  15750. */
  15751. void removeFromDesktop();
  15752. /** Returns true if this component is currently showing on the desktop.
  15753. @see addToDesktop, removeFromDesktop
  15754. */
  15755. bool isOnDesktop() const throw();
  15756. /** Returns the heavyweight window that contains this component.
  15757. If this component is itself on the desktop, this will return the window
  15758. object that it is using. Otherwise, it will return the window of
  15759. its top-level parent component.
  15760. This may return 0 if there isn't a desktop component.
  15761. @see addToDesktop, isOnDesktop
  15762. */
  15763. ComponentPeer* getPeer() const throw();
  15764. /** For components on the desktop, this is called if the system wants to close the window.
  15765. This is a signal that either the user or the system wants the window to close. The
  15766. default implementation of this method will trigger an assertion to warn you that your
  15767. component should do something about it, but you can override this to ignore the event
  15768. if you want.
  15769. */
  15770. virtual void userTriedToCloseWindow();
  15771. /** Called for a desktop component which has just been minimised or un-minimised.
  15772. This will only be called for components on the desktop.
  15773. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15774. */
  15775. virtual void minimisationStateChanged (bool isNowMinimised);
  15776. /** Brings the component to the front of its siblings.
  15777. If some of the component's siblings have had their 'always-on-top' flag set,
  15778. then they will still be kept in front of this one (unless of course this
  15779. one is also 'always-on-top').
  15780. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15781. to the component (see grabKeyboardFocus() for more details)
  15782. @see toBack, toBehind, setAlwaysOnTop
  15783. */
  15784. void toFront (const bool shouldAlsoGainFocus);
  15785. /** Changes this component's z-order to be at the back of all its siblings.
  15786. If the component is set to be 'always-on-top', it will only be moved to the
  15787. back of the other other 'always-on-top' components.
  15788. @see toFront, toBehind, setAlwaysOnTop
  15789. */
  15790. void toBack();
  15791. /** Changes this component's z-order so that it's just behind another component.
  15792. @see toFront, toBack
  15793. */
  15794. void toBehind (Component* const other);
  15795. /** Sets whether the component should always be kept at the front of its siblings.
  15796. @see isAlwaysOnTop
  15797. */
  15798. void setAlwaysOnTop (const bool shouldStayOnTop);
  15799. /** Returns true if this component is set to always stay in front of its siblings.
  15800. @see setAlwaysOnTop
  15801. */
  15802. bool isAlwaysOnTop() const throw();
  15803. /** Returns the x co-ordinate of the component's left edge.
  15804. This is a distance in pixels from the left edge of the component's parent.
  15805. @see getScreenX
  15806. */
  15807. inline int getX() const throw() { return bounds_.getX(); }
  15808. /** Returns the y co-ordinate of the top of this component.
  15809. This is a distance in pixels from the top edge of the component's parent.
  15810. @see getScreenY
  15811. */
  15812. inline int getY() const throw() { return bounds_.getY(); }
  15813. /** Returns the component's width in pixels. */
  15814. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15815. /** Returns the component's height in pixels. */
  15816. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15817. /** Returns the x co-ordinate of the component's right-hand edge.
  15818. This is a distance in pixels from the left edge of the component's parent.
  15819. */
  15820. int getRight() const throw() { return bounds_.getRight(); }
  15821. /** Returns the y co-ordinate of the bottom edge of this component.
  15822. This is a distance in pixels from the top edge of the component's parent.
  15823. */
  15824. int getBottom() const throw() { return bounds_.getBottom(); }
  15825. /** Returns this component's bounding box.
  15826. The rectangle returned is relative to the top-left of the component's parent.
  15827. */
  15828. const Rectangle& getBounds() const throw() { return bounds_; }
  15829. /** Returns the region of this component that's not obscured by other, opaque components.
  15830. The RectangleList that is returned represents the area of this component
  15831. which isn't covered by opaque child components.
  15832. If includeSiblings is true, it will also take into account any siblings
  15833. that may be overlapping the component.
  15834. */
  15835. void getVisibleArea (RectangleList& result,
  15836. const bool includeSiblings) const;
  15837. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15838. @see getX, relativePositionToGlobal
  15839. */
  15840. int getScreenX() const throw();
  15841. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15842. @see getY, relativePositionToGlobal
  15843. */
  15844. int getScreenY() const throw();
  15845. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15846. @see globalPositionToRelative, relativePositionToOtherComponent
  15847. */
  15848. void relativePositionToGlobal (int& x, int& y) const throw();
  15849. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15850. @see relativePositionToGlobal, relativePositionToOtherComponent
  15851. */
  15852. void globalPositionToRelative (int& x, int& y) const throw();
  15853. /** Converts a position relative to this component's top-left into a position
  15854. relative to another component's top-left.
  15855. @see relativePositionToGlobal, globalPositionToRelative
  15856. */
  15857. void relativePositionToOtherComponent (const Component* const targetComponent,
  15858. int& x, int& y) const throw();
  15859. /** Moves the component to a new position.
  15860. Changes the component's top-left position (without changing its size).
  15861. The position is relative to the top-left of the component's parent.
  15862. If the component actually moves, this method will make a synchronous call to moved().
  15863. @see setBounds, ComponentListener::componentMovedOrResized
  15864. */
  15865. void setTopLeftPosition (const int x, const int y);
  15866. /** Moves the component to a new position.
  15867. Changes the position of the component's top-right corner (keeping it the same size).
  15868. The position is relative to the top-left of the component's parent.
  15869. If the component actually moves, this method will make a synchronous call to moved().
  15870. */
  15871. void setTopRightPosition (const int x, const int y);
  15872. /** Changes the size of the component.
  15873. A synchronous call to resized() will be occur if the size actually changes.
  15874. */
  15875. void setSize (const int newWidth, const int newHeight);
  15876. /** Changes the component's position and size.
  15877. The co-ordinates are relative to the top-left of the component's parent, or relative
  15878. to the origin of the screen is the component is on the desktop.
  15879. If this method changes the component's top-left position, it will make a synchronous
  15880. call to moved(). If it changes the size, it will also make a call to resized().
  15881. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15882. */
  15883. void setBounds (int x, int y, int width, int height);
  15884. /** Changes the component's position and size.
  15885. @see setBounds
  15886. */
  15887. void setBounds (const Rectangle& newBounds);
  15888. /** Changes the component's position and size in terms of fractions of its parent's size.
  15889. The values are factors of the parent's size, so for example
  15890. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15891. width and height of the parent, with its top-left position 20% of
  15892. the way across and down the parent.
  15893. */
  15894. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15895. const float proportionalWidth, const float proportionalHeight);
  15896. /** Changes the component's position and size based on the amount of space to leave around it.
  15897. This will position the component within its parent, leaving the specified number of
  15898. pixels around each edge.
  15899. */
  15900. void setBoundsInset (const BorderSize& borders);
  15901. /** Positions the component within a given rectangle, keeping its proportions
  15902. unchanged.
  15903. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15904. rectangle as possible without changing its aspect ratio (the component's
  15905. current size is used to determine its aspect ratio, so a zero-size component
  15906. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15907. too big to fit inside the rectangle.
  15908. It will then be positioned within the rectangle according to the justification flags
  15909. specified.
  15910. */
  15911. void setBoundsToFit (int x, int y, int width, int height,
  15912. const Justification& justification,
  15913. const bool onlyReduceInSize);
  15914. /** Changes the position of the component's centre.
  15915. Leaves the component's size unchanged, but sets the position of its centre
  15916. relative to its parent's top-left.
  15917. */
  15918. void setCentrePosition (const int x, const int y);
  15919. /** Changes the position of the component's centre.
  15920. Leaves the position unchanged, but positions its centre relative to its
  15921. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15922. its parent.
  15923. */
  15924. void setCentreRelative (const float x, const float y);
  15925. /** Changes the component's size and centres it within its parent.
  15926. After changing the size, the component will be moved so that it's
  15927. centred within its parent.
  15928. */
  15929. void centreWithSize (const int width, const int height);
  15930. /** Returns a proportion of the component's width.
  15931. This is a handy equivalent of (getWidth() * proportion).
  15932. */
  15933. int proportionOfWidth (const float proportion) const throw();
  15934. /** Returns a proportion of the component's height.
  15935. This is a handy equivalent of (getHeight() * proportion).
  15936. */
  15937. int proportionOfHeight (const float proportion) const throw();
  15938. /** Returns the width of the component's parent.
  15939. If the component has no parent (i.e. if it's on the desktop), this will return
  15940. the width of the screen.
  15941. */
  15942. int getParentWidth() const throw();
  15943. /** Returns the height of the component's parent.
  15944. If the component has no parent (i.e. if it's on the desktop), this will return
  15945. the height of the screen.
  15946. */
  15947. int getParentHeight() const throw();
  15948. /** Returns the screen co-ordinates of the monitor that contains this component.
  15949. If there's only one monitor, this will return its size - if there are multiple
  15950. monitors, it will return the area of the monitor that contains the component's
  15951. centre.
  15952. */
  15953. const Rectangle getParentMonitorArea() const throw();
  15954. /** Returns the number of child components that this component contains.
  15955. @see getChildComponent, getIndexOfChildComponent
  15956. */
  15957. int getNumChildComponents() const throw();
  15958. /** Returns one of this component's child components, by it index.
  15959. The component with index 0 is at the back of the z-order, the one at the
  15960. front will have index (getNumChildComponents() - 1).
  15961. If the index is out-of-range, this will return a null pointer.
  15962. @see getNumChildComponents, getIndexOfChildComponent
  15963. */
  15964. Component* getChildComponent (const int index) const throw();
  15965. /** Returns the index of this component in the list of child components.
  15966. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15967. values are further towards the front.
  15968. Returns -1 if the component passed-in is not a child of this component.
  15969. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15970. */
  15971. int getIndexOfChildComponent (const Component* const child) const throw();
  15972. /** Adds a child component to this one.
  15973. @param child the new component to add. If the component passed-in is already
  15974. the child of another component, it'll first be removed from that.
  15975. @param zOrder The index in the child-list at which this component should be inserted.
  15976. A value of -1 will insert it in front of the others, 0 is the back.
  15977. @see removeChildComponent, addAndMakeVisible, getChild,
  15978. ComponentListener::componentChildrenChanged
  15979. */
  15980. void addChildComponent (Component* const child,
  15981. int zOrder = -1);
  15982. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15983. Quite a useful function, this is just the same as calling addChildComponent()
  15984. followed by setVisible (true) on the child.
  15985. */
  15986. void addAndMakeVisible (Component* const child,
  15987. int zOrder = -1);
  15988. /** Removes one of this component's child-components.
  15989. If the child passed-in isn't actually a child of this component (either because
  15990. it's invalid or is the child of a different parent), then nothing is done.
  15991. Note that removing a child will not delete it!
  15992. @see addChildComponent, ComponentListener::componentChildrenChanged
  15993. */
  15994. void removeChildComponent (Component* const childToRemove);
  15995. /** Removes one of this component's child-components by index.
  15996. This will return a pointer to the component that was removed, or null if
  15997. the index was out-of-range.
  15998. Note that removing a child will not delete it!
  15999. @see addChildComponent, ComponentListener::componentChildrenChanged
  16000. */
  16001. Component* removeChildComponent (const int childIndexToRemove);
  16002. /** Removes all this component's children.
  16003. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  16004. */
  16005. void removeAllChildren();
  16006. /** Removes all this component's children, and deletes them.
  16007. @see removeAllChildren
  16008. */
  16009. void deleteAllChildren();
  16010. /** Returns the component which this component is inside.
  16011. If this is the highest-level component or hasn't yet been added to
  16012. a parent, this will return null.
  16013. */
  16014. Component* getParentComponent() const throw() { return parentComponent_; }
  16015. /** Searches the parent components for a component of a specified class.
  16016. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  16017. component that can be dynamically cast to a MyComp, or will return 0 if none
  16018. of the parents are suitable.
  16019. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  16020. */
  16021. template <class TargetClass>
  16022. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  16023. {
  16024. (void) dummyParameter;
  16025. Component* p = parentComponent_;
  16026. while (p != 0)
  16027. {
  16028. TargetClass* target = dynamic_cast <TargetClass*> (p);
  16029. if (target != 0)
  16030. return target;
  16031. p = p->parentComponent_;
  16032. }
  16033. return 0;
  16034. }
  16035. /** Returns the highest-level component which contains this one or its parents.
  16036. This will search upwards in the parent-hierarchy from this component, until it
  16037. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  16038. not yet added to a parent), and will return that.
  16039. */
  16040. Component* getTopLevelComponent() const throw();
  16041. /** Checks whether a component is anywhere inside this component or its children.
  16042. This will recursively check through this components children to see if the
  16043. given component is anywhere inside.
  16044. */
  16045. bool isParentOf (const Component* possibleChild) const throw();
  16046. /** Called to indicate that the component's parents have changed.
  16047. When a component is added or removed from its parent, this method will
  16048. be called on all of its children (recursively - so all children of its
  16049. children will also be called as well).
  16050. Subclasses can override this if they need to react to this in some way.
  16051. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  16052. */
  16053. virtual void parentHierarchyChanged();
  16054. /** Subclasses can use this callback to be told when children are added or removed.
  16055. @see parentHierarchyChanged
  16056. */
  16057. virtual void childrenChanged();
  16058. /** Tests whether a given point inside the component.
  16059. Overriding this method allows you to create components which only intercept
  16060. mouse-clicks within a user-defined area.
  16061. This is called to find out whether a particular x, y co-ordinate is
  16062. considered to be inside the component or not, and is used by methods such
  16063. as contains() and getComponentAt() to work out which component
  16064. the mouse is clicked on.
  16065. Components with custom shapes will probably want to override it to perform
  16066. some more complex hit-testing.
  16067. The default implementation of this method returns either true or false,
  16068. depending on the value that was set by calling setInterceptsMouseClicks() (true
  16069. is the default return value).
  16070. Note that the hit-test region is not related to the opacity with which
  16071. areas of a component are painted.
  16072. Applications should never call hitTest() directly - instead use the
  16073. contains() method, because this will also test for occlusion by the
  16074. component's parent.
  16075. Note that for components on the desktop, this method will be ignored, because it's
  16076. not always possible to implement this behaviour on all platforms.
  16077. @param x the x co-ordinate to test, relative to the left hand edge of this
  16078. component. This value is guaranteed to be greater than or equal to
  16079. zero, and less than the component's width
  16080. @param y the y co-ordinate to test, relative to the top edge of this
  16081. component. This value is guaranteed to be greater than or equal to
  16082. zero, and less than the component's height
  16083. @returns true if the click is considered to be inside the component
  16084. @see setInterceptsMouseClicks, contains
  16085. */
  16086. virtual bool hitTest (int x, int y);
  16087. /** Changes the default return value for the hitTest() method.
  16088. Setting this to false is an easy way to make a component pass its mouse-clicks
  16089. through to the components behind it.
  16090. When a component is created, the default setting for this is true.
  16091. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  16092. return false (or true for child components if allowClicksOnChildComponents
  16093. is true)
  16094. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  16095. components can be clicked on as normal but clicks on this component pass
  16096. straight through; if this is false and allowClicksOnThisComponent
  16097. is false, then neither this component nor any child components can
  16098. be clicked on
  16099. @see hitTest, getInterceptsMouseClicks
  16100. */
  16101. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  16102. const bool allowClicksOnChildComponents) throw();
  16103. /** Retrieves the current state of the mouse-click interception flags.
  16104. On return, the two parameters are set to the state used in the last call to
  16105. setInterceptsMouseClicks().
  16106. @see setInterceptsMouseClicks
  16107. */
  16108. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  16109. bool& allowsClicksOnChildComponents) const throw();
  16110. /** Returns true if a given point lies within this component or one of its children.
  16111. Never override this method! Use hitTest to create custom hit regions.
  16112. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16113. @param y the y co-ordinate to test, relative to this component's top edge.
  16114. @returns true if the point is within the component's hit-test area, but only if
  16115. that part of the component isn't clipped by its parent component. Note
  16116. that this won't take into account any overlapping sibling components
  16117. which might be in the way - for that, see reallyContains()
  16118. @see hitTest, reallyContains, getComponentAt
  16119. */
  16120. virtual bool contains (int x, int y);
  16121. /** Returns true if a given point lies in this component, taking any overlapping
  16122. siblings into account.
  16123. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16124. @param y the y co-ordinate to test, relative to this component's top edge.
  16125. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  16126. component, this determines the value that will
  16127. be returned.
  16128. @see contains, getComponentAt
  16129. */
  16130. bool reallyContains (int x, int y,
  16131. const bool returnTrueIfWithinAChild);
  16132. /** Returns the component at a certain point within this one.
  16133. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16134. @param y the y co-ordinate to test, relative to this component's top edge.
  16135. @returns the component that is at this position - which may be 0, this component,
  16136. or one of its children. Note that overlapping siblings that might actually
  16137. be in the way are not taken into account by this method - to account for these,
  16138. instead call getComponentAt on the top-level parent of this component.
  16139. @see hitTest, contains, reallyContains
  16140. */
  16141. Component* getComponentAt (const int x, const int y);
  16142. /** Marks the whole component as needing to be redrawn.
  16143. Calling this will not do any repainting immediately, but will mark the component
  16144. as 'dirty'. At some point in the near future the operating system will send a paint
  16145. message, which will redraw all the dirty regions of all components.
  16146. There's no guarantee about how soon after calling repaint() the redraw will actually
  16147. happen, and other queued events may be delivered before a redraw is done.
  16148. If the setBufferedToImage() method has been used to cause this component
  16149. to use a buffer, the repaint() call will invalidate the component's buffer.
  16150. To redraw just a subsection of the component rather than the whole thing,
  16151. use the repaint (int, int, int, int) method.
  16152. @see paint
  16153. */
  16154. void repaint() throw();
  16155. /** Marks a subsection of this component as needing to be redrawn.
  16156. Calling this will not do any repainting immediately, but will mark the given region
  16157. of the component as 'dirty'. At some point in the near future the operating system
  16158. will send a paint message, which will redraw all the dirty regions of all components.
  16159. There's no guarantee about how soon after calling repaint() the redraw will actually
  16160. happen, and other queued events may be delivered before a redraw is done.
  16161. The region that is passed in will be clipped to keep it within the bounds of this
  16162. component.
  16163. @see repaint()
  16164. */
  16165. void repaint (const int x, const int y,
  16166. const int width, const int height) throw();
  16167. /** Makes the component use an internal buffer to optimise its redrawing.
  16168. Setting this flag to true will cause the component to allocate an
  16169. internal buffer into which it paints itself, so that when asked to
  16170. redraw itself, it can use this buffer rather than actually calling the
  16171. paint() method.
  16172. The buffer is kept until the repaint() method is called directly on
  16173. this component (or until it is resized), when the image is invalidated
  16174. and then redrawn the next time the component is painted.
  16175. Note that only the drawing that happens within the component's paint()
  16176. method is drawn into the buffer, it's child components are not buffered, and
  16177. nor is the paintOverChildren() method.
  16178. @see repaint, paint, createComponentSnapshot
  16179. */
  16180. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16181. /** Generates a snapshot of part of this component.
  16182. This will return a new Image, the size of the rectangle specified,
  16183. containing a snapshot of the specified area of the component and all
  16184. its children.
  16185. The image may or may not have an alpha-channel, depending on whether the
  16186. image is opaque or not.
  16187. If the clipImageToComponentBounds parameter is true and the area is greater than
  16188. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16189. then parts of the component beyond its bounds can be drawn.
  16190. The caller is responsible for deleting the image that is returned.
  16191. @see paintEntireComponent
  16192. */
  16193. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16194. const bool clipImageToComponentBounds = true);
  16195. /** Draws this component and all its subcomponents onto the specified graphics
  16196. context.
  16197. You should very rarely have to use this method, it's simply there in case you need
  16198. to draw a component with a custom graphics context for some reason, e.g. for
  16199. creating a snapshot of the component.
  16200. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16201. on its children in order to render the entire tree.
  16202. The graphics context may be left in an undefined state after this method returns,
  16203. so you may need to reset it if you're going to use it again.
  16204. */
  16205. void paintEntireComponent (Graphics& context);
  16206. /** Adds an effect filter to alter the component's appearance.
  16207. When a component has an effect filter set, then this is applied to the
  16208. results of its paint() method. There are a few preset effects, such as
  16209. a drop-shadow or glow, but they can be user-defined as well.
  16210. The effect that is passed in will not be deleted by the component - the
  16211. caller must take care of deleting it.
  16212. To remove an effect from a component, pass a null pointer in as the parameter.
  16213. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16214. */
  16215. void setComponentEffect (ImageEffectFilter* const newEffect);
  16216. /** Returns the current component effect.
  16217. @see setComponentEffect
  16218. */
  16219. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16220. /** Finds the appropriate look-and-feel to use for this component.
  16221. If the component hasn't had a look-and-feel explicitly set, this will
  16222. return the parent's look-and-feel, or just the default one if there's no
  16223. parent.
  16224. @see setLookAndFeel, lookAndFeelChanged
  16225. */
  16226. LookAndFeel& getLookAndFeel() const throw();
  16227. /** Sets the look and feel to use for this component.
  16228. This will also change the look and feel for any child components that haven't
  16229. had their look set explicitly.
  16230. The object passed in will not be deleted by the component, so it's the caller's
  16231. responsibility to manage it. It may be used at any time until this component
  16232. has been deleted.
  16233. Calling this method will also invoke the sendLookAndFeelChange() method.
  16234. @see getLookAndFeel, lookAndFeelChanged
  16235. */
  16236. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16237. /** Called to let the component react to a change in the look-and-feel setting.
  16238. When the look-and-feel is changed for a component, this will be called in
  16239. all its child components, recursively.
  16240. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16241. an application uses a LookAndFeel class that might have changed internally.
  16242. @see sendLookAndFeelChange, getLookAndFeel
  16243. */
  16244. virtual void lookAndFeelChanged();
  16245. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16246. This will recurse through the children and their children, calling lookAndFeelChanged()
  16247. on them all.
  16248. @see lookAndFeelChanged
  16249. */
  16250. void sendLookAndFeelChange();
  16251. /** Indicates whether any parts of the component might be transparent.
  16252. Components that always paint all of their contents with solid colour and
  16253. thus completely cover any components behind them should use this method
  16254. to tell the repaint system that they are opaque.
  16255. This information is used to optimise drawing, because it means that
  16256. objects underneath opaque windows don't need to be painted.
  16257. By default, components are considered transparent, unless this is used to
  16258. make it otherwise.
  16259. @see isOpaque, getVisibleArea
  16260. */
  16261. void setOpaque (const bool shouldBeOpaque) throw();
  16262. /** Returns true if no parts of this component are transparent.
  16263. @returns the value that was set by setOpaque, (the default being false)
  16264. @see setOpaque
  16265. */
  16266. bool isOpaque() const throw();
  16267. /** Indicates whether the component should be brought to the front when clicked.
  16268. Setting this flag to true will cause the component to be brought to the front
  16269. when the mouse is clicked somewhere inside it or its child components.
  16270. Note that a top-level desktop window might still be brought to the front by the
  16271. operating system when it's clicked, depending on how the OS works.
  16272. By default this is set to false.
  16273. @see setMouseClickGrabsKeyboardFocus
  16274. */
  16275. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16276. /** Indicates whether the component should be brought to the front when clicked-on.
  16277. @see setBroughtToFrontOnMouseClick
  16278. */
  16279. bool isBroughtToFrontOnMouseClick() const throw();
  16280. // Keyboard focus methods
  16281. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16282. By default components aren't actually interested in gaining the
  16283. focus, but this method can be used to turn this on.
  16284. See the grabKeyboardFocus() method for details about the way a component
  16285. is chosen to receive the focus.
  16286. @see grabKeyboardFocus, getWantsKeyboardFocus
  16287. */
  16288. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16289. /** Returns true if the component is interested in getting keyboard focus.
  16290. This returns the flag set by setWantsKeyboardFocus(). The default
  16291. setting is false.
  16292. @see setWantsKeyboardFocus
  16293. */
  16294. bool getWantsKeyboardFocus() const throw();
  16295. /** Chooses whether a click on this component automatically grabs the focus.
  16296. By default this is set to true, but you might want a component which can
  16297. be focused, but where you don't want the user to be able to affect it directly
  16298. by clicking.
  16299. */
  16300. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16301. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16302. See setMouseClickGrabsKeyboardFocus() for more info.
  16303. */
  16304. bool getMouseClickGrabsKeyboardFocus() const throw();
  16305. /** Tries to give keyboard focus to this component.
  16306. When the user clicks on a component or its grabKeyboardFocus()
  16307. method is called, the following procedure is used to work out which
  16308. component should get it:
  16309. - if the component that was clicked on actually wants focus (as indicated
  16310. by calling getWantsKeyboardFocus), it gets it.
  16311. - if the component itself doesn't want focus, it will try to pass it
  16312. on to whichever of its children is the default component, as determined by
  16313. KeyboardFocusTraverser::getDefaultComponent()
  16314. - if none of its children want focus at all, it will pass it up to its
  16315. parent instead, unless it's a top-level component without a parent,
  16316. in which case it just takes the focus itself.
  16317. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16318. getCurrentlyFocusedComponent, focusGained, focusLost,
  16319. keyPressed, keyStateChanged
  16320. */
  16321. void grabKeyboardFocus();
  16322. /** Returns true if this component currently has the keyboard focus.
  16323. @param trueIfChildIsFocused if this is true, then the method returns true if
  16324. either this component or any of its children (recursively)
  16325. have the focus. If false, the method only returns true if
  16326. this component has the focus.
  16327. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16328. focusGained, focusLost
  16329. */
  16330. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16331. /** Returns the component that currently has the keyboard focus.
  16332. @returns the focused component, or null if nothing is focused.
  16333. */
  16334. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16335. /** Tries to move the keyboard focus to one of this component's siblings.
  16336. This will try to move focus to either the next or previous component. (This
  16337. is the method that is used when shifting focus by pressing the tab key).
  16338. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16339. @param moveToNext if true, the focus will move forwards; if false, it will
  16340. move backwards
  16341. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16342. */
  16343. void moveKeyboardFocusToSibling (const bool moveToNext);
  16344. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16345. which focus should be passed from this component.
  16346. The default implementation of this method will return a default
  16347. KeyboardFocusTraverser if this component is a focus container (as determined
  16348. by the setFocusContainer() method). If the component isn't a focus
  16349. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16350. If you overrride this to return a custom KeyboardFocusTraverser, then
  16351. this component and all its sub-components will use the new object to
  16352. make their focusing decisions.
  16353. The method should return a new object, which the caller is required to
  16354. delete when no longer needed.
  16355. */
  16356. virtual KeyboardFocusTraverser* createFocusTraverser();
  16357. /** Returns the focus order of this component, if one has been specified.
  16358. By default components don't have a focus order - in that case, this
  16359. will return 0. Lower numbers indicate that the component will be
  16360. earlier in the focus traversal order.
  16361. To change the order, call setExplicitFocusOrder().
  16362. The focus order may be used by the KeyboardFocusTraverser class as part of
  16363. its algorithm for deciding the order in which components should be traversed.
  16364. See the KeyboardFocusTraverser class for more details on this.
  16365. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16366. */
  16367. int getExplicitFocusOrder() const throw();
  16368. /** Sets the index used in determining the order in which focusable components
  16369. should be traversed.
  16370. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16371. that traversal should use other factors, like the component's position.
  16372. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16373. */
  16374. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16375. /** Indicates whether this component is a parent for components that can have
  16376. their focus traversed.
  16377. This flag is used by the default implementation of the createFocusTraverser()
  16378. method, which uses the flag to find the first parent component (of the currently
  16379. focused one) which wants to be a focus container.
  16380. So using this method to set the flag to 'true' causes this component to
  16381. act as the top level within which focus is passed around.
  16382. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16383. */
  16384. void setFocusContainer (const bool isFocusContainer) throw();
  16385. /** Returns true if this component has been marked as a focus container.
  16386. See setFocusContainer() for more details.
  16387. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16388. */
  16389. bool isFocusContainer() const throw();
  16390. /** Returns true if the component (and all its parents) are enabled.
  16391. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16392. what difference this makes to the component depends on the type. E.g. buttons
  16393. and sliders will choose to draw themselves differently, etc.
  16394. Note that if one of this component's parents is disabled, this will always
  16395. return false, even if this component itself is enabled.
  16396. @see setEnabled, enablementChanged
  16397. */
  16398. bool isEnabled() const throw();
  16399. /** Enables or disables this component.
  16400. Disabling a component will also cause all of its child components to become
  16401. disabled.
  16402. Similarly, enabling a component which is inside a disabled parent
  16403. component won't make any difference until the parent is re-enabled.
  16404. @see isEnabled, enablementChanged
  16405. */
  16406. void setEnabled (const bool shouldBeEnabled);
  16407. /** Callback to indicate that this component has been enabled or disabled.
  16408. This can be triggered by one of the component's parent components
  16409. being enabled or disabled, as well as changes to the component itself.
  16410. The default implementation of this method does nothing; your class may
  16411. wish to repaint itself or something when this happens.
  16412. @see setEnabled, isEnabled
  16413. */
  16414. virtual void enablementChanged();
  16415. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16416. Note that the cursor set by this method can be overridden by the getMouseCursor
  16417. method.
  16418. @see MouseCursor
  16419. */
  16420. void setMouseCursor (const MouseCursor& cursorType) throw();
  16421. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16422. The default implementation will return the cursor that was set by setCursor()
  16423. but can be overridden for more specialised purposes, e.g. returning different
  16424. cursors depending on the mouse position.
  16425. @see MouseCursor
  16426. */
  16427. virtual const MouseCursor getMouseCursor();
  16428. /** Forces the current mouse cursor to be updated.
  16429. If you're overriding the getMouseCursor() method to control which cursor is
  16430. displayed, then this will only be checked each time the user moves the mouse. So
  16431. if you want to force the system to check that the cursor being displayed is
  16432. up-to-date (even if the mouse is just sitting there), call this method.
  16433. This isn't needed if you're only using setMouseCursor().
  16434. */
  16435. void updateMouseCursor() const throw();
  16436. /** Components can override this method to draw their content.
  16437. The paint() method gets called when a region of a component needs redrawing,
  16438. either because the component's repaint() method has been called, or because
  16439. something has happened on the screen that means a section of a window needs
  16440. to be redrawn.
  16441. Any child components will draw themselves over whatever this method draws. If
  16442. you need to paint over the top of your child components, you can also implement
  16443. the paintOverChildren() method to do this.
  16444. If you want to cause a component to redraw itself, this is done asynchronously -
  16445. calling the repaint() method marks a region of the component as "dirty", and the
  16446. paint() method will automatically be called sometime later, by the message thread,
  16447. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16448. you never redraw something synchronously.
  16449. You should never need to call this method directly - to take a snapshot of the
  16450. component you could use createComponentSnapshot() or paintEntireComponent().
  16451. @param g the graphics context that must be used to do the drawing operations.
  16452. @see repaint, paintOverChildren, Graphics
  16453. */
  16454. virtual void paint (Graphics& g);
  16455. /** Components can override this method to draw over the top of their children.
  16456. For most drawing operations, it's better to use the normal paint() method,
  16457. but if you need to overlay something on top of the children, this can be
  16458. used.
  16459. @see paint, Graphics
  16460. */
  16461. virtual void paintOverChildren (Graphics& g);
  16462. /** Called when the mouse moves inside this component.
  16463. If the mouse button isn't pressed and the mouse moves over a component,
  16464. this will be called to let the component react to this.
  16465. A component will always get a mouseEnter callback before a mouseMove.
  16466. @param e details about the position and status of the mouse event
  16467. @see mouseEnter, mouseExit, mouseDrag, contains
  16468. */
  16469. virtual void mouseMove (const MouseEvent& e);
  16470. /** Called when the mouse first enters this component.
  16471. If the mouse button isn't pressed and the mouse moves into a component,
  16472. this will be called to let the component react to this.
  16473. When the mouse button is pressed and held down while being moved in
  16474. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16475. mouseDrag messages are sent to the component that the mouse was originally
  16476. clicked on, until the button is released.
  16477. If you're writing a component that needs to repaint itself when the mouse
  16478. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16479. method.
  16480. @param e details about the position and status of the mouse event
  16481. @see mouseExit, mouseDrag, mouseMove, contains
  16482. */
  16483. virtual void mouseEnter (const MouseEvent& e);
  16484. /** Called when the mouse moves out of this component.
  16485. This will be called when the mouse moves off the edge of this
  16486. component.
  16487. If the mouse button was pressed, and it was then dragged off the
  16488. edge of the component and released, then this callback will happen
  16489. when the button is released, after the mouseUp callback.
  16490. If you're writing a component that needs to repaint itself when the mouse
  16491. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16492. method.
  16493. @param e details about the position and status of the mouse event
  16494. @see mouseEnter, mouseDrag, mouseMove, contains
  16495. */
  16496. virtual void mouseExit (const MouseEvent& e);
  16497. /** Called when a mouse button is pressed while it's over this component.
  16498. The MouseEvent object passed in contains lots of methods for finding out
  16499. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16500. were held down at the time.
  16501. Once a button is held down, the mouseDrag method will be called when the
  16502. mouse moves, until the button is released.
  16503. @param e details about the position and status of the mouse event
  16504. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16505. */
  16506. virtual void mouseDown (const MouseEvent& e);
  16507. /** Called when the mouse is moved while a button is held down.
  16508. When a mouse button is pressed inside a component, that component
  16509. receives mouseDrag callbacks each time the mouse moves, even if the
  16510. mouse strays outside the component's bounds.
  16511. If you want to be able to drag things off the edge of a component
  16512. and have the component scroll when you get to the edges, the
  16513. beginDragAutoRepeat() method might be useful.
  16514. @param e details about the position and status of the mouse event
  16515. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16516. */
  16517. virtual void mouseDrag (const MouseEvent& e);
  16518. /** Called when a mouse button is released.
  16519. A mouseUp callback is sent to the component in which a button was pressed
  16520. even if the mouse is actually over a different component when the
  16521. button is released.
  16522. The MouseEvent object passed in contains lots of methods for finding out
  16523. which buttons were down just before they were released.
  16524. @param e details about the position and status of the mouse event
  16525. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16526. */
  16527. virtual void mouseUp (const MouseEvent& e);
  16528. /** Called when a mouse button has been double-clicked in this component.
  16529. The MouseEvent object passed in contains lots of methods for finding out
  16530. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16531. were held down at the time.
  16532. For altering the time limit used to detect double-clicks,
  16533. see MouseEvent::setDoubleClickTimeout.
  16534. @param e details about the position and status of the mouse event
  16535. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16536. MouseEvent::getDoubleClickTimeout
  16537. */
  16538. virtual void mouseDoubleClick (const MouseEvent& e);
  16539. /** Called when the mouse-wheel is moved.
  16540. This callback is sent to the component that the mouse is over when the
  16541. wheel is moved.
  16542. If not overridden, the component will forward this message to its parent, so
  16543. that parent components can collect mouse-wheel messages that happen to
  16544. child components which aren't interested in them.
  16545. @param e details about the position and status of the mouse event
  16546. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16547. value means the wheel has been pushed to the right, negative means it
  16548. was pushed to the left
  16549. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16550. value means the wheel has been pushed upwards, negative means it
  16551. was pushed downwards
  16552. */
  16553. virtual void mouseWheelMove (const MouseEvent& e,
  16554. float wheelIncrementX,
  16555. float wheelIncrementY);
  16556. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16557. next mouse-drag operation.
  16558. This allows you to make sure that mouseDrag() events sent continuously, even
  16559. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16560. components when the mouse is near an edge.
  16561. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16562. minimum interval between consecutive mouse drag callbacks. The callbacks
  16563. will continue until the mouse is released, and then the interval will be reset,
  16564. so you need to make sure it's called every time you begin a drag event. If it
  16565. is called when the mouse isn't actually being pressed, it will apply to the next
  16566. mouse-drag operation that happens.
  16567. Passing an interval of 0 or less will cancel the auto-repeat.
  16568. @see mouseDrag
  16569. */
  16570. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16571. /** Causes automatic repaints when the mouse enters or exits this component.
  16572. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16573. on the component, it will trigger a repaint.
  16574. This is handy for things like buttons that need to draw themselves differently when
  16575. the mouse moves over them, and it avoids having to override all the different mouse
  16576. callbacks and call repaint().
  16577. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16578. */
  16579. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16580. /** Registers a listener to be told when mouse events occur in this component.
  16581. If you need to get informed about mouse events in a component but can't or
  16582. don't want to override its methods, you can attach any number of listeners
  16583. to the component, and these will get told about the events in addition to
  16584. the component's own callbacks being called.
  16585. Note that a MouseListener can also be attached to more than one component.
  16586. @param newListener the listener to register
  16587. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16588. for events that happen to any child component
  16589. within this component, including deeply-nested
  16590. child components. If false, it will only be
  16591. told about events that this component handles.
  16592. @see MouseListener, removeMouseListener
  16593. */
  16594. void addMouseListener (MouseListener* const newListener,
  16595. const bool wantsEventsForAllNestedChildComponents) throw();
  16596. /** Deregisters a mouse listener.
  16597. @see addMouseListener, MouseListener
  16598. */
  16599. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16600. /** Adds a listener that wants to hear about keypresses that this component receives.
  16601. The listeners that are registered with a component are called by its keyPressed() or
  16602. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16603. If you add an object as a key listener, be careful to remove it when the object
  16604. is deleted, or the component will be left with a dangling pointer.
  16605. @see keyPressed, keyStateChanged, removeKeyListener
  16606. */
  16607. void addKeyListener (KeyListener* const newListener) throw();
  16608. /** Removes a previously-registered key listener.
  16609. @see addKeyListener
  16610. */
  16611. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16612. /** Called when a key is pressed.
  16613. When a key is pressed, the component that has the keyboard focus will have this
  16614. method called. Remember that a component will only be given the focus if its
  16615. setWantsKeyboardFocus() method has been used to enable this.
  16616. If your implementation returns true, the event will be consumed and not passed
  16617. on to any other listeners. If it returns false, the key will be passed to any
  16618. KeyListeners that have been registered with this component. As soon as one of these
  16619. returns true, the process will stop, but if they all return false, the event will
  16620. be passed upwards to this component's parent, and so on.
  16621. The default implementation of this method does nothing and returns false.
  16622. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16623. */
  16624. virtual bool keyPressed (const KeyPress& key);
  16625. /** Called when a key is pressed or released.
  16626. Whenever a key on the keyboard is pressed or released (including modifier keys
  16627. like shift and ctrl), this method will be called on the component that currently
  16628. has the keyboard focus. Remember that a component will only be given the focus if
  16629. its setWantsKeyboardFocus() method has been used to enable this.
  16630. If your implementation returns true, the event will be consumed and not passed
  16631. on to any other listeners. If it returns false, then any KeyListeners that have
  16632. been registered with this component will have their keyStateChanged methods called.
  16633. As soon as one of these returns true, the process will stop, but if they all return
  16634. false, the event will be passed upwards to this component's parent, and so on.
  16635. The default implementation of this method does nothing and returns false.
  16636. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16637. method.
  16638. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16639. */
  16640. virtual bool keyStateChanged();
  16641. /** Called when a modifier key is pressed or released.
  16642. Whenever the shift, control, alt or command keys are pressed or released,
  16643. this method will be called on the component that currently has the keyboard focus.
  16644. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16645. method has been used to enable this.
  16646. The default implementation of this method actually calls its parent's modifierKeysChanged
  16647. method, so that focused components which aren't interested in this will give their
  16648. parents a chance to act on the event instead.
  16649. @see keyStateChanged, ModifierKeys
  16650. */
  16651. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16652. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16653. enum FocusChangeType
  16654. {
  16655. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16656. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16657. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16658. };
  16659. /** Called to indicate that this component has just acquired the keyboard focus.
  16660. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16661. */
  16662. virtual void focusGained (FocusChangeType cause);
  16663. /** Called to indicate that this component has just lost the keyboard focus.
  16664. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16665. */
  16666. virtual void focusLost (FocusChangeType cause);
  16667. /** Called to indicate that one of this component's children has been focused or unfocused.
  16668. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16669. changed. It happens when focus moves from one of this component's children (at any depth)
  16670. to a component that isn't contained in this one, (or vice-versa).
  16671. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16672. */
  16673. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16674. /** Returns true if the mouse is currently over this component.
  16675. If the mouse isn't over the component, this will return false, even if the
  16676. mouse is currently being dragged - so you can use this in your mouseDrag
  16677. method to find out whether it's really over the component or not.
  16678. Note that when the mouse button is being held down, then the only component
  16679. for which this method will return true is the one that was originally
  16680. clicked on.
  16681. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16682. */
  16683. bool isMouseOver() const throw();
  16684. /** Returns true if the mouse button is currently held down in this component.
  16685. Note that this is a test to see whether the mouse is being pressed in this
  16686. component, so it'll return false if called on component A when the mouse
  16687. is actually being dragged in component B.
  16688. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16689. */
  16690. bool isMouseButtonDown() const throw();
  16691. /** True if the mouse is over this component, or if it's being dragged in this component.
  16692. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16693. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16694. */
  16695. bool isMouseOverOrDragging() const throw();
  16696. /** Returns true if a mouse button is currently down.
  16697. Unlike isMouseButtonDown, this will test the current state of the
  16698. buttons without regard to which component (if any) it has been
  16699. pressed in.
  16700. @see isMouseButtonDown, ModifierKeys
  16701. */
  16702. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16703. /** Returns the mouse's current position, relative to this component.
  16704. The co-ordinates are relative to the component's top-left corner.
  16705. */
  16706. void getMouseXYRelative (int& x, int& y) const throw();
  16707. /** Returns the component that's currently underneath the mouse.
  16708. @returns the component or 0 if there isn't one.
  16709. @see contains, getComponentAt
  16710. */
  16711. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16712. /** Allows the mouse to move beyond the edges of the screen.
  16713. Calling this method when the mouse button is currently pressed inside this component
  16714. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16715. the edges of the screen.
  16716. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16717. can be used for things like custom slider controls or dragging objects around, where
  16718. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16719. The unbounded mode is automatically turned off when the mouse button is released, or
  16720. it can be turned off explicitly by calling this method again.
  16721. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16722. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16723. hidden; if true, it will only be hidden when it
  16724. is moved beyond the edge of the screen
  16725. */
  16726. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16727. bool keepCursorVisibleUntilOffscreen = false) throw();
  16728. /** Called when this component's size has been changed.
  16729. A component can implement this method to do things such as laying out its
  16730. child components when its width or height changes.
  16731. The method is called synchronously as a result of the setBounds or setSize
  16732. methods, so repeatedly changing a components size will repeatedly call its
  16733. resized method (unlike things like repainting, where multiple calls to repaint
  16734. are coalesced together).
  16735. If the component is a top-level window on the desktop, its size could also
  16736. be changed by operating-system factors beyond the application's control.
  16737. @see moved, setSize
  16738. */
  16739. virtual void resized();
  16740. /** Called when this component's position has been changed.
  16741. This is called when the position relative to its parent changes, not when
  16742. its absolute position on the screen changes (so it won't be called for
  16743. all child components when a parent component is moved).
  16744. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16745. or any of the other repositioning methods, and like resized(), it will be
  16746. called each time those methods are called.
  16747. If the component is a top-level window on the desktop, its position could also
  16748. be changed by operating-system factors beyond the application's control.
  16749. @see resized, setBounds
  16750. */
  16751. virtual void moved();
  16752. /** Called when one of this component's children is moved or resized.
  16753. If the parent wants to know about changes to its immediate children (not
  16754. to children of its children), this is the method to override.
  16755. @see moved, resized, parentSizeChanged
  16756. */
  16757. virtual void childBoundsChanged (Component* child);
  16758. /** Called when this component's immediate parent has been resized.
  16759. If the component is a top-level window, this indicates that the screen size
  16760. has changed.
  16761. @see childBoundsChanged, moved, resized
  16762. */
  16763. virtual void parentSizeChanged();
  16764. /** Called when this component has been moved to the front of its siblings.
  16765. The component may have been brought to the front by the toFront() method, or
  16766. by the operating system if it's a top-level window.
  16767. @see toFront
  16768. */
  16769. virtual void broughtToFront();
  16770. /** Adds a listener to be told about changes to the component hierarchy or position.
  16771. Component listeners get called when this component's size, position or children
  16772. change - see the ComponentListener class for more details.
  16773. @param newListener the listener to register - if this is already registered, it
  16774. will be ignored.
  16775. @see ComponentListener, removeComponentListener
  16776. */
  16777. void addComponentListener (ComponentListener* const newListener) throw();
  16778. /** Removes a component listener.
  16779. @see addComponentListener
  16780. */
  16781. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16782. /** Dispatches a numbered message to this component.
  16783. This is a quick and cheap way of allowing simple asynchronous messages to
  16784. be sent to components. It's also safe, because if the component that you
  16785. send the message to is a null or dangling pointer, this won't cause an error.
  16786. The command ID is later delivered to the component's handleCommandMessage() method by
  16787. the application's message queue.
  16788. @see handleCommandMessage
  16789. */
  16790. void postCommandMessage (const int commandId) throw();
  16791. /** Called to handle a command that was sent by postCommandMessage().
  16792. This is called by the message thread when a command message arrives, and
  16793. the component can override this method to process it in any way it needs to.
  16794. @see postCommandMessage
  16795. */
  16796. virtual void handleCommandMessage (int commandId);
  16797. /** Runs a component modally, waiting until the loop terminates.
  16798. This method first makes the component visible, brings it to the front and
  16799. gives it the keyboard focus.
  16800. It then runs a loop, dispatching messages from the system message queue, but
  16801. blocking all mouse or keyboard messages from reaching any components other
  16802. than this one and its children.
  16803. This loop continues until the component's exitModalState() method is called (or
  16804. the component is deleted), and then this method returns, returning the value
  16805. passed into exitModalState().
  16806. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16807. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16808. */
  16809. int runModalLoop();
  16810. /** Puts the component into a modal state.
  16811. This makes the component modal, so that messages are blocked from reaching
  16812. any components other than this one and its children, but unlike runModalLoop(),
  16813. this method returns immediately.
  16814. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16815. get the focus, which is usually what you'll want it to do. If not, it will leave
  16816. the focus unchanged.
  16817. @see exitModalState, runModalLoop
  16818. */
  16819. void enterModalState (const bool takeKeyboardFocus = true);
  16820. /** Ends a component's modal state.
  16821. If this component is currently modal, this will turn of its modalness, and return
  16822. a value to the runModalLoop() method that might have be running its modal loop.
  16823. @see runModalLoop, enterModalState, isCurrentlyModal
  16824. */
  16825. void exitModalState (const int returnValue);
  16826. /** Returns true if this component is the modal one.
  16827. It's possible to have nested modal components, e.g. a pop-up dialog box
  16828. that launches another pop-up, but this will only return true for
  16829. the one at the top of the stack.
  16830. @see getCurrentlyModalComponent
  16831. */
  16832. bool isCurrentlyModal() const throw();
  16833. /** Returns the number of components that are currently in a modal state.
  16834. @see getCurrentlyModalComponent
  16835. */
  16836. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  16837. /** Returns one of the components that are currently modal.
  16838. The index specifies which of the possible modal components to return. The order
  16839. of the components in this list is the reverse of the order in which they became
  16840. modal - so the component at index 0 is always the active component, and the others
  16841. are progressively earlier ones that are themselves now blocked by later ones.
  16842. @returns the modal component, or null if no components are modal (or if the
  16843. index is out of range)
  16844. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  16845. */
  16846. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  16847. /** Checks whether there's a modal component somewhere that's stopping this one
  16848. from receiving messages.
  16849. If there is a modal component, its canModalEventBeSentToComponent() method
  16850. will be called to see if it will still allow this component to receive events.
  16851. @see runModalLoop, getCurrentlyModalComponent
  16852. */
  16853. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16854. /** When a component is modal, this callback allows it to choose which other
  16855. components can still receive events.
  16856. When a modal component is active and the user clicks on a non-modal component,
  16857. this method is called on the modal component, and if it returns true, the
  16858. event is allowed to reach its target. If it returns false, the event is blocked
  16859. and the inputAttemptWhenModal() callback is made.
  16860. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16861. implementation just returns false in all cases.
  16862. */
  16863. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16864. /** Called when the user tries to click on a component that is blocked by another
  16865. modal component.
  16866. When a component is modal and the user clicks on one of the other components,
  16867. the modal component will receive this callback.
  16868. The default implementation of this method will play a beep, and bring the currently
  16869. modal component to the front, but it can be overridden to do other tasks.
  16870. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16871. */
  16872. virtual void inputAttemptWhenModal();
  16873. /** Returns one of the component's properties as a string.
  16874. @param keyName the name of the property to retrieve
  16875. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16876. properties, then it will check whether the parent component has
  16877. the key.
  16878. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16879. */
  16880. const String getComponentProperty (const String& keyName,
  16881. const bool useParentComponentIfNotFound,
  16882. const String& defaultReturnValue = String::empty) const throw();
  16883. /** Returns one of the properties as an integer.
  16884. @param keyName the name of the property to retrieve
  16885. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16886. properties, then it will check whether the parent component has
  16887. the key.
  16888. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16889. */
  16890. int getComponentPropertyInt (const String& keyName,
  16891. const bool useParentComponentIfNotFound,
  16892. const int defaultReturnValue = 0) const throw();
  16893. /** Returns one of the properties as an double.
  16894. @param keyName the name of the property to retrieve
  16895. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16896. properties, then it will check whether the parent component has
  16897. the key.
  16898. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16899. */
  16900. double getComponentPropertyDouble (const String& keyName,
  16901. const bool useParentComponentIfNotFound,
  16902. const double defaultReturnValue = 0.0) const throw();
  16903. /** Returns one of the properties as an boolean.
  16904. The result will be true if the string found for this key name can be parsed as a non-zero
  16905. integer.
  16906. @param keyName the name of the property to retrieve
  16907. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16908. properties, then it will check whether the parent component has
  16909. the key.
  16910. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16911. */
  16912. bool getComponentPropertyBool (const String& keyName,
  16913. const bool useParentComponentIfNotFound,
  16914. const bool defaultReturnValue = false) const throw();
  16915. /** Returns one of the properties as an colour.
  16916. @param keyName the name of the property to retrieve
  16917. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16918. properties, then it will check whether the parent component has
  16919. the key.
  16920. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16921. */
  16922. const Colour getComponentPropertyColour (const String& keyName,
  16923. const bool useParentComponentIfNotFound,
  16924. const Colour& defaultReturnValue = Colours::black) const throw();
  16925. /** Sets a named property as a string.
  16926. @param keyName the name of the property to set. (This mustn't be an empty string)
  16927. @param value the new value to set it to
  16928. @see removeComponentProperty
  16929. */
  16930. void setComponentProperty (const String& keyName, const String& value) throw();
  16931. /** Sets a named property to an integer.
  16932. @param keyName the name of the property to set. (This mustn't be an empty string)
  16933. @param value the new value to set it to
  16934. @see removeComponentProperty
  16935. */
  16936. void setComponentProperty (const String& keyName, const int value) throw();
  16937. /** Sets a named property to a double.
  16938. @param keyName the name of the property to set. (This mustn't be an empty string)
  16939. @param value the new value to set it to
  16940. @see removeComponentProperty
  16941. */
  16942. void setComponentProperty (const String& keyName, const double value) throw();
  16943. /** Sets a named property to a boolean.
  16944. @param keyName the name of the property to set. (This mustn't be an empty string)
  16945. @param value the new value to set it to
  16946. @see removeComponentProperty
  16947. */
  16948. void setComponentProperty (const String& keyName, const bool value) throw();
  16949. /** Sets a named property to a colour.
  16950. @param keyName the name of the property to set. (This mustn't be an empty string)
  16951. @param newColour the new colour to set it to
  16952. @see removeComponentProperty
  16953. */
  16954. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16955. /** Deletes a named component property.
  16956. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16957. @see setComponentProperty, getComponentProperty
  16958. */
  16959. void removeComponentProperty (const String& keyName) throw();
  16960. /** Returns the complete set of properties that have been set for this component.
  16961. If no properties have been set, this will return a null pointer.
  16962. @see getComponentProperty, setComponentProperty
  16963. */
  16964. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16965. /** Looks for a colour that has been registered with the given colour ID number.
  16966. If a colour has been set for this ID number using setColour(), then it is
  16967. returned. If none has been set, the method will try calling the component's
  16968. LookAndFeel class's findColour() method. If none has been registered with the
  16969. look-and-feel either, it will just return black.
  16970. The colour IDs for various purposes are stored as enums in the components that
  16971. they are relevent to - for an example, see Slider::ColourIds,
  16972. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16973. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16974. */
  16975. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16976. /** Registers a colour to be used for a particular purpose.
  16977. Changing a colour will cause a synchronous callback to the colourChanged()
  16978. method, which your component can override if it needs to do something when
  16979. colours are altered.
  16980. For more details about colour IDs, see the comments for findColour().
  16981. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16982. */
  16983. void setColour (const int colourId, const Colour& colour);
  16984. /** If a colour has been set with setColour(), this will remove it.
  16985. This allows you to make a colour revert to its default state.
  16986. */
  16987. void removeColour (const int colourId);
  16988. /** Returns true if the specified colour ID has been explicitly set for this
  16989. component using the setColour() method.
  16990. */
  16991. bool isColourSpecified (const int colourId) const throw();
  16992. /** This looks for any colours that have been specified for this component,
  16993. and copies them to the specified target component.
  16994. */
  16995. void copyAllExplicitColoursTo (Component& target) const throw();
  16996. /** This method is called when a colour is changed by the setColour() method.
  16997. @see setColour, findColour
  16998. */
  16999. virtual void colourChanged();
  17000. /** Returns the underlying native window handle for this component.
  17001. This is platform-dependent and strictly for power-users only!
  17002. */
  17003. void* getWindowHandle() const throw();
  17004. /** When created, each component is given a number to uniquely identify it.
  17005. The number is incremented each time a new component is created, so it's a more
  17006. unique way of identifying a component than using its memory location (which
  17007. may be reused after the component is deleted, of course).
  17008. */
  17009. uint32 getComponentUID() const throw() { return componentUID; }
  17010. juce_UseDebuggingNewOperator
  17011. private:
  17012. friend class ComponentPeer;
  17013. friend class InternalDragRepeater;
  17014. static Component* currentlyFocusedComponent;
  17015. static Component* componentUnderMouse;
  17016. String componentName_;
  17017. Component* parentComponent_;
  17018. uint32 componentUID;
  17019. Rectangle bounds_;
  17020. unsigned short numDeepMouseListeners;
  17021. Array <Component*> childComponentList_;
  17022. LookAndFeel* lookAndFeel_;
  17023. MouseCursor cursor_;
  17024. ImageEffectFilter* effect_;
  17025. Image* bufferedImage_;
  17026. VoidArray* mouseListeners_;
  17027. VoidArray* keyListeners_;
  17028. VoidArray* componentListeners_;
  17029. PropertySet* propertySet_;
  17030. struct ComponentFlags
  17031. {
  17032. bool hasHeavyweightPeerFlag : 1;
  17033. bool visibleFlag : 1;
  17034. bool opaqueFlag : 1;
  17035. bool ignoresMouseClicksFlag : 1;
  17036. bool allowChildMouseClicksFlag : 1;
  17037. bool wantsFocusFlag : 1;
  17038. bool isFocusContainerFlag : 1;
  17039. bool dontFocusOnMouseClickFlag : 1;
  17040. bool alwaysOnTopFlag : 1;
  17041. bool bufferToImageFlag : 1;
  17042. bool bringToFrontOnClickFlag : 1;
  17043. bool repaintOnMouseActivityFlag : 1;
  17044. bool draggingFlag : 1;
  17045. bool mouseOverFlag : 1;
  17046. bool mouseInsideFlag : 1;
  17047. bool currentlyModalFlag : 1;
  17048. bool isDisabledFlag : 1;
  17049. bool childCompFocusedFlag : 1;
  17050. #ifdef JUCE_DEBUG
  17051. bool isInsidePaintCall : 1;
  17052. #endif
  17053. };
  17054. union
  17055. {
  17056. uint32 componentFlags_;
  17057. ComponentFlags flags;
  17058. };
  17059. void internalMouseEnter (int x, int y, const int64 time);
  17060. void internalMouseExit (int x, int y, const int64 time);
  17061. void internalMouseDown (int x, int y);
  17062. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  17063. void internalMouseDrag (int x, int y, const int64 time);
  17064. void internalMouseMove (int x, int y, const int64 time);
  17065. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  17066. void internalBroughtToFront();
  17067. void internalFocusGain (const FocusChangeType cause);
  17068. void internalFocusLoss (const FocusChangeType cause);
  17069. void internalChildFocusChange (FocusChangeType cause);
  17070. void internalModalInputAttempt();
  17071. void internalModifierKeysChanged();
  17072. void internalChildrenChanged();
  17073. void internalHierarchyChanged();
  17074. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  17075. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  17076. void repaintParent() throw();
  17077. void sendFakeMouseMove() const;
  17078. void takeKeyboardFocus (const FocusChangeType cause);
  17079. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  17080. static void giveAwayFocus();
  17081. void sendEnablementChangeMessage();
  17082. static void* runModalLoopCallback (void*);
  17083. void subtractObscuredRegions (RectangleList& result,
  17084. const int deltaX, const int deltaY,
  17085. const Rectangle& clipRect,
  17086. const Component* const compToAvoid) const throw();
  17087. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  17088. const int deltaX, const int deltaY) const throw();
  17089. // how much of the component is not off the edges of its parents
  17090. const Rectangle getUnclippedArea() const;
  17091. void sendVisibilityChangeMessage();
  17092. // This is included here just to cause a compile error if your code is still handling
  17093. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  17094. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  17095. // implement its methods instead of this Component method).
  17096. virtual void filesDropped (const StringArray&, int, int) {}
  17097. // components aren't allowed to have copy constructors, as this would mess up parent
  17098. // hierarchies. You might need to give your subclasses a private dummy constructor like
  17099. // this one to avoid compiler warnings.
  17100. Component (const Component&);
  17101. const Component& operator= (const Component&);
  17102. protected:
  17103. /** @internal */
  17104. virtual void internalRepaint (int x, int y, int w, int h);
  17105. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  17106. /** Overridden from the MessageListener parent class.
  17107. You can override this if you really need to, but be sure to pass your unwanted messages up
  17108. to this base class implementation, as the Component class needs to send itself messages
  17109. to work properly.
  17110. */
  17111. void handleMessage (const Message&);
  17112. };
  17113. #endif // __JUCE_COMPONENT_JUCEHEADER__
  17114. /********* End of inlined file: juce_Component.h *********/
  17115. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  17116. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17117. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17118. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  17119. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17120. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17121. /** A type used to hold the unique ID for an application command.
  17122. This is a numeric type, so it can be stored as an integer.
  17123. @see ApplicationCommandInfo, ApplicationCommandManager,
  17124. ApplicationCommandTarget, KeyPressMappingSet
  17125. */
  17126. typedef int CommandID;
  17127. /** A set of general-purpose application command IDs.
  17128. Because these commands are likely to be used in most apps, they're defined
  17129. here to help different apps to use the same numeric values for them.
  17130. Of course you don't have to use these, but some of them are used internally by
  17131. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  17132. @see ApplicationCommandInfo, ApplicationCommandManager,
  17133. ApplicationCommandTarget, KeyPressMappingSet
  17134. */
  17135. namespace StandardApplicationCommandIDs
  17136. {
  17137. /** This command ID should be used to send a "Quit the App" command.
  17138. This command is recognised by the JUCEApplication class, so if it is invoked
  17139. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  17140. object will catch it and call JUCEApplication::systemRequestedQuit().
  17141. */
  17142. static const CommandID quit = 0x1001;
  17143. /** The command ID that should be used to send a "Delete" command. */
  17144. static const CommandID del = 0x1002;
  17145. /** The command ID that should be used to send a "Cut" command. */
  17146. static const CommandID cut = 0x1003;
  17147. /** The command ID that should be used to send a "Copy to clipboard" command. */
  17148. static const CommandID copy = 0x1004;
  17149. /** The command ID that should be used to send a "Paste from clipboard" command. */
  17150. static const CommandID paste = 0x1005;
  17151. /** The command ID that should be used to send a "Select all" command. */
  17152. static const CommandID selectAll = 0x1006;
  17153. /** The command ID that should be used to send a "Deselect all" command. */
  17154. static const CommandID deselectAll = 0x1007;
  17155. }
  17156. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17157. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  17158. /**
  17159. Holds information describing an application command.
  17160. This object is used to pass information about a particular command, such as its
  17161. name, description and other usage flags.
  17162. When an ApplicationCommandTarget is asked to provide information about the commands
  17163. it can perform, this is the structure gets filled-in to describe each one.
  17164. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  17165. ApplicationCommandManager
  17166. */
  17167. struct JUCE_API ApplicationCommandInfo
  17168. {
  17169. ApplicationCommandInfo (const CommandID commandID) throw();
  17170. /** Sets a number of the structures values at once.
  17171. The meanings of each of the parameters is described below, in the appropriate
  17172. member variable's description.
  17173. */
  17174. void setInfo (const String& shortName,
  17175. const String& description,
  17176. const String& categoryName,
  17177. const int flags) throw();
  17178. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17179. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17180. is false, the bit is set.
  17181. */
  17182. void setActive (const bool isActive) throw();
  17183. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17184. */
  17185. void setTicked (const bool isTicked) throw();
  17186. /** Handy method for adding a keypress to the defaultKeypresses array.
  17187. This is just so you can write things like:
  17188. @code
  17189. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17190. @endcode
  17191. instead of
  17192. @code
  17193. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17194. @endcode
  17195. */
  17196. void addDefaultKeypress (const int keyCode,
  17197. const ModifierKeys& modifiers) throw();
  17198. /** The command's unique ID number.
  17199. */
  17200. CommandID commandID;
  17201. /** A short name to describe the command.
  17202. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17203. You can use the setInfo() method to quickly set this and some of the command's
  17204. other properties.
  17205. */
  17206. String shortName;
  17207. /** A longer description of the command.
  17208. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17209. pop-up tooltip describing what the command does.
  17210. You can use the setInfo() method to quickly set this and some of the command's
  17211. other properties.
  17212. */
  17213. String description;
  17214. /** A named category that the command fits into.
  17215. You can give your commands any category you like, and these will be displayed in
  17216. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17217. commands together.
  17218. You can use the setInfo() method to quickly set this and some of the command's
  17219. other properties.
  17220. */
  17221. String categoryName;
  17222. /** A list of zero or more keypresses that should be used as the default keys for
  17223. this command.
  17224. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17225. this list to initialise the default set of key-to-command mappings.
  17226. @see addDefaultKeypress
  17227. */
  17228. Array <KeyPress> defaultKeypresses;
  17229. /** Flags describing the ways in which this command should be used.
  17230. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17231. variable.
  17232. */
  17233. enum CommandFlags
  17234. {
  17235. /** Indicates that the command can't currently be performed.
  17236. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17237. not currently permissable to perform the command. If the flag is set, then
  17238. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17239. command or show themselves as not being enabled.
  17240. @see ApplicationCommandInfo::setActive
  17241. */
  17242. isDisabled = 1 << 0,
  17243. /** Indicates that the command should have a tick next to it on a menu.
  17244. If your command is shown on a menu and this is set, it'll show a tick next to
  17245. it. Other components such as buttons may also use this flag to indicate that it
  17246. is a value that can be toggled, and is currently in the 'on' state.
  17247. @see ApplicationCommandInfo::setTicked
  17248. */
  17249. isTicked = 1 << 1,
  17250. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17251. it will call the command twice, once on key-down and again on key-up.
  17252. @see ApplicationCommandTarget::InvocationInfo
  17253. */
  17254. wantsKeyUpDownCallbacks = 1 << 2,
  17255. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17256. command in its list.
  17257. */
  17258. hiddenFromKeyEditor = 1 << 3,
  17259. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17260. command in its list, but won't allow the assigned keypress to be changed.
  17261. */
  17262. readOnlyInKeyEditor = 1 << 4,
  17263. /** If this flag is present and the command is invoked from a keypress, then any
  17264. buttons or menus that are also connected to the command will not flash to
  17265. indicate that they've been triggered.
  17266. */
  17267. dontTriggerVisualFeedback = 1 << 5
  17268. };
  17269. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17270. You can use the setInfo() method to quickly set this and some of the command's
  17271. other properties.
  17272. */
  17273. int flags;
  17274. };
  17275. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17276. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17277. /**
  17278. A command target publishes a list of command IDs that it can perform.
  17279. An ApplicationCommandManager despatches commands to targets, which must be
  17280. able to provide information about what commands they can handle.
  17281. To create a target, you'll need to inherit from this class, implementing all of
  17282. its pure virtual methods.
  17283. For info about how a target is chosen to receive a command, see
  17284. ApplicationCommandManager::getFirstCommandTarget().
  17285. @see ApplicationCommandManager, ApplicationCommandInfo
  17286. */
  17287. class JUCE_API ApplicationCommandTarget
  17288. {
  17289. public:
  17290. /** Creates a command target. */
  17291. ApplicationCommandTarget();
  17292. /** Destructor. */
  17293. virtual ~ApplicationCommandTarget();
  17294. /**
  17295. */
  17296. struct JUCE_API InvocationInfo
  17297. {
  17298. InvocationInfo (const CommandID commandID) throw();
  17299. /** The UID of the command that should be performed. */
  17300. CommandID commandID;
  17301. /** The command's flags.
  17302. See ApplicationCommandInfo for a description of these flag values.
  17303. */
  17304. int commandFlags;
  17305. /** The types of context in which the command might be called. */
  17306. enum InvocationMethod
  17307. {
  17308. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17309. fromKeyPress, /**< The command is being invoked by a key-press. */
  17310. fromMenu, /**< The command is being invoked by a menu selection. */
  17311. fromButton /**< The command is being invoked by a button click. */
  17312. };
  17313. /** The type of event that triggered this command. */
  17314. InvocationMethod invocationMethod;
  17315. /** If triggered by a keypress or menu, this will be the component that had the
  17316. keyboard focus at the time.
  17317. If triggered by a button, it may be set to that component, or it may be null.
  17318. */
  17319. Component* originatingComponent;
  17320. /** The keypress that was used to invoke it.
  17321. Note that this will be an invalid keypress if the command was invoked
  17322. by some other means than a keyboard shortcut.
  17323. */
  17324. KeyPress keyPress;
  17325. /** True if the callback is being invoked when the key is pressed,
  17326. false if the key is being released.
  17327. @see KeyPressMappingSet::addCommand()
  17328. */
  17329. bool isKeyDown;
  17330. /** If the key is being released, this indicates how long it had been held
  17331. down for.
  17332. (Only relevant if isKeyDown is false.)
  17333. */
  17334. int millisecsSinceKeyPressed;
  17335. };
  17336. /** This must return the next target to try after this one.
  17337. When a command is being sent, and the first target can't handle
  17338. that command, this method is used to determine the next target that should
  17339. be tried.
  17340. It may return 0 if it doesn't know of another target.
  17341. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17342. method to return a parent component that might want to handle it.
  17343. @see invoke
  17344. */
  17345. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17346. /** This must return a complete list of commands that this target can handle.
  17347. Your target should add all the command IDs that it handles to the array that is
  17348. passed-in.
  17349. */
  17350. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17351. /** This must provide details about one of the commands that this target can perform.
  17352. This will be called with one of the command IDs that the target provided in its
  17353. getAllCommands() methods.
  17354. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17355. suitable information about the command. (The commandID field will already have been filled-in
  17356. by the caller).
  17357. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17358. set all the fields at once.
  17359. If the command is currently inactive for some reason, this method must use
  17360. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17361. bit of the ApplicationCommandInfo::flags field).
  17362. Any default key-presses for the command should be appended to the
  17363. ApplicationCommandInfo::defaultKeypresses field.
  17364. Note that if you change something that affects the status of the commands
  17365. that would be returned by this method (e.g. something that makes some commands
  17366. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17367. to cause the manager to refresh its status.
  17368. */
  17369. virtual void getCommandInfo (const CommandID commandID,
  17370. ApplicationCommandInfo& result) = 0;
  17371. /** This must actually perform the specified command.
  17372. If this target is able to perform the command specified by the commandID field of the
  17373. InvocationInfo structure, then it should do so, and must return true.
  17374. If it can't handle this command, it should return false, which tells the caller to pass
  17375. the command on to the next target in line.
  17376. @see invoke, ApplicationCommandManager::invoke
  17377. */
  17378. virtual bool perform (const InvocationInfo& info) = 0;
  17379. /** Makes this target invoke a command.
  17380. Your code can call this method to invoke a command on this target, but normally
  17381. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17382. ApplicationCommandManager::invokeDirectly().
  17383. If this target can perform the given command, it will call its perform() method to
  17384. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17385. to try, and the command will be passed along to it.
  17386. @param invocationInfo this must be correctly filled-in, describing the context for
  17387. the invocation.
  17388. @param asynchronously if false, the command will be performed before this method returns.
  17389. If true, a message will be posted so that the command will be performed
  17390. later on the message thread, and this method will return immediately.
  17391. @see perform, ApplicationCommandManager::invoke
  17392. */
  17393. bool invoke (const InvocationInfo& invocationInfo,
  17394. const bool asynchronously);
  17395. /** Invokes a given command directly on this target.
  17396. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17397. structure.
  17398. */
  17399. bool invokeDirectly (const CommandID commandID,
  17400. const bool asynchronously);
  17401. /** Searches this target and all subsequent ones for the first one that can handle
  17402. the specified command.
  17403. This will use getNextCommandTarget() to determine the chain of targets to try
  17404. after this one.
  17405. */
  17406. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17407. /** Checks whether this command can currently be performed by this target.
  17408. This will return true only if a call to getCommandInfo() doesn't set the
  17409. isDisabled flag to indicate that the command is inactive.
  17410. */
  17411. bool isCommandActive (const CommandID commandID);
  17412. /** If this object is a Component, this method will seach upwards in its current
  17413. UI hierarchy for the next parent component that implements the
  17414. ApplicationCommandTarget class.
  17415. If your target is a Component, this is a very handy method to use in your
  17416. getNextCommandTarget() implementation.
  17417. */
  17418. ApplicationCommandTarget* findFirstTargetParentComponent();
  17419. juce_UseDebuggingNewOperator
  17420. private:
  17421. // (for async invocation of commands)
  17422. class CommandTargetMessageInvoker : public MessageListener
  17423. {
  17424. public:
  17425. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17426. ~CommandTargetMessageInvoker();
  17427. void handleMessage (const Message& message);
  17428. private:
  17429. ApplicationCommandTarget* const owner;
  17430. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17431. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17432. };
  17433. CommandTargetMessageInvoker* messageInvoker;
  17434. friend class CommandTargetMessageInvoker;
  17435. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17436. };
  17437. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17438. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17439. /********* Start of inlined file: juce_ActionListener.h *********/
  17440. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17441. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17442. /**
  17443. Receives callbacks to indicate that some kind of event has occurred.
  17444. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17445. about something that's happened.
  17446. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17447. */
  17448. class JUCE_API ActionListener
  17449. {
  17450. public:
  17451. /** Destructor. */
  17452. virtual ~ActionListener() {}
  17453. /** Overridden by your subclass to receive the callback.
  17454. @param message the string that was specified when the event was triggered
  17455. by a call to ActionListenerList::sendActionMessage()
  17456. */
  17457. virtual void actionListenerCallback (const String& message) = 0;
  17458. };
  17459. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17460. /********* End of inlined file: juce_ActionListener.h *********/
  17461. /**
  17462. An instance of this class is used to specify initialisation and shutdown
  17463. code for the application.
  17464. An application that wants to run in the JUCE framework needs to declare a
  17465. subclass of JUCEApplication and implement its various pure virtual methods.
  17466. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17467. to declare an instance of this class and generate a suitable platform-specific
  17468. main() function.
  17469. e.g. @code
  17470. class MyJUCEApp : public JUCEApplication
  17471. {
  17472. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17473. // objects, which you must create in the initialise() method.
  17474. MyApplicationWindow* myMainWindow;
  17475. public:
  17476. MyJUCEApp()
  17477. : myMainWindow (0)
  17478. {
  17479. // never create any Juce objects in the constructor - do all your initialisation
  17480. // in the initialise() method.
  17481. }
  17482. ~MyJUCEApp()
  17483. {
  17484. // all your shutdown code must have already been done in the shutdown() method -
  17485. // nothing should happen in this destructor.
  17486. }
  17487. void initialise (const String& commandLine)
  17488. {
  17489. myMainWindow = new MyApplicationWindow();
  17490. myMainWindow->setBounds (100, 100, 400, 500);
  17491. myMainWindow->setVisible (true);
  17492. }
  17493. void shutdown()
  17494. {
  17495. delete myMainWindow;
  17496. }
  17497. const String getApplicationName()
  17498. {
  17499. return T("Super JUCE-o-matic");
  17500. }
  17501. const String getApplicationVersion()
  17502. {
  17503. return T("1.0");
  17504. }
  17505. };
  17506. // this creates wrapper code to actually launch the app properly.
  17507. START_JUCE_APPLICATION (MyJUCEApp)
  17508. @endcode
  17509. Because this object will be created before Juce has properly initialised, you must
  17510. NEVER add any member variable objects that will be automatically constructed. Likewise
  17511. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17512. you want to add to the class must be pointers, which you should instantiate during the
  17513. initialise() method, and delete in the shutdown() method.
  17514. @see MessageManager, DeletedAtShutdown
  17515. */
  17516. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17517. private ActionListener
  17518. {
  17519. protected:
  17520. /** Constructs a JUCE app object.
  17521. If subclasses implement a constructor or destructor, they shouldn't call any
  17522. JUCE code in there - put your startup/shutdown code in initialise() and
  17523. shutdown() instead.
  17524. */
  17525. JUCEApplication();
  17526. public:
  17527. /** Destructor.
  17528. If subclasses implement a constructor or destructor, they shouldn't call any
  17529. JUCE code in there - put your startup/shutdown code in initialise() and
  17530. shutdown() instead.
  17531. */
  17532. virtual ~JUCEApplication();
  17533. /** Returns the global instance of the application object being run. */
  17534. static JUCEApplication* getInstance() throw();
  17535. /** Called when the application starts.
  17536. This will be called once to let the application do whatever initialisation
  17537. it needs, create its windows, etc.
  17538. After the method returns, the normal event-dispatch loop will be run,
  17539. until the quit() method is called, at which point the shutdown()
  17540. method will be called to let the application clear up anything it needs
  17541. to delete.
  17542. If during the initialise() method, the application decides not to start-up
  17543. after all, it can just call the quit() method and the event loop won't be run.
  17544. @param commandLineParameters the line passed in does not include the
  17545. name of the executable, just the parameter list.
  17546. @see shutdown, quit
  17547. */
  17548. virtual void initialise (const String& commandLineParameters) = 0;
  17549. /** Returns true if the application hasn't yet completed its initialise() method
  17550. and entered the main event loop.
  17551. This is handy for things like splash screens to know when the app's up-and-running
  17552. properly.
  17553. */
  17554. bool isInitialising() const throw();
  17555. /* Called to allow the application to clear up before exiting.
  17556. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17557. terminate, and this method will get called to allow the app to sort itself
  17558. out.
  17559. Be careful that nothing happens in this method that might rely on messages
  17560. being sent, or any kind of window activity, because the message loop is no
  17561. longer running at this point.
  17562. @see DeletedAtShutdown
  17563. */
  17564. virtual void shutdown() = 0;
  17565. /** Returns the application's name.
  17566. An application must implement this to name itself.
  17567. */
  17568. virtual const String getApplicationName() = 0;
  17569. /** Returns the application's version number.
  17570. An application can implement this to give itself a version.
  17571. (The default implementation of this just returns an empty string).
  17572. */
  17573. virtual const String getApplicationVersion();
  17574. /** Checks whether multiple instances of the app are allowed.
  17575. If you application class returns true for this, more than one instance is
  17576. permitted to run (except on the Mac where this isn't possible).
  17577. If it's false, the second instance won't start, but it you will still get a
  17578. callback to anotherInstanceStarted() to tell you about this - which
  17579. gives you a chance to react to what the user was trying to do.
  17580. */
  17581. virtual bool moreThanOneInstanceAllowed();
  17582. /** Indicates that the user has tried to start up another instance of the app.
  17583. This will get called even if moreThanOneInstanceAllowed() is false.
  17584. */
  17585. virtual void anotherInstanceStarted (const String& commandLine);
  17586. /** Called when the operating system is trying to close the application.
  17587. The default implementation of this method is to call quit(), but it may
  17588. be overloaded to ignore the request or do some other special behaviour
  17589. instead. For example, you might want to offer the user the chance to save
  17590. their changes before quitting, and give them the chance to cancel.
  17591. If you want to send a quit signal to your app, this is the correct method
  17592. to call, because it means that requests that come from the system get handled
  17593. in the same way as those from your own application code. So e.g. you'd
  17594. call this method from a "quit" item on a menu bar.
  17595. */
  17596. virtual void systemRequestedQuit();
  17597. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17598. callback will be triggered, in case you want to log them or do some other
  17599. type of error-handling.
  17600. If the type of exception is derived from the std::exception class, the pointer
  17601. passed-in will be valid. If the exception is of unknown type, this pointer
  17602. will be null.
  17603. */
  17604. virtual void unhandledException (const std::exception* e,
  17605. const String& sourceFilename,
  17606. const int lineNumber);
  17607. /** Signals that the main message loop should stop and the application should terminate.
  17608. This isn't synchronous, it just posts a quit message to the main queue, and
  17609. when this message arrives, the message loop will stop, the shutdown() method
  17610. will be called, and the app will exit.
  17611. Note that this will cause an unconditional quit to happen, so if you need an
  17612. extra level before this, e.g. to give the user the chance to save their work
  17613. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17614. method - see that method's help for more info.
  17615. @see MessageManager, DeletedAtShutdown
  17616. */
  17617. static void quit();
  17618. /** Sets the value that should be returned as the application's exit code when the
  17619. app quits.
  17620. This is the value that's returned by the main() function. Normally you'd leave this
  17621. as 0 unless you want to indicate an error code.
  17622. @see getApplicationReturnValue
  17623. */
  17624. void setApplicationReturnValue (const int newReturnValue) throw();
  17625. /** Returns the value that has been set as the application's exit code.
  17626. @see setApplicationReturnValue
  17627. */
  17628. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17629. /** Returns the application's command line params.
  17630. */
  17631. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  17632. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17633. /** @internal */
  17634. static int main (String& commandLine, JUCEApplication* const newApp);
  17635. /** @internal */
  17636. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17637. /** @internal */
  17638. static void sendUnhandledException (const std::exception* const e,
  17639. const char* const sourceFile,
  17640. const int lineNumber);
  17641. /** @internal */
  17642. ApplicationCommandTarget* getNextCommandTarget();
  17643. /** @internal */
  17644. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17645. /** @internal */
  17646. void getAllCommands (Array <CommandID>& commands);
  17647. /** @internal */
  17648. bool perform (const InvocationInfo& info);
  17649. /** @internal */
  17650. void actionListenerCallback (const String& message);
  17651. private:
  17652. String commandLineParameters;
  17653. int appReturnValue;
  17654. bool stillInitialising;
  17655. static int shutdownAppAndClearUp();
  17656. };
  17657. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17658. /********* End of inlined file: juce_Application.h *********/
  17659. #endif
  17660. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17661. #endif
  17662. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17663. #endif
  17664. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17665. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17666. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17667. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17668. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17669. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17670. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17671. /**
  17672. Has a callback method that is triggered asynchronously.
  17673. This object allows an asynchronous callback function to be triggered, for
  17674. tasks such as coalescing multiple updates into a single callback later on.
  17675. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17676. message thread calling handleAsyncUpdate() as soon as it can.
  17677. */
  17678. class JUCE_API AsyncUpdater
  17679. {
  17680. public:
  17681. /** Creates an AsyncUpdater object. */
  17682. AsyncUpdater() throw();
  17683. /** Destructor.
  17684. If there are any pending callbacks when the object is deleted, these are lost.
  17685. */
  17686. virtual ~AsyncUpdater();
  17687. /** Causes the callback to be triggered at a later time.
  17688. This method returns immediately, having made sure that a callback
  17689. to the handleAsyncUpdate() method will occur as soon as possible.
  17690. If an update callback is already pending but hasn't happened yet, calls
  17691. to this method will be ignored.
  17692. It's thread-safe to call this method from any number of threads without
  17693. needing to worry about locking.
  17694. */
  17695. void triggerAsyncUpdate() throw();
  17696. /** This will stop any pending updates from happening.
  17697. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17698. callback happens, this will cancel the handleAsyncUpdate() callback.
  17699. */
  17700. void cancelPendingUpdate() throw();
  17701. /** If an update has been triggered and is pending, this will invoke it
  17702. synchronously.
  17703. Use this as a kind of "flush" operation - if an update is pending, the
  17704. handleAsyncUpdate() method will be called immediately; if no update is
  17705. pending, then nothing will be done.
  17706. */
  17707. void handleUpdateNowIfNeeded();
  17708. /** Called back to do whatever your class needs to do.
  17709. This method is called by the message thread at the next convenient time
  17710. after the triggerAsyncUpdate() method has been called.
  17711. */
  17712. virtual void handleAsyncUpdate() = 0;
  17713. private:
  17714. class AsyncUpdaterInternal : public MessageListener
  17715. {
  17716. public:
  17717. AsyncUpdaterInternal() throw() {}
  17718. ~AsyncUpdaterInternal() {}
  17719. void handleMessage (const Message&);
  17720. AsyncUpdater* owner;
  17721. private:
  17722. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17723. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17724. };
  17725. AsyncUpdaterInternal internalAsyncHandler;
  17726. bool asyncMessagePending;
  17727. };
  17728. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17729. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17730. /********* Start of inlined file: juce_Desktop.h *********/
  17731. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17732. #define __JUCE_DESKTOP_JUCEHEADER__
  17733. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17734. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17735. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17736. /**
  17737. Classes derived from this will be automatically deleted when the application exits.
  17738. After JUCEApplication::shutdown() has been called, any objects derived from
  17739. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17740. order to that in which they were created.
  17741. So if you've got a singleton and don't want to have to explicitly delete it, just
  17742. inherit from this and it'll be taken care of.
  17743. */
  17744. class JUCE_API DeletedAtShutdown
  17745. {
  17746. protected:
  17747. /** Creates a DeletedAtShutdown object. */
  17748. DeletedAtShutdown() throw();
  17749. /** Destructor.
  17750. It's ok to delete these objects explicitly - it's only the ones left
  17751. dangling at the end that will be deleted automatically.
  17752. */
  17753. virtual ~DeletedAtShutdown();
  17754. public:
  17755. /** Deletes all extant objects.
  17756. This shouldn't be used by applications, as it's called automatically
  17757. in the shutdown code of the JUCEApplication class.
  17758. */
  17759. static void deleteAll();
  17760. private:
  17761. DeletedAtShutdown (const DeletedAtShutdown&);
  17762. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17763. };
  17764. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17765. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17766. /********* Start of inlined file: juce_Timer.h *********/
  17767. #ifndef __JUCE_TIMER_JUCEHEADER__
  17768. #define __JUCE_TIMER_JUCEHEADER__
  17769. class InternalTimerThread;
  17770. /**
  17771. Repeatedly calls a user-defined method at a specified time interval.
  17772. A Timer's timerCallback() method will be repeatedly called at a given
  17773. interval. Initially when a Timer object is created, they will do nothing
  17774. until the startTimer() method is called, then the message thread will
  17775. start calling it back until stopTimer() is called.
  17776. The time interval isn't guaranteed to be precise to any more than maybe
  17777. 10-20ms, and the intervals may end up being much longer than requested if the
  17778. system is busy. Because it's the message thread that is doing the callbacks,
  17779. any messages that take a significant amount of time to process will block
  17780. all the timers for that period.
  17781. If you need to have a single callback that is shared by multiple timers with
  17782. different frequencies, then the MultiTimer class allows you to do that - its
  17783. structure is very similar to the Timer class, but contains multiple timers
  17784. internally, each one identified by an ID number.
  17785. @see MultiTimer
  17786. */
  17787. class JUCE_API Timer
  17788. {
  17789. protected:
  17790. /** Creates a Timer.
  17791. When created, the timer is stopped, so use startTimer() to get it going.
  17792. */
  17793. Timer() throw();
  17794. /** Creates a copy of another timer.
  17795. Note that this timer won't be started, even if the one you're copying
  17796. is running.
  17797. */
  17798. Timer (const Timer& other) throw();
  17799. public:
  17800. /** Destructor. */
  17801. virtual ~Timer();
  17802. /** The user-defined callback routine that actually gets called periodically.
  17803. It's perfectly ok to call startTimer() or stopTimer() from within this
  17804. callback to change the subsequent intervals.
  17805. */
  17806. virtual void timerCallback() = 0;
  17807. /** Starts the timer and sets the length of interval required.
  17808. If the timer is already started, this will reset it, so the
  17809. time between calling this method and the next timer callback
  17810. will not be less than the interval length passed in.
  17811. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17812. rounded up to 1)
  17813. */
  17814. void startTimer (const int intervalInMilliseconds) throw();
  17815. /** Stops the timer.
  17816. No more callbacks will be made after this method returns.
  17817. If this is called from a different thread, any callbacks that may
  17818. be currently executing may be allowed to finish before the method
  17819. returns.
  17820. */
  17821. void stopTimer() throw();
  17822. /** Checks if the timer has been started.
  17823. @returns true if the timer is running.
  17824. */
  17825. bool isTimerRunning() const throw() { return periodMs > 0; }
  17826. /** Returns the timer's interval.
  17827. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17828. */
  17829. int getTimerInterval() const throw() { return periodMs; }
  17830. private:
  17831. friend class InternalTimerThread;
  17832. int countdownMs, periodMs;
  17833. Timer* previous;
  17834. Timer* next;
  17835. const Timer& operator= (const Timer&);
  17836. };
  17837. #endif // __JUCE_TIMER_JUCEHEADER__
  17838. /********* End of inlined file: juce_Timer.h *********/
  17839. /**
  17840. Classes can implement this interface and register themselves with the Desktop class
  17841. to receive callbacks when the currently focused component changes.
  17842. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17843. */
  17844. class JUCE_API FocusChangeListener
  17845. {
  17846. public:
  17847. /** Destructor. */
  17848. virtual ~FocusChangeListener() {}
  17849. /** Callback to indicate that the currently focused component has changed. */
  17850. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17851. };
  17852. /**
  17853. Describes and controls aspects of the computer's desktop.
  17854. */
  17855. class JUCE_API Desktop : private DeletedAtShutdown,
  17856. private Timer,
  17857. private AsyncUpdater
  17858. {
  17859. public:
  17860. /** There's only one dektop object, and this method will return it.
  17861. */
  17862. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17863. /** Returns a list of the positions of all the monitors available.
  17864. The first rectangle in the list will be the main monitor area.
  17865. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17866. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17867. */
  17868. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17869. /** Returns the position and size of the main monitor.
  17870. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17871. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17872. */
  17873. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17874. /** Returns the position and size of the monitor which contains this co-ordinate.
  17875. If none of the monitors contains the point, this will just return the
  17876. main monitor.
  17877. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17878. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17879. */
  17880. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17881. /** Returns the mouse position.
  17882. The co-ordinates are relative to the top-left of the main monitor.
  17883. */
  17884. static void getMousePosition (int& x, int& y) throw();
  17885. /** Makes the mouse pointer jump to a given location.
  17886. The co-ordinates are relative to the top-left of the main monitor.
  17887. */
  17888. static void setMousePosition (int x, int y) throw();
  17889. /** Returns the last position at which a mouse button was pressed.
  17890. */
  17891. static void getLastMouseDownPosition (int& x, int& y) throw();
  17892. /** Returns the number of times the mouse button has been clicked since the
  17893. app started.
  17894. Each mouse-down event increments this number by 1.
  17895. */
  17896. static int getMouseButtonClickCounter() throw();
  17897. /** This lets you prevent the screensaver from becoming active.
  17898. Handy if you're running some sort of presentation app where having a screensaver
  17899. appear would be annoying.
  17900. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17901. won't enable a screensaver unless the user has actually set one up).
  17902. The disablement will only happen while the Juce application is the foreground
  17903. process - if another task is running in front of it, then the screensaver will
  17904. be unaffected.
  17905. @see isScreenSaverEnabled
  17906. */
  17907. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17908. /** Returns true if the screensaver has not been turned off.
  17909. This will return the last value passed into setScreenSaverEnabled(). Note that
  17910. it won't tell you whether the user is actually using a screen saver, just
  17911. whether this app is deliberately preventing one from running.
  17912. @see setScreenSaverEnabled
  17913. */
  17914. static bool isScreenSaverEnabled() throw();
  17915. /** Registers a MouseListener that will receive all mouse events that occur on
  17916. any component.
  17917. @see removeGlobalMouseListener
  17918. */
  17919. void addGlobalMouseListener (MouseListener* const listener) throw();
  17920. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17921. method.
  17922. @see addGlobalMouseListener
  17923. */
  17924. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17925. /** Registers a MouseListener that will receive a callback whenever the focused
  17926. component changes.
  17927. */
  17928. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17929. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17930. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17931. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  17932. The component must already be on the desktop for this method to work. It will
  17933. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  17934. etc will be hidden.
  17935. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  17936. the component that's currently being used will be resized back to the size
  17937. and position it was in before being put into this mode.
  17938. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  17939. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  17940. to hide as much on-screen paraphenalia as possible.
  17941. */
  17942. void setKioskModeComponent (Component* componentToUse,
  17943. const bool allowMenusAndBars = true);
  17944. /** Returns the component that is currently being used in kiosk-mode.
  17945. This is the component that was last set by setKioskModeComponent(). If none
  17946. has been set, this returns 0.
  17947. */
  17948. Component* getKioskModeComponent() const { return kioskModeComponent; }
  17949. /** Returns the number of components that are currently active as top-level
  17950. desktop windows.
  17951. @see getComponent, Component::addToDesktop
  17952. */
  17953. int getNumComponents() const throw();
  17954. /** Returns one of the top-level desktop window components.
  17955. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17956. index is out-of-range.
  17957. @see getNumComponents, Component::addToDesktop
  17958. */
  17959. Component* getComponent (const int index) const throw();
  17960. /** Finds the component at a given screen location.
  17961. This will drill down into top-level windows to find the child component at
  17962. the given position.
  17963. Returns 0 if the co-ordinates are inside a non-Juce window.
  17964. */
  17965. Component* findComponentAt (const int screenX,
  17966. const int screenY) const;
  17967. juce_UseDebuggingNewOperator
  17968. /** Tells this object to refresh its idea of what the screen resolution is.
  17969. (Called internally by the native code).
  17970. */
  17971. void refreshMonitorSizes() throw();
  17972. /** True if the OS supports semitransparent windows */
  17973. static bool canUseSemiTransparentWindows() throw();
  17974. private:
  17975. friend class Component;
  17976. friend class ComponentPeer;
  17977. SortedSet <void*> mouseListeners, focusListeners;
  17978. VoidArray desktopComponents;
  17979. friend class DeletedAtShutdown;
  17980. friend class TopLevelWindowManager;
  17981. Desktop() throw();
  17982. ~Desktop() throw();
  17983. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17984. int lastMouseX, lastMouseY;
  17985. Component* kioskModeComponent;
  17986. Rectangle kioskComponentOriginalBounds;
  17987. void timerCallback();
  17988. void sendMouseMove();
  17989. void resetTimer() throw();
  17990. int getNumDisplayMonitors() const throw();
  17991. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17992. void addDesktopComponent (Component* const c) throw();
  17993. void removeDesktopComponent (Component* const c) throw();
  17994. void componentBroughtToFront (Component* const c) throw();
  17995. void triggerFocusCallback() throw();
  17996. void handleAsyncUpdate();
  17997. Desktop (const Desktop&);
  17998. const Desktop& operator= (const Desktop&);
  17999. };
  18000. #endif // __JUCE_DESKTOP_JUCEHEADER__
  18001. /********* End of inlined file: juce_Desktop.h *********/
  18002. class KeyPressMappingSet;
  18003. class ApplicationCommandManagerListener;
  18004. /**
  18005. One of these objects holds a list of all the commands your app can perform,
  18006. and despatches these commands when needed.
  18007. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  18008. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  18009. to invoke automatically, which means you don't have to handle the result of a menu
  18010. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  18011. which can choose which events they want to handle.
  18012. This architecture also allows for nested ApplicationCommandTargets, so that for example
  18013. you could have two different objects, one inside the other, both of which can respond to
  18014. a "delete" command. Depending on which one has focus, the command will be sent to the
  18015. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  18016. method.
  18017. To set up your app to use commands, you'll need to do the following:
  18018. - Create a global ApplicationCommandManager to hold the list of all possible
  18019. commands. (This will also manage a set of key-mappings for them).
  18020. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  18021. This allows the object to provide a list of commands that it can perform, and
  18022. to handle them.
  18023. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  18024. or ApplicationCommandManager::registerCommand().
  18025. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  18026. method to access the key-mapper object, which you will need to register as a key-listener
  18027. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  18028. about setting this up.
  18029. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  18030. cause these commands to be invoked automatically.
  18031. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  18032. When a command is invoked, the ApplicationCommandManager will try to choose the best
  18033. ApplicationCommandTarget to receive the specified command. To do this it will use the
  18034. current keyboard focus to see which component might be interested, and will search the
  18035. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  18036. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  18037. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  18038. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  18039. point if the command still hasn't been performed, it will be passed to the current
  18040. JUCEApplication object (which is itself an ApplicationCommandTarget).
  18041. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  18042. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  18043. the object yourself.
  18044. @see ApplicationCommandTarget, ApplicationCommandInfo
  18045. */
  18046. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  18047. private FocusChangeListener
  18048. {
  18049. public:
  18050. /** Creates an ApplicationCommandManager.
  18051. Once created, you'll need to register all your app's commands with it, using
  18052. ApplicationCommandManager::registerAllCommandsForTarget() or
  18053. ApplicationCommandManager::registerCommand().
  18054. */
  18055. ApplicationCommandManager();
  18056. /** Destructor.
  18057. Make sure that you don't delete this if pointers to it are still being used by
  18058. objects such as PopupMenus or Buttons.
  18059. */
  18060. virtual ~ApplicationCommandManager();
  18061. /** Clears the current list of all commands.
  18062. Note that this will also clear the contents of the KeyPressMappingSet.
  18063. */
  18064. void clearCommands();
  18065. /** Adds a command to the list of registered commands.
  18066. @see registerAllCommandsForTarget
  18067. */
  18068. void registerCommand (const ApplicationCommandInfo& newCommand);
  18069. /** Adds all the commands that this target publishes to the manager's list.
  18070. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  18071. to get details about all the commands that this target can do, and will call
  18072. registerCommand() to add each one to the manger's list.
  18073. @see registerCommand
  18074. */
  18075. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  18076. /** Removes the command with a specified ID.
  18077. Note that this will also remove any key mappings that are mapped to the command.
  18078. */
  18079. void removeCommand (const CommandID commandID);
  18080. /** This should be called to tell the manager that one of its registered commands may have changed
  18081. its active status.
  18082. Because the command manager only finds out whether a command is active or inactive by querying
  18083. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  18084. allows things like buttons to update their enablement, etc.
  18085. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  18086. for any registered listeners.
  18087. */
  18088. void commandStatusChanged();
  18089. /** Returns the number of commands that have been registered.
  18090. @see registerCommand
  18091. */
  18092. int getNumCommands() const throw() { return commands.size(); }
  18093. /** Returns the details about one of the registered commands.
  18094. The index is between 0 and (getNumCommands() - 1).
  18095. */
  18096. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  18097. /** Returns the details about a given command ID.
  18098. This will search the list of registered commands for one with the given command
  18099. ID number, and return its associated info. If no matching command is found, this
  18100. will return 0.
  18101. */
  18102. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  18103. /** Returns the name field for a command.
  18104. An empty string is returned if no command with this ID has been registered.
  18105. @see getDescriptionOfCommand
  18106. */
  18107. const String getNameOfCommand (const CommandID commandID) const throw();
  18108. /** Returns the description field for a command.
  18109. An empty string is returned if no command with this ID has been registered. If the
  18110. command has no description, this will return its short name field instead.
  18111. @see getNameOfCommand
  18112. */
  18113. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  18114. /** Returns the list of categories.
  18115. This will go through all registered commands, and return a list of all the distict
  18116. categoryName values from their ApplicationCommandInfo structure.
  18117. @see getCommandsInCategory()
  18118. */
  18119. const StringArray getCommandCategories() const throw();
  18120. /** Returns a list of all the command UIDs in a particular category.
  18121. @see getCommandCategories()
  18122. */
  18123. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  18124. /** Returns the manager's internal set of key mappings.
  18125. This object can be used to edit the keypresses. To actually link this object up
  18126. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  18127. class.
  18128. @see KeyPressMappingSet
  18129. */
  18130. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  18131. /** Invokes the given command directly, sending it to the default target.
  18132. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18133. structure.
  18134. */
  18135. bool invokeDirectly (const CommandID commandID,
  18136. const bool asynchronously);
  18137. /** Sends a command to the default target.
  18138. This will choose a target using getFirstCommandTarget(), and send the specified command
  18139. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  18140. first target can't handle the command, it will be passed on to targets further down the
  18141. chain (see ApplicationCommandTarget::invoke() for more info).
  18142. @param invocationInfo this must be correctly filled-in, describing the context for
  18143. the invocation.
  18144. @param asynchronously if false, the command will be performed before this method returns.
  18145. If true, a message will be posted so that the command will be performed
  18146. later on the message thread, and this method will return immediately.
  18147. @see ApplicationCommandTarget::invoke
  18148. */
  18149. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  18150. const bool asynchronously);
  18151. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  18152. Whenever the manager needs to know which target a command should be sent to, it calls
  18153. this method to determine the first one to try.
  18154. By default, this method will return the target that was set by calling setFirstCommandTarget().
  18155. If no target is set, it will return the result of findDefaultComponentTarget().
  18156. If you need to make sure all commands go via your own custom target, then you can
  18157. either use setFirstCommandTarget() to specify a single target, or override this method
  18158. if you need more complex logic to choose one.
  18159. It may return 0 if no targets are available.
  18160. @see getTargetForCommand, invoke, invokeDirectly
  18161. */
  18162. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  18163. /** Sets a target to be returned by getFirstCommandTarget().
  18164. If this is set to 0, then getFirstCommandTarget() will by default return the
  18165. result of findDefaultComponentTarget().
  18166. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  18167. deleting the target object.
  18168. */
  18169. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  18170. /** Tries to find the best target to use to perform a given command.
  18171. This will call getFirstCommandTarget() to find the preferred target, and will
  18172. check whether that target can handle the given command. If it can't, then it'll use
  18173. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  18174. so on until no more are available.
  18175. If no targets are found that can perform the command, this method will return 0.
  18176. If a target is found, then it will get the target to fill-in the upToDateInfo
  18177. structure with the latest info about that command, so that the caller can see
  18178. whether the command is disabled, ticked, etc.
  18179. */
  18180. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18181. ApplicationCommandInfo& upToDateInfo);
  18182. /** Registers a listener that will be called when various events occur. */
  18183. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18184. /** Deregisters a previously-added listener. */
  18185. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18186. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18187. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18188. but is exposed here in case it's useful.
  18189. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18190. windows, etc., and using the findTargetForComponent() method.
  18191. */
  18192. static ApplicationCommandTarget* findDefaultComponentTarget();
  18193. /** Examines this component and all its parents in turn, looking for the first one
  18194. which is a ApplicationCommandTarget.
  18195. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18196. that class.
  18197. */
  18198. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18199. juce_UseDebuggingNewOperator
  18200. private:
  18201. OwnedArray <ApplicationCommandInfo> commands;
  18202. SortedSet <void*> listeners;
  18203. KeyPressMappingSet* keyMappings;
  18204. ApplicationCommandTarget* firstTarget;
  18205. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18206. void handleAsyncUpdate();
  18207. void globalFocusChanged (Component*);
  18208. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18209. // version of this method.
  18210. virtual short getFirstCommandTarget() { return 0; }
  18211. };
  18212. /**
  18213. A listener that receives callbacks from an ApplicationCommandManager when
  18214. commands are invoked or the command list is changed.
  18215. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18216. */
  18217. class JUCE_API ApplicationCommandManagerListener
  18218. {
  18219. public:
  18220. /** Destructor. */
  18221. virtual ~ApplicationCommandManagerListener() {}
  18222. /** Called when an app command is about to be invoked. */
  18223. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18224. /** Called when commands are registered or deregistered from the
  18225. command manager, or when commands are made active or inactive.
  18226. Note that if you're using this to watch for changes to whether a command is disabled,
  18227. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18228. whenever the status of your command might have changed.
  18229. */
  18230. virtual void applicationCommandListChanged() = 0;
  18231. };
  18232. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18233. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18234. #endif
  18235. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18236. #endif
  18237. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18238. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18239. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18240. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18241. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18242. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18243. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18244. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18245. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18246. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18247. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18248. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18249. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18250. /********* Start of inlined file: juce_ChangeListener.h *********/
  18251. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18252. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18253. /**
  18254. Receives callbacks about changes to some kind of object.
  18255. Many objects use a ChangeListenerList to keep a set of listeners which they
  18256. will inform when something changes. A subclass of ChangeListener
  18257. is used to receive these callbacks.
  18258. Note that the major difference between an ActionListener and a ChangeListener
  18259. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18260. callbacks, but ActionListeners perform one callback for every event posted.
  18261. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18262. */
  18263. class JUCE_API ChangeListener
  18264. {
  18265. public:
  18266. /** Destructor. */
  18267. virtual ~ChangeListener() {}
  18268. /** Overridden by your subclass to receive the callback.
  18269. @param objectThatHasChanged the value that was passed to the
  18270. ChangeListenerList::sendChangeMessage() method
  18271. */
  18272. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18273. };
  18274. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18275. /********* End of inlined file: juce_ChangeListener.h *********/
  18276. /**
  18277. A set of ChangeListeners.
  18278. Listeners can be added and removed from the list, and change messages can be
  18279. broadcast to all the listeners.
  18280. @see ChangeListener, ChangeBroadcaster
  18281. */
  18282. class JUCE_API ChangeListenerList : public MessageListener
  18283. {
  18284. public:
  18285. /** Creates an empty list. */
  18286. ChangeListenerList() throw();
  18287. /** Destructor. */
  18288. ~ChangeListenerList() throw();
  18289. /** Adds a listener to the list.
  18290. (Trying to add a listener that's already on the list will have no effect).
  18291. */
  18292. void addChangeListener (ChangeListener* const listener) throw();
  18293. /** Removes a listener from the list.
  18294. If the listener isn't on the list, this won't have any effect.
  18295. */
  18296. void removeChangeListener (ChangeListener* const listener) throw();
  18297. /** Removes all listeners from the list. */
  18298. void removeAllChangeListeners() throw();
  18299. /** Posts an asynchronous change message to all the listeners.
  18300. If a message has already been sent and hasn't yet been delivered, this
  18301. method won't send another - in this way it coalesces multiple frequent
  18302. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18303. with the ActionListener, which posts a new event for every call to its
  18304. sendActionMessage() method.
  18305. Only listeners which are on the list when the change event is delivered
  18306. will receive the event - and this may include listeners that weren't on
  18307. the list when the change message was sent.
  18308. @param objectThatHasChanged this pointer is passed to the
  18309. ChangeListener::changeListenerCallback() method,
  18310. and can be any value the application needs
  18311. @see sendSynchronousChangeMessage
  18312. */
  18313. void sendChangeMessage (void* objectThatHasChanged) throw();
  18314. /** This will synchronously callback all the ChangeListeners.
  18315. Use this if you need to synchronously force a call to all the
  18316. listeners' ChangeListener::changeListenerCallback() methods.
  18317. */
  18318. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18319. /** If a change message has been sent but not yet dispatched, this will
  18320. use sendSynchronousChangeMessage() to make the callback immediately.
  18321. */
  18322. void dispatchPendingMessages();
  18323. /** @internal */
  18324. void handleMessage (const Message&);
  18325. juce_UseDebuggingNewOperator
  18326. private:
  18327. SortedSet <void*> listeners;
  18328. CriticalSection lock;
  18329. void* lastChangedObject;
  18330. bool messagePending;
  18331. ChangeListenerList (const ChangeListenerList&);
  18332. const ChangeListenerList& operator= (const ChangeListenerList&);
  18333. };
  18334. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18335. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18336. /** Manages a list of ChangeListeners, and can send them messages.
  18337. To quickly add methods to your class that can add/remove change
  18338. listeners and broadcast to them, you can derive from this.
  18339. @see ChangeListenerList, ChangeListener
  18340. */
  18341. class JUCE_API ChangeBroadcaster
  18342. {
  18343. public:
  18344. /** Creates an ChangeBroadcaster. */
  18345. ChangeBroadcaster() throw();
  18346. /** Destructor. */
  18347. virtual ~ChangeBroadcaster();
  18348. /** Adds a listener to the list.
  18349. (Trying to add a listener that's already on the list will have no effect).
  18350. */
  18351. void addChangeListener (ChangeListener* const listener) throw();
  18352. /** Removes a listener from the list.
  18353. If the listener isn't on the list, this won't have any effect.
  18354. */
  18355. void removeChangeListener (ChangeListener* const listener) throw();
  18356. /** Removes all listeners from the list. */
  18357. void removeAllChangeListeners() throw();
  18358. /** Broadcasts a change message to all the registered listeners.
  18359. The message will be delivered asynchronously by the event thread, so this
  18360. method will not directly call any of the listeners. For a synchronous
  18361. message, use sendSynchronousChangeMessage().
  18362. @see ChangeListenerList::sendActionMessage
  18363. */
  18364. void sendChangeMessage (void* objectThatHasChanged) throw();
  18365. /** Sends a synchronous change message to all the registered listeners.
  18366. @see ChangeListenerList::sendSynchronousChangeMessage
  18367. */
  18368. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18369. /** If a change message has been sent but not yet dispatched, this will
  18370. use sendSynchronousChangeMessage() to make the callback immediately.
  18371. */
  18372. void dispatchPendingMessages();
  18373. private:
  18374. ChangeListenerList changeListenerList;
  18375. ChangeBroadcaster (const ChangeBroadcaster&);
  18376. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18377. };
  18378. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18379. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18380. /** Wrapper on a file that stores a list of key/value data pairs.
  18381. Useful for storing application settings, etc. See the PropertySet class for
  18382. the interfaces that read and write values.
  18383. Not designed for very large amounts of data, as it keeps all the values in
  18384. memory and writes them out to disk lazily when they are changed.
  18385. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18386. with it, and these will be signalled when a value changes.
  18387. @see PropertySet
  18388. */
  18389. class JUCE_API PropertiesFile : public PropertySet,
  18390. public ChangeBroadcaster,
  18391. private Timer
  18392. {
  18393. public:
  18394. enum FileFormatOptions
  18395. {
  18396. ignoreCaseOfKeyNames = 1,
  18397. storeAsBinary = 2,
  18398. storeAsCompressedBinary = 4,
  18399. storeAsXML = 8
  18400. };
  18401. /**
  18402. Creates a PropertiesFile object.
  18403. @param file the file to use
  18404. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18405. is changed, the object will wait for this amount
  18406. of time and then save the file. If zero, the file
  18407. will be written to disk immediately on being changed
  18408. (which might be slow, as it'll re-write synchronously
  18409. each time a value-change method is called). If it is
  18410. less than zero, the file won't be saved until
  18411. save() or saveIfNeeded() are explicitly called.
  18412. @param options a combination of the flags in the FileFormatOptions
  18413. enum, which specify the type of file to save, and other
  18414. options.
  18415. */
  18416. PropertiesFile (const File& file,
  18417. const int millisecondsBeforeSaving,
  18418. const int options) throw();
  18419. /** Destructor.
  18420. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18421. */
  18422. ~PropertiesFile();
  18423. /** This will flush all the values to disk if they've changed since the last
  18424. time they were saved.
  18425. Returns false if it fails to write to the file for some reason (maybe because
  18426. it's read-only or the directory doesn't exist or something).
  18427. @see save
  18428. */
  18429. bool saveIfNeeded();
  18430. /** This will force a write-to-disk of the current values, regardless of whether
  18431. anything has changed since the last save.
  18432. Returns false if it fails to write to the file for some reason (maybe because
  18433. it's read-only or the directory doesn't exist or something).
  18434. @see saveIfNeeded
  18435. */
  18436. bool save();
  18437. /** Returns true if the properties have been altered since the last time they were
  18438. saved.
  18439. */
  18440. bool needsToBeSaved() const throw();
  18441. /** Returns the file that's being used. */
  18442. const File getFile() const throw();
  18443. /** Handy utility to create a properties file in whatever the standard OS-specific
  18444. location is for these things.
  18445. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18446. creates a PropertiesFile object with the specified properties. See
  18447. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18448. what the parameters do.
  18449. @see getDefaultAppSettingsFile
  18450. */
  18451. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18452. const String& fileNameSuffix,
  18453. const String& folderName,
  18454. const bool commonToAllUsers,
  18455. const int millisecondsBeforeSaving,
  18456. const int propertiesFileOptions);
  18457. /** Handy utility to choose a file in the standard OS-dependent location for application
  18458. settings files.
  18459. So on a Mac, this will return a file called:
  18460. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18461. On Windows it'll return something like:
  18462. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18463. On Linux it'll return
  18464. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18465. If you pass an empty string as the folder name, it'll use the app name for this (or
  18466. omit the folder name on the Mac).
  18467. If commonToAllUsers is true, then this will return the same file for all users of the
  18468. computer, regardless of the current user. If it is false, the file will be specific to
  18469. only the current user. Use this to choose whether you're saving settings that are common
  18470. or user-specific.
  18471. */
  18472. static const File getDefaultAppSettingsFile (const String& applicationName,
  18473. const String& fileNameSuffix,
  18474. const String& folderName,
  18475. const bool commonToAllUsers);
  18476. juce_UseDebuggingNewOperator
  18477. protected:
  18478. virtual void propertyChanged();
  18479. private:
  18480. File file;
  18481. int timerInterval;
  18482. const int options;
  18483. bool needsWriting;
  18484. void timerCallback();
  18485. PropertiesFile (const PropertiesFile&);
  18486. const PropertiesFile& operator= (const PropertiesFile&);
  18487. };
  18488. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18489. /********* End of inlined file: juce_PropertiesFile.h *********/
  18490. /**
  18491. Manages a collection of properties.
  18492. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18493. as a singleton.
  18494. It holds two different PropertiesFile objects internally, one for user-specific
  18495. settings (stored in your user directory), and one for settings that are common to
  18496. all users (stored in a folder accessible to all users).
  18497. The class manages the creation of these files on-demand, allowing access via the
  18498. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18499. methods like testWriteAccess() to check that the files can be saved.
  18500. If you're using one of these as a singleton, then your app's start-up code should
  18501. first of all call setStorageParameters() to tell it the parameters to use to create
  18502. the properties files.
  18503. @see PropertiesFile
  18504. */
  18505. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18506. {
  18507. public:
  18508. /**
  18509. Creates an ApplicationProperties object.
  18510. Before using it, you must call setStorageParameters() to give it the info
  18511. it needs to create the property files.
  18512. */
  18513. ApplicationProperties() throw();
  18514. /** Destructor.
  18515. */
  18516. ~ApplicationProperties();
  18517. juce_DeclareSingleton (ApplicationProperties, false)
  18518. /** Gives the object the information it needs to create the appropriate properties files.
  18519. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18520. info about how these parameters are used.
  18521. */
  18522. void setStorageParameters (const String& applicationName,
  18523. const String& fileNameSuffix,
  18524. const String& folderName,
  18525. const int millisecondsBeforeSaving,
  18526. const int propertiesFileOptions) throw();
  18527. /** Tests whether the files can be successfully written to, and can show
  18528. an error message if not.
  18529. Returns true if none of the tests fail.
  18530. @param testUserSettings if true, the user settings file will be tested
  18531. @param testCommonSettings if true, the common settings file will be tested
  18532. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18533. message box if either of the tests fail
  18534. */
  18535. bool testWriteAccess (const bool testUserSettings,
  18536. const bool testCommonSettings,
  18537. const bool showWarningDialogOnFailure);
  18538. /** Returns the user settings file.
  18539. The first time this is called, it will create and load the properties file.
  18540. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18541. the common settings are used as a second-chance place to look. This is done via the
  18542. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18543. to the fallback for the user settings.
  18544. @see getCommonSettings
  18545. */
  18546. PropertiesFile* getUserSettings() throw();
  18547. /** Returns the common settings file.
  18548. The first time this is called, it will create and load the properties file.
  18549. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18550. read-only (e.g. because the user doesn't have permission to write
  18551. to shared files), then this will return the user settings instead,
  18552. (like getUserSettings() would do). This is handy if you'd like to
  18553. write a value to the common settings, but if that's no possible,
  18554. then you'd rather write to the user settings than none at all.
  18555. If returnUserPropsIfReadOnly is false, this method will always return
  18556. the common settings, even if any changes to them can't be saved.
  18557. @see getUserSettings
  18558. */
  18559. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18560. /** Saves both files if they need to be saved.
  18561. @see PropertiesFile::saveIfNeeded
  18562. */
  18563. bool saveIfNeeded();
  18564. /** Flushes and closes both files if they are open.
  18565. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18566. and closes both files. They will then be re-opened the next time getUserSettings()
  18567. or getCommonSettings() is called.
  18568. */
  18569. void closeFiles();
  18570. juce_UseDebuggingNewOperator
  18571. private:
  18572. PropertiesFile* userProps;
  18573. PropertiesFile* commonProps;
  18574. String appName, fileSuffix, folderName;
  18575. int msBeforeSaving, options;
  18576. int commonSettingsAreReadOnly;
  18577. ApplicationProperties (const ApplicationProperties&);
  18578. const ApplicationProperties& operator= (const ApplicationProperties&);
  18579. void openFiles() throw();
  18580. };
  18581. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18582. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18583. #endif
  18584. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18585. #endif
  18586. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18587. #endif
  18588. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18589. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18590. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18591. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18592. /**
  18593. Handles reading/writing to the system's clipboard.
  18594. */
  18595. class JUCE_API SystemClipboard
  18596. {
  18597. public:
  18598. /** Copies a string of text onto the clipboard */
  18599. static void copyTextToClipboard (const String& text) throw();
  18600. /** Gets the current clipboard's contents.
  18601. Obviously this might have come from another app, so could contain
  18602. anything..
  18603. */
  18604. static const String getTextFromClipboard() throw();
  18605. };
  18606. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18607. /********* End of inlined file: juce_SystemClipboard.h *********/
  18608. #endif
  18609. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  18610. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  18611. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  18612. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  18613. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18614. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18615. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18616. /********* Start of inlined file: juce_MidiMessage.h *********/
  18617. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18618. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18619. /**
  18620. Encapsulates a MIDI message.
  18621. @see MidiMessageSequence, MidiOutput, MidiInput
  18622. */
  18623. class JUCE_API MidiMessage
  18624. {
  18625. public:
  18626. /** Creates a 3-byte short midi message.
  18627. @param byte1 message byte 1
  18628. @param byte2 message byte 2
  18629. @param byte3 message byte 3
  18630. @param timeStamp the time to give the midi message - this value doesn't
  18631. use any particular units, so will be application-specific
  18632. */
  18633. MidiMessage (const int byte1,
  18634. const int byte2,
  18635. const int byte3,
  18636. const double timeStamp = 0) throw();
  18637. /** Creates a 2-byte short midi message.
  18638. @param byte1 message byte 1
  18639. @param byte2 message byte 2
  18640. @param timeStamp the time to give the midi message - this value doesn't
  18641. use any particular units, so will be application-specific
  18642. */
  18643. MidiMessage (const int byte1,
  18644. const int byte2,
  18645. const double timeStamp = 0) throw();
  18646. /** Creates a 1-byte short midi message.
  18647. @param byte1 message byte 1
  18648. @param timeStamp the time to give the midi message - this value doesn't
  18649. use any particular units, so will be application-specific
  18650. */
  18651. MidiMessage (const int byte1,
  18652. const double timeStamp = 0) throw();
  18653. /** Creates a midi message from a block of data. */
  18654. MidiMessage (const uint8* const data,
  18655. const int dataSize,
  18656. const double timeStamp = 0) throw();
  18657. /** Reads the next midi message from some data.
  18658. This will read as many bytes from a data stream as it needs to make a
  18659. complete message, and will return the number of bytes it used. This lets
  18660. you read a sequence of midi messages from a file or stream.
  18661. @param data the data to read from
  18662. @param size the maximum number of bytes it's allowed to read
  18663. @param numBytesUsed returns the number of bytes that were actually needed
  18664. @param lastStatusByte in a sequence of midi messages, the initial byte
  18665. can be dropped from a message if it's the same as the
  18666. first byte of the previous message, so this lets you
  18667. supply the byte to use if the first byte of the message
  18668. has in fact been dropped.
  18669. @param timeStamp the time to give the midi message - this value doesn't
  18670. use any particular units, so will be application-specific
  18671. */
  18672. MidiMessage (const uint8* data,
  18673. int size,
  18674. int& numBytesUsed,
  18675. uint8 lastStatusByte,
  18676. double timeStamp = 0) throw();
  18677. /** Creates a copy of another midi message. */
  18678. MidiMessage (const MidiMessage& other) throw();
  18679. /** Creates a copy of another midi message, with a different timestamp. */
  18680. MidiMessage (const MidiMessage& other,
  18681. const double newTimeStamp) throw();
  18682. /** Destructor. */
  18683. ~MidiMessage() throw();
  18684. /** Copies this message from another one. */
  18685. const MidiMessage& operator= (const MidiMessage& other) throw();
  18686. /** Returns a pointer to the raw midi data.
  18687. @see getRawDataSize
  18688. */
  18689. uint8* getRawData() const throw() { return data; }
  18690. /** Returns the number of bytes of data in the message.
  18691. @see getRawData
  18692. */
  18693. int getRawDataSize() const throw() { return size; }
  18694. /** Returns the timestamp associated with this message.
  18695. The units for the timestamp will be application-specific.
  18696. @see setTimeStamp, addToTimeStamp
  18697. */
  18698. double getTimeStamp() const throw() { return timeStamp; }
  18699. /** Changes the message's associated timestamp.
  18700. The units for the timestamp will be application-specific.
  18701. @see addToTimeStamp, getTimeStamp
  18702. */
  18703. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18704. /** Adds a value to the message's timestamp.
  18705. The units for the timestamp will be application-specific.
  18706. */
  18707. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18708. /** Returns the midi channel associated with the message.
  18709. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18710. if it's a sysex)
  18711. @see isForChannel, setChannel
  18712. */
  18713. int getChannel() const throw();
  18714. /** Returns true if the message applies to the given midi channel.
  18715. @param channelNumber the channel number to look for, in the range 1 to 16
  18716. @see getChannel, setChannel
  18717. */
  18718. bool isForChannel (const int channelNumber) const throw();
  18719. /** Changes the message's midi channel.
  18720. This won't do anything for non-channel messages like sysexes.
  18721. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18722. */
  18723. void setChannel (const int newChannelNumber) throw();
  18724. /** Returns true if this is a system-exclusive message.
  18725. */
  18726. bool isSysEx() const throw();
  18727. /** Returns a pointer to the sysex data inside the message.
  18728. If this event isn't a sysex event, it'll return 0.
  18729. @see getSysExDataSize
  18730. */
  18731. const uint8* getSysExData() const throw();
  18732. /** Returns the size of the sysex data.
  18733. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18734. @see getSysExData
  18735. */
  18736. int getSysExDataSize() const throw();
  18737. /** Returns true if this message is a 'key-down' event.
  18738. This will return false for a note-on event with a velocity of 0.
  18739. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18740. */
  18741. bool isNoteOn() const throw();
  18742. /** Creates a key-down message (using a floating-point velocity).
  18743. @param channel the midi channel, in the range 1 to 16
  18744. @param noteNumber the key number, 0 to 127
  18745. @param velocity in the range 0 to 1.0
  18746. @see isNoteOn
  18747. */
  18748. static const MidiMessage noteOn (const int channel,
  18749. const int noteNumber,
  18750. const float velocity) throw();
  18751. /** Creates a key-down message (using an integer velocity).
  18752. @param channel the midi channel, in the range 1 to 16
  18753. @param noteNumber the key number, 0 to 127
  18754. @param velocity in the range 0 to 127
  18755. @see isNoteOn
  18756. */
  18757. static const MidiMessage noteOn (const int channel,
  18758. const int noteNumber,
  18759. const uint8 velocity) throw();
  18760. /** Returns true if this message is a 'key-up' event.
  18761. This will also return true for a note-on event with a velocity of 0.
  18762. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18763. */
  18764. bool isNoteOff() const throw();
  18765. /** Creates a key-up message.
  18766. @param channel the midi channel, in the range 1 to 16
  18767. @param noteNumber the key number, 0 to 127
  18768. @see isNoteOff
  18769. */
  18770. static const MidiMessage noteOff (const int channel,
  18771. const int noteNumber) throw();
  18772. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18773. @see isNoteOn, isNoteOff
  18774. */
  18775. bool isNoteOnOrOff() const throw();
  18776. /** Returns the midi note number for note-on and note-off messages.
  18777. If the message isn't a note-on or off, the value returned will be
  18778. meaningless.
  18779. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18780. */
  18781. int getNoteNumber() const throw();
  18782. /** Changes the midi note number of a note-on or note-off message.
  18783. If the message isn't a note on or off, this will do nothing.
  18784. */
  18785. void setNoteNumber (const int newNoteNumber) throw();
  18786. /** Returns the velocity of a note-on or note-off message.
  18787. The value returned will be in the range 0 to 127.
  18788. If the message isn't a note-on or off event, it will return 0.
  18789. @see getFloatVelocity
  18790. */
  18791. uint8 getVelocity() const throw();
  18792. /** Returns the velocity of a note-on or note-off message.
  18793. The value returned will be in the range 0 to 1.0
  18794. If the message isn't a note-on or off event, it will return 0.
  18795. @see getVelocity, setVelocity
  18796. */
  18797. float getFloatVelocity() const throw();
  18798. /** Changes the velocity of a note-on or note-off message.
  18799. If the message isn't a note on or off, this will do nothing.
  18800. @param newVelocity the new velocity, in the range 0 to 1.0
  18801. @see getFloatVelocity, multiplyVelocity
  18802. */
  18803. void setVelocity (const float newVelocity) throw();
  18804. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18805. If the message isn't a note on or off, this will do nothing.
  18806. @param scaleFactor the value by which to multiply the velocity
  18807. @see setVelocity
  18808. */
  18809. void multiplyVelocity (const float scaleFactor) throw();
  18810. /** Returns true if the message is a program (patch) change message.
  18811. @see getProgramChangeNumber, getGMInstrumentName
  18812. */
  18813. bool isProgramChange() const throw();
  18814. /** Returns the new program number of a program change message.
  18815. If the message isn't a program change, the value returned will be
  18816. nonsense.
  18817. @see isProgramChange, getGMInstrumentName
  18818. */
  18819. int getProgramChangeNumber() const throw();
  18820. /** Creates a program-change message.
  18821. @param channel the midi channel, in the range 1 to 16
  18822. @param programNumber the midi program number, 0 to 127
  18823. @see isProgramChange, getGMInstrumentName
  18824. */
  18825. static const MidiMessage programChange (const int channel,
  18826. const int programNumber) throw();
  18827. /** Returns true if the message is a pitch-wheel move.
  18828. @see getPitchWheelValue, pitchWheel
  18829. */
  18830. bool isPitchWheel() const throw();
  18831. /** Returns the pitch wheel position from a pitch-wheel move message.
  18832. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18833. If called for messages which aren't pitch wheel events, the number returned will be
  18834. nonsense.
  18835. @see isPitchWheel
  18836. */
  18837. int getPitchWheelValue() const throw();
  18838. /** Creates a pitch-wheel move message.
  18839. @param channel the midi channel, in the range 1 to 16
  18840. @param position the wheel position, in the range 0 to 16383
  18841. @see isPitchWheel
  18842. */
  18843. static const MidiMessage pitchWheel (const int channel,
  18844. const int position) throw();
  18845. /** Returns true if the message is an aftertouch event.
  18846. For aftertouch events, use the getNoteNumber() method to find out the key
  18847. that it applies to, and getAftertouchValue() to find out the amount. Use
  18848. getChannel() to find out the channel.
  18849. @see getAftertouchValue, getNoteNumber
  18850. */
  18851. bool isAftertouch() const throw();
  18852. /** Returns the amount of aftertouch from an aftertouch messages.
  18853. The value returned is in the range 0 to 127, and will be nonsense for messages
  18854. other than aftertouch messages.
  18855. @see isAftertouch
  18856. */
  18857. int getAfterTouchValue() const throw();
  18858. /** Creates an aftertouch message.
  18859. @param channel the midi channel, in the range 1 to 16
  18860. @param noteNumber the key number, 0 to 127
  18861. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18862. @see isAftertouch
  18863. */
  18864. static const MidiMessage aftertouchChange (const int channel,
  18865. const int noteNumber,
  18866. const int aftertouchAmount) throw();
  18867. /** Returns true if the message is a channel-pressure change event.
  18868. This is like aftertouch, but common to the whole channel rather than a specific
  18869. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18870. to find out the channel.
  18871. @see channelPressureChange
  18872. */
  18873. bool isChannelPressure() const throw();
  18874. /** Returns the pressure from a channel pressure change message.
  18875. @returns the pressure, in the range 0 to 127
  18876. @see isChannelPressure, channelPressureChange
  18877. */
  18878. int getChannelPressureValue() const throw();
  18879. /** Creates a channel-pressure change event.
  18880. @param channel the midi channel: 1 to 16
  18881. @param pressure the pressure, 0 to 127
  18882. @see isChannelPressure
  18883. */
  18884. static const MidiMessage channelPressureChange (const int channel,
  18885. const int pressure) throw();
  18886. /** Returns true if this is a midi controller message.
  18887. @see getControllerNumber, getControllerValue, controllerEvent
  18888. */
  18889. bool isController() const throw();
  18890. /** Returns the controller number of a controller message.
  18891. The name of the controller can be looked up using the getControllerName() method.
  18892. Note that the value returned is invalid for messages that aren't controller changes.
  18893. @see isController, getControllerName, getControllerValue
  18894. */
  18895. int getControllerNumber() const throw();
  18896. /** Returns the controller value from a controller message.
  18897. A value 0 to 127 is returned to indicate the new controller position.
  18898. Note that the value returned is invalid for messages that aren't controller changes.
  18899. @see isController, getControllerNumber
  18900. */
  18901. int getControllerValue() const throw();
  18902. /** Creates a controller message.
  18903. @param channel the midi channel, in the range 1 to 16
  18904. @param controllerType the type of controller
  18905. @param value the controller value
  18906. @see isController
  18907. */
  18908. static const MidiMessage controllerEvent (const int channel,
  18909. const int controllerType,
  18910. const int value) throw();
  18911. /** Checks whether this message is an all-notes-off message.
  18912. @see allNotesOff
  18913. */
  18914. bool isAllNotesOff() const throw();
  18915. /** Checks whether this message is an all-sound-off message.
  18916. @see allSoundOff
  18917. */
  18918. bool isAllSoundOff() const throw();
  18919. /** Creates an all-notes-off message.
  18920. @param channel the midi channel, in the range 1 to 16
  18921. @see isAllNotesOff
  18922. */
  18923. static const MidiMessage allNotesOff (const int channel) throw();
  18924. /** Creates an all-sound-off message.
  18925. @param channel the midi channel, in the range 1 to 16
  18926. @see isAllSoundOff
  18927. */
  18928. static const MidiMessage allSoundOff (const int channel) throw();
  18929. /** Creates an all-controllers-off message.
  18930. @param channel the midi channel, in the range 1 to 16
  18931. */
  18932. static const MidiMessage allControllersOff (const int channel) throw();
  18933. /** Returns true if this event is a meta-event.
  18934. Meta-events are things like tempo changes, track names, etc.
  18935. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18936. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18937. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18938. */
  18939. bool isMetaEvent() const throw();
  18940. /** Returns a meta-event's type number.
  18941. If the message isn't a meta-event, this will return -1.
  18942. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18943. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18944. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18945. */
  18946. int getMetaEventType() const throw();
  18947. /** Returns a pointer to the data in a meta-event.
  18948. @see isMetaEvent, getMetaEventLength
  18949. */
  18950. const uint8* getMetaEventData() const throw();
  18951. /** Returns the length of the data for a meta-event.
  18952. @see isMetaEvent, getMetaEventData
  18953. */
  18954. int getMetaEventLength() const throw();
  18955. /** Returns true if this is a 'track' meta-event. */
  18956. bool isTrackMetaEvent() const throw();
  18957. /** Returns true if this is an 'end-of-track' meta-event. */
  18958. bool isEndOfTrackMetaEvent() const throw();
  18959. /** Creates an end-of-track meta-event.
  18960. @see isEndOfTrackMetaEvent
  18961. */
  18962. static const MidiMessage endOfTrack() throw();
  18963. /** Returns true if this is an 'track name' meta-event.
  18964. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18965. */
  18966. bool isTrackNameEvent() const throw();
  18967. /** Returns true if this is a 'text' meta-event.
  18968. @see getTextFromTextMetaEvent
  18969. */
  18970. bool isTextMetaEvent() const throw();
  18971. /** Returns the text from a text meta-event.
  18972. @see isTextMetaEvent
  18973. */
  18974. const String getTextFromTextMetaEvent() const throw();
  18975. /** Returns true if this is a 'tempo' meta-event.
  18976. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18977. */
  18978. bool isTempoMetaEvent() const throw();
  18979. /** Returns the tick length from a tempo meta-event.
  18980. @param timeFormat the 16-bit time format value from the midi file's header.
  18981. @returns the tick length (in seconds).
  18982. @see isTempoMetaEvent
  18983. */
  18984. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18985. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18986. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18987. */
  18988. double getTempoSecondsPerQuarterNote() const throw();
  18989. /** Creates a tempo meta-event.
  18990. @see isTempoMetaEvent
  18991. */
  18992. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18993. /** Returns true if this is a 'time-signature' meta-event.
  18994. @see getTimeSignatureInfo
  18995. */
  18996. bool isTimeSignatureMetaEvent() const throw();
  18997. /** Returns the time-signature values from a time-signature meta-event.
  18998. @see isTimeSignatureMetaEvent
  18999. */
  19000. void getTimeSignatureInfo (int& numerator,
  19001. int& denominator) const throw();
  19002. /** Creates a time-signature meta-event.
  19003. @see isTimeSignatureMetaEvent
  19004. */
  19005. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  19006. const int denominator) throw();
  19007. /** Returns true if this is a 'key-signature' meta-event.
  19008. @see getKeySignatureNumberOfSharpsOrFlats
  19009. */
  19010. bool isKeySignatureMetaEvent() const throw();
  19011. /** Returns the key from a key-signature meta-event.
  19012. @see isKeySignatureMetaEvent
  19013. */
  19014. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  19015. /** Returns true if this is a 'channel' meta-event.
  19016. A channel meta-event specifies the midi channel that should be used
  19017. for subsequent meta-events.
  19018. @see getMidiChannelMetaEventChannel
  19019. */
  19020. bool isMidiChannelMetaEvent() const throw();
  19021. /** Returns the channel number from a channel meta-event.
  19022. @returns the channel, in the range 1 to 16.
  19023. @see isMidiChannelMetaEvent
  19024. */
  19025. int getMidiChannelMetaEventChannel() const throw();
  19026. /** Creates a midi channel meta-event.
  19027. @param channel the midi channel, in the range 1 to 16
  19028. @see isMidiChannelMetaEvent
  19029. */
  19030. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  19031. /** Returns true if this is an active-sense message. */
  19032. bool isActiveSense() const throw();
  19033. /** Returns true if this is a midi start event.
  19034. @see midiStart
  19035. */
  19036. bool isMidiStart() const throw();
  19037. /** Creates a midi start event. */
  19038. static const MidiMessage midiStart() throw();
  19039. /** Returns true if this is a midi continue event.
  19040. @see midiContinue
  19041. */
  19042. bool isMidiContinue() const throw();
  19043. /** Creates a midi continue event. */
  19044. static const MidiMessage midiContinue() throw();
  19045. /** Returns true if this is a midi stop event.
  19046. @see midiStop
  19047. */
  19048. bool isMidiStop() const throw();
  19049. /** Creates a midi stop event. */
  19050. static const MidiMessage midiStop() throw();
  19051. /** Returns true if this is a midi clock event.
  19052. @see midiClock, songPositionPointer
  19053. */
  19054. bool isMidiClock() const throw();
  19055. /** Creates a midi clock event. */
  19056. static const MidiMessage midiClock() throw();
  19057. /** Returns true if this is a song-position-pointer message.
  19058. @see getSongPositionPointerMidiBeat, songPositionPointer
  19059. */
  19060. bool isSongPositionPointer() const throw();
  19061. /** Returns the midi beat-number of a song-position-pointer message.
  19062. @see isSongPositionPointer, songPositionPointer
  19063. */
  19064. int getSongPositionPointerMidiBeat() const throw();
  19065. /** Creates a song-position-pointer message.
  19066. The position is a number of midi beats from the start of the song, where 1 midi
  19067. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  19068. are 4 midi beats in a quarter-note.
  19069. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  19070. */
  19071. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  19072. /** Returns true if this is a quarter-frame midi timecode message.
  19073. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  19074. */
  19075. bool isQuarterFrame() const throw();
  19076. /** Returns the sequence number of a quarter-frame midi timecode message.
  19077. This will be a value between 0 and 7.
  19078. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  19079. */
  19080. int getQuarterFrameSequenceNumber() const throw();
  19081. /** Returns the value from a quarter-frame message.
  19082. This will be the lower nybble of the message's data-byte, a value
  19083. between 0 and 15
  19084. */
  19085. int getQuarterFrameValue() const throw();
  19086. /** Creates a quarter-frame MTC message.
  19087. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  19088. @param value a value 0 to 15 for the lower nybble of the message's data byte
  19089. */
  19090. static const MidiMessage quarterFrame (const int sequenceNumber,
  19091. const int value) throw();
  19092. /** SMPTE timecode types.
  19093. Used by the getFullFrameParameters() and fullFrame() methods.
  19094. */
  19095. enum SmpteTimecodeType
  19096. {
  19097. fps24 = 0,
  19098. fps25 = 1,
  19099. fps30drop = 2,
  19100. fps30 = 3
  19101. };
  19102. /** Returns true if this is a full-frame midi timecode message.
  19103. */
  19104. bool isFullFrame() const throw();
  19105. /** Extracts the timecode information from a full-frame midi timecode message.
  19106. You should only call this on messages where you've used isFullFrame() to
  19107. check that they're the right kind.
  19108. */
  19109. void getFullFrameParameters (int& hours,
  19110. int& minutes,
  19111. int& seconds,
  19112. int& frames,
  19113. SmpteTimecodeType& timecodeType) const throw();
  19114. /** Creates a full-frame MTC message.
  19115. */
  19116. static const MidiMessage fullFrame (const int hours,
  19117. const int minutes,
  19118. const int seconds,
  19119. const int frames,
  19120. SmpteTimecodeType timecodeType);
  19121. /** Types of MMC command.
  19122. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  19123. */
  19124. enum MidiMachineControlCommand
  19125. {
  19126. mmc_stop = 1,
  19127. mmc_play = 2,
  19128. mmc_deferredplay = 3,
  19129. mmc_fastforward = 4,
  19130. mmc_rewind = 5,
  19131. mmc_recordStart = 6,
  19132. mmc_recordStop = 7,
  19133. mmc_pause = 9
  19134. };
  19135. /** Checks whether this is an MMC message.
  19136. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  19137. */
  19138. bool isMidiMachineControlMessage() const throw();
  19139. /** For an MMC message, this returns its type.
  19140. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  19141. calling this method.
  19142. */
  19143. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  19144. /** Creates an MMC message.
  19145. */
  19146. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  19147. /** Checks whether this is an MMC "goto" message.
  19148. If it is, the parameters passed-in are set to the time that the message contains.
  19149. @see midiMachineControlGoto
  19150. */
  19151. bool isMidiMachineControlGoto (int& hours,
  19152. int& minutes,
  19153. int& seconds,
  19154. int& frames) const throw();
  19155. /** Creates an MMC "goto" message.
  19156. This messages tells the device to go to a specific frame.
  19157. @see isMidiMachineControlGoto
  19158. */
  19159. static const MidiMessage midiMachineControlGoto (int hours,
  19160. int minutes,
  19161. int seconds,
  19162. int frames);
  19163. /** Creates a master-volume change message.
  19164. @param volume the volume, 0 to 1.0
  19165. */
  19166. static const MidiMessage masterVolume (const float volume) throw();
  19167. /** Creates a system-exclusive message.
  19168. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19169. */
  19170. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19171. const int dataSize) throw();
  19172. /** Reads a midi variable-length integer.
  19173. @param data the data to read the number from
  19174. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19175. */
  19176. static int readVariableLengthVal (const uint8* data,
  19177. int& numBytesUsed) throw();
  19178. /** Based on the first byte of a short midi message, this uses a lookup table
  19179. to return the message length (either 1, 2, or 3 bytes).
  19180. The value passed in must be 0x80 or higher.
  19181. */
  19182. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19183. /** Returns the name of a midi note number.
  19184. E.g "C", "D#", etc.
  19185. @param noteNumber the midi note number, 0 to 127
  19186. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19187. they'll be flattened, e.g. "Db"
  19188. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19189. e.g. "C#4"
  19190. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19191. number that will be used for middle C's octave
  19192. @see getMidiNoteInHertz
  19193. */
  19194. static const String getMidiNoteName (int noteNumber,
  19195. bool useSharps,
  19196. bool includeOctaveNumber,
  19197. int octaveNumForMiddleC) throw();
  19198. /** Returns the frequency of a midi note number.
  19199. @see getMidiNoteName
  19200. */
  19201. static const double getMidiNoteInHertz (int noteNumber) throw();
  19202. /** Returns the standard name of a GM instrument.
  19203. @param midiInstrumentNumber the program number 0 to 127
  19204. @see getProgramChangeNumber
  19205. */
  19206. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19207. /** Returns the name of a bank of GM instruments.
  19208. @param midiBankNumber the bank, 0 to 15
  19209. */
  19210. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19211. /** Returns the standard name of a channel 10 percussion sound.
  19212. @param midiNoteNumber the key number, 35 to 81
  19213. */
  19214. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19215. /** Returns the name of a controller type number.
  19216. @see getControllerNumber
  19217. */
  19218. static const String getControllerName (int controllerNumber) throw();
  19219. juce_UseDebuggingNewOperator
  19220. private:
  19221. double timeStamp;
  19222. uint8* data;
  19223. int message, size;
  19224. };
  19225. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19226. /********* End of inlined file: juce_MidiMessage.h *********/
  19227. /**
  19228. Holds a sequence of time-stamped midi events.
  19229. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19230. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19231. @see MidiMessage
  19232. */
  19233. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19234. {
  19235. public:
  19236. /** Creates an empty MidiBuffer. */
  19237. MidiBuffer() throw();
  19238. /** Creates a copy of another MidiBuffer. */
  19239. MidiBuffer (const MidiBuffer& other) throw();
  19240. /** Makes a copy of another MidiBuffer. */
  19241. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19242. /** Destructor */
  19243. ~MidiBuffer() throw();
  19244. /** Removes all events from the buffer. */
  19245. void clear() throw();
  19246. /** Removes all events between two times from the buffer.
  19247. All events for which (start <= event position < start + numSamples) will
  19248. be removed.
  19249. */
  19250. void clear (const int start,
  19251. const int numSamples) throw();
  19252. /** Returns true if the buffer is empty.
  19253. To actually retrieve the events, use a MidiBuffer::Iterator object
  19254. */
  19255. bool isEmpty() const throw();
  19256. /** Counts the number of events in the buffer.
  19257. This is actually quite a slow operation, as it has to iterate through all
  19258. the events, so you might prefer to call isEmpty() if that's all you need
  19259. to know.
  19260. */
  19261. int getNumEvents() const throw();
  19262. /** Adds an event to the buffer.
  19263. The sample number will be used to determine the position of the event in
  19264. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19265. ignored.
  19266. If an event is added whose sample position is the same as one or more events
  19267. already in the buffer, the new event will be placed after the existing ones.
  19268. To retrieve events, use a MidiBuffer::Iterator object
  19269. */
  19270. void addEvent (const MidiMessage& midiMessage,
  19271. const int sampleNumber) throw();
  19272. /** Adds an event to the buffer from raw midi data.
  19273. The sample number will be used to determine the position of the event in
  19274. the buffer, which is always kept sorted.
  19275. If an event is added whose sample position is the same as one or more events
  19276. already in the buffer, the new event will be placed after the existing ones.
  19277. The event data will be inspected to calculate the number of bytes in length that
  19278. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19279. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19280. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19281. add an event at all.
  19282. To retrieve events, use a MidiBuffer::Iterator object
  19283. */
  19284. void addEvent (const uint8* const rawMidiData,
  19285. const int maxBytesOfMidiData,
  19286. const int sampleNumber) throw();
  19287. /** Adds some events from another buffer to this one.
  19288. @param otherBuffer the buffer containing the events you want to add
  19289. @param startSample the lowest sample number in the source buffer for which
  19290. events should be added. Any source events whose timestamp is
  19291. less than this will be ignored
  19292. @param numSamples the valid range of samples from the source buffer for which
  19293. events should be added - i.e. events in the source buffer whose
  19294. timestamp is greater than or equal to (startSample + numSamples)
  19295. will be ignored. If this value is less than 0, all events after
  19296. startSample will be taken.
  19297. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19298. that are added to this buffer
  19299. */
  19300. void addEvents (const MidiBuffer& otherBuffer,
  19301. const int startSample,
  19302. const int numSamples,
  19303. const int sampleDeltaToAdd) throw();
  19304. /** Returns the sample number of the first event in the buffer.
  19305. If the buffer's empty, this will just return 0.
  19306. */
  19307. int getFirstEventTime() const throw();
  19308. /** Returns the sample number of the last event in the buffer.
  19309. If the buffer's empty, this will just return 0.
  19310. */
  19311. int getLastEventTime() const throw();
  19312. /**
  19313. Used to iterate through the events in a MidiBuffer.
  19314. Note that altering the buffer while an iterator is using it isn't a
  19315. safe operation.
  19316. @see MidiBuffer
  19317. */
  19318. class Iterator
  19319. {
  19320. public:
  19321. /** Creates an Iterator for this MidiBuffer. */
  19322. Iterator (const MidiBuffer& buffer) throw();
  19323. /** Destructor. */
  19324. ~Iterator() throw();
  19325. /** Repositions the iterator so that the next event retrieved will be the first
  19326. one whose sample position is at greater than or equal to the given position.
  19327. */
  19328. void setNextSamplePosition (const int samplePosition) throw();
  19329. /** Retrieves a copy of the next event from the buffer.
  19330. @param result on return, this will be the message (the MidiMessage's timestamp
  19331. is not set)
  19332. @param samplePosition on return, this will be the position of the event
  19333. @returns true if an event was found, or false if the iterator has reached
  19334. the end of the buffer
  19335. */
  19336. bool getNextEvent (MidiMessage& result,
  19337. int& samplePosition) throw();
  19338. /** Retrieves the next event from the buffer.
  19339. @param midiData on return, this pointer will be set to a block of data containing
  19340. the midi message. Note that to make it fast, this is a pointer
  19341. directly into the MidiBuffer's internal data, so is only valid
  19342. temporarily until the MidiBuffer is altered.
  19343. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19344. midi message
  19345. @param samplePosition on return, this will be the position of the event
  19346. @returns true if an event was found, or false if the iterator has reached
  19347. the end of the buffer
  19348. */
  19349. bool getNextEvent (const uint8* &midiData,
  19350. int& numBytesOfMidiData,
  19351. int& samplePosition) throw();
  19352. juce_UseDebuggingNewOperator
  19353. private:
  19354. const MidiBuffer& buffer;
  19355. const uint8* data;
  19356. Iterator (const Iterator&);
  19357. const Iterator& operator= (const Iterator&);
  19358. };
  19359. juce_UseDebuggingNewOperator
  19360. private:
  19361. friend class MidiBuffer::Iterator;
  19362. int bytesUsed;
  19363. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19364. };
  19365. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19366. /********* End of inlined file: juce_MidiBuffer.h *********/
  19367. class MidiKeyboardState;
  19368. /**
  19369. Receives events from a MidiKeyboardState object.
  19370. @see MidiKeyboardState
  19371. */
  19372. class JUCE_API MidiKeyboardStateListener
  19373. {
  19374. public:
  19375. MidiKeyboardStateListener() throw() {}
  19376. virtual ~MidiKeyboardStateListener() {}
  19377. /** Called when one of the MidiKeyboardState's keys is pressed.
  19378. This will be called synchronously when the state is either processing a
  19379. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19380. when a note is being played with its MidiKeyboardState::noteOn() method.
  19381. Note that this callback could happen from an audio callback thread, so be
  19382. careful not to block, and avoid any UI activity in the callback.
  19383. */
  19384. virtual void handleNoteOn (MidiKeyboardState* source,
  19385. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19386. /** Called when one of the MidiKeyboardState's keys is released.
  19387. This will be called synchronously when the state is either processing a
  19388. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19389. when a note is being played with its MidiKeyboardState::noteOff() method.
  19390. Note that this callback could happen from an audio callback thread, so be
  19391. careful not to block, and avoid any UI activity in the callback.
  19392. */
  19393. virtual void handleNoteOff (MidiKeyboardState* source,
  19394. int midiChannel, int midiNoteNumber) = 0;
  19395. };
  19396. /**
  19397. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19398. This object can parse a stream of midi events, using them to update its idea
  19399. of which keys are pressed for each individiual midi channel.
  19400. When keys go up or down, it can broadcast these events to listener objects.
  19401. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19402. methods, and midi messages for these events will be merged into the
  19403. midi stream that gets processed by processNextMidiBuffer().
  19404. */
  19405. class JUCE_API MidiKeyboardState
  19406. {
  19407. public:
  19408. MidiKeyboardState();
  19409. ~MidiKeyboardState();
  19410. /** Resets the state of the object.
  19411. All internal data for all the channels is reset, but no events are sent as a
  19412. result.
  19413. If you want to release any keys that are currently down, and to send out note-up
  19414. midi messages for this, use the allNotesOff() method instead.
  19415. */
  19416. void reset();
  19417. /** Returns true if the given midi key is currently held down for the given midi channel.
  19418. The channel number must be between 1 and 16. If you want to see if any notes are
  19419. on for a range of channels, use the isNoteOnForChannels() method.
  19420. */
  19421. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19422. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19423. The channel mask has a bit set for each midi channel you want to test for - bit
  19424. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19425. If a note is on for at least one of the specified channels, this returns true.
  19426. */
  19427. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19428. /** Turns a specified note on.
  19429. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19430. next call to processNextMidiBuffer().
  19431. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19432. gone down.
  19433. */
  19434. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19435. /** Turns a specified note off.
  19436. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19437. next call to processNextMidiBuffer().
  19438. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19439. gone up.
  19440. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19441. */
  19442. void noteOff (const int midiChannel, const int midiNoteNumber);
  19443. /** This will turn off any currently-down notes for the given midi channel.
  19444. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19445. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19446. and events being added to the midi stream.
  19447. */
  19448. void allNotesOff (const int midiChannel);
  19449. /** Looks at a key-up/down event and uses it to update the state of this object.
  19450. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19451. instead.
  19452. */
  19453. void processNextMidiEvent (const MidiMessage& message);
  19454. /** Scans a midi stream for up/down events and adds its own events to it.
  19455. This will look for any up/down events and use them to update the internal state,
  19456. synchronously making suitable callbacks to the listeners.
  19457. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19458. and noteOff() calls will be added into the buffer.
  19459. Only the section of the buffer whose timestamps are between startSample and
  19460. (startSample + numSamples) will be affected, and any events added will be placed
  19461. between these times.
  19462. If you're going to use this method, you'll need to keep calling it regularly for
  19463. it to work satisfactorily.
  19464. To process a single midi event at a time, use the processNextMidiEvent() method
  19465. instead.
  19466. */
  19467. void processNextMidiBuffer (MidiBuffer& buffer,
  19468. const int startSample,
  19469. const int numSamples,
  19470. const bool injectIndirectEvents);
  19471. /** Registers a listener for callbacks when keys go up or down.
  19472. @see removeListener
  19473. */
  19474. void addListener (MidiKeyboardStateListener* const listener) throw();
  19475. /** Deregisters a listener.
  19476. @see addListener
  19477. */
  19478. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19479. juce_UseDebuggingNewOperator
  19480. private:
  19481. CriticalSection lock;
  19482. uint16 noteStates [128];
  19483. MidiBuffer eventsToAdd;
  19484. VoidArray listeners;
  19485. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19486. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19487. MidiKeyboardState (const MidiKeyboardState&);
  19488. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19489. };
  19490. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19491. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19492. #endif
  19493. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19494. #endif
  19495. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19496. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19497. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19498. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19499. /********* Start of inlined file: juce_MidiInput.h *********/
  19500. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19501. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19502. class MidiInput;
  19503. /**
  19504. Receives midi messages from a midi input device.
  19505. This class is overridden to handle incoming midi messages. See the MidiInput
  19506. class for more details.
  19507. @see MidiInput
  19508. */
  19509. class JUCE_API MidiInputCallback
  19510. {
  19511. public:
  19512. /** Destructor. */
  19513. virtual ~MidiInputCallback() {}
  19514. /** Receives an incoming message.
  19515. A MidiInput object will call this method when a midi event arrives. It'll be
  19516. called on a high-priority system thread, so avoid doing anything time-consuming
  19517. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19518. for queueing incoming messages for use later.
  19519. @param source the MidiInput object that generated the message
  19520. @param message the incoming message. The message's timestamp is set to a value
  19521. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19522. time when the message arrived.
  19523. */
  19524. virtual void handleIncomingMidiMessage (MidiInput* source,
  19525. const MidiMessage& message) = 0;
  19526. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19527. If a long sysex message is broken up into multiple packets, this callback is made
  19528. for each packet that arrives until the message is finished, at which point
  19529. the normal handleIncomingMidiMessage() callback will be made with the entire
  19530. message.
  19531. The message passed in will contain the start of a sysex, but won't be finished
  19532. with the terminating 0xf7 byte.
  19533. */
  19534. virtual void handlePartialSysexMessage (MidiInput* source,
  19535. const uint8* messageData,
  19536. const int numBytesSoFar,
  19537. const double timestamp)
  19538. {
  19539. // (this bit is just to avoid compiler warnings about unused variables)
  19540. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19541. }
  19542. };
  19543. /**
  19544. Represents a midi input device.
  19545. To create one of these, use the static getDevices() method to find out what inputs are
  19546. available, and then use the openDevice() method to try to open one.
  19547. @see MidiOutput
  19548. */
  19549. class JUCE_API MidiInput
  19550. {
  19551. public:
  19552. /** Returns a list of the available midi input devices.
  19553. You can open one of the devices by passing its index into the
  19554. openDevice() method.
  19555. @see getDefaultDeviceIndex, openDevice
  19556. */
  19557. static const StringArray getDevices();
  19558. /** Returns the index of the default midi input device to use.
  19559. This refers to the index in the list returned by getDevices().
  19560. */
  19561. static int getDefaultDeviceIndex();
  19562. /** Tries to open one of the midi input devices.
  19563. This will return a MidiInput object if it manages to open it. You can then
  19564. call start() and stop() on this device, and delete it when no longer needed.
  19565. If the device can't be opened, this will return a null pointer.
  19566. @param deviceIndex the index of a device from the list returned by getDevices()
  19567. @param callback the object that will receive the midi messages from this device.
  19568. @see MidiInputCallback, getDevices
  19569. */
  19570. static MidiInput* openDevice (int deviceIndex,
  19571. MidiInputCallback* callback);
  19572. #if JUCE_LINUX || DOXYGEN
  19573. /** LINUX ONLY - This will try to create a new midi input device.
  19574. This will attempt to create a new midi input device with the specified name,
  19575. for other apps to connect to.
  19576. Returns 0 if a device can't be created.
  19577. @param deviceName the name to use for the new device
  19578. @param callback the object that will receive the midi messages from this device.
  19579. */
  19580. static MidiInput* createNewDevice (const String& deviceName,
  19581. MidiInputCallback* callback);
  19582. #endif
  19583. /** Destructor. */
  19584. virtual ~MidiInput();
  19585. /** Returns the name of this device.
  19586. */
  19587. virtual const String getName() const throw() { return name; }
  19588. /** Allows you to set a custom name for the device, in case you don't like the name
  19589. it was given when created.
  19590. */
  19591. virtual void setName (const String& newName) throw() { name = newName; }
  19592. /** Starts the device running.
  19593. After calling this, the device will start sending midi messages to the
  19594. MidiInputCallback object that was specified when the openDevice() method
  19595. was called.
  19596. @see stop
  19597. */
  19598. virtual void start();
  19599. /** Stops the device running.
  19600. @see start
  19601. */
  19602. virtual void stop();
  19603. juce_UseDebuggingNewOperator
  19604. protected:
  19605. String name;
  19606. void* internal;
  19607. MidiInput (const String& name);
  19608. MidiInput (const MidiInput&);
  19609. };
  19610. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19611. /********* End of inlined file: juce_MidiInput.h *********/
  19612. /**
  19613. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19614. processing by a block-based audio callback.
  19615. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19616. so it can easily use a midi input or keyboard component as its source.
  19617. @see MidiMessage, MidiInput
  19618. */
  19619. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19620. public MidiInputCallback
  19621. {
  19622. public:
  19623. /** Creates a MidiMessageCollector. */
  19624. MidiMessageCollector();
  19625. /** Destructor. */
  19626. ~MidiMessageCollector();
  19627. /** Clears any messages from the queue.
  19628. You need to call this method before starting to use the collector, so that
  19629. it knows the correct sample rate to use.
  19630. */
  19631. void reset (const double sampleRate);
  19632. /** Takes an incoming real-time message and adds it to the queue.
  19633. The message's timestamp is taken, and it will be ready for retrieval as part
  19634. of the block returned by the next call to removeNextBlockOfMessages().
  19635. This method is fully thread-safe when overlapping calls are made with
  19636. removeNextBlockOfMessages().
  19637. */
  19638. void addMessageToQueue (const MidiMessage& message);
  19639. /** Removes all the pending messages from the queue as a buffer.
  19640. This will also correct the messages' timestamps to make sure they're in
  19641. the range 0 to numSamples - 1.
  19642. This call should be made regularly by something like an audio processing
  19643. callback, because the time that it happens is used in calculating the
  19644. midi event positions.
  19645. This method is fully thread-safe when overlapping calls are made with
  19646. addMessageToQueue().
  19647. */
  19648. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19649. const int numSamples);
  19650. /** @internal */
  19651. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19652. /** @internal */
  19653. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19654. /** @internal */
  19655. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19656. juce_UseDebuggingNewOperator
  19657. private:
  19658. double lastCallbackTime;
  19659. CriticalSection midiCallbackLock;
  19660. MidiBuffer incomingMessages;
  19661. double sampleRate;
  19662. MidiMessageCollector (const MidiMessageCollector&);
  19663. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19664. };
  19665. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19666. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19667. #endif
  19668. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19669. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19670. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19671. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19672. /**
  19673. A sequence of timestamped midi messages.
  19674. This allows the sequence to be manipulated, and also to be read from and
  19675. written to a standard midi file.
  19676. @see MidiMessage, MidiFile
  19677. */
  19678. class JUCE_API MidiMessageSequence
  19679. {
  19680. public:
  19681. /** Creates an empty midi sequence object. */
  19682. MidiMessageSequence();
  19683. /** Creates a copy of another sequence. */
  19684. MidiMessageSequence (const MidiMessageSequence& other);
  19685. /** Replaces this sequence with another one. */
  19686. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19687. /** Destructor. */
  19688. ~MidiMessageSequence();
  19689. /** Structure used to hold midi events in the sequence.
  19690. These structures act as 'handles' on the events as they are moved about in
  19691. the list, and make it quick to find the matching note-offs for note-on events.
  19692. @see MidiMessageSequence::getEventPointer
  19693. */
  19694. class MidiEventHolder
  19695. {
  19696. public:
  19697. /** Destructor. */
  19698. ~MidiEventHolder();
  19699. /** The message itself, whose timestamp is used to specify the event's time.
  19700. */
  19701. MidiMessage message;
  19702. /** The matching note-off event (if this is a note-on event).
  19703. If this isn't a note-on, this pointer will be null.
  19704. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19705. note-offs up-to-date after events have been moved around in the sequence
  19706. or deleted.
  19707. */
  19708. MidiEventHolder* noteOffObject;
  19709. juce_UseDebuggingNewOperator
  19710. private:
  19711. friend class MidiMessageSequence;
  19712. MidiEventHolder (const MidiMessage& message);
  19713. };
  19714. /** Clears the sequence. */
  19715. void clear();
  19716. /** Returns the number of events in the sequence. */
  19717. int getNumEvents() const;
  19718. /** Returns a pointer to one of the events. */
  19719. MidiEventHolder* getEventPointer (const int index) const;
  19720. /** Returns the time of the note-up that matches the note-on at this index.
  19721. If the event at this index isn't a note-on, it'll just return 0.
  19722. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19723. */
  19724. double getTimeOfMatchingKeyUp (const int index) const;
  19725. /** Returns the index of the note-up that matches the note-on at this index.
  19726. If the event at this index isn't a note-on, it'll just return -1.
  19727. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19728. */
  19729. int getIndexOfMatchingKeyUp (const int index) const;
  19730. /** Returns the index of an event. */
  19731. int getIndexOf (MidiEventHolder* const event) const;
  19732. /** Returns the index of the first event on or after the given timestamp.
  19733. If the time is beyond the end of the sequence, this will return the
  19734. number of events.
  19735. */
  19736. int getNextIndexAtTime (const double timeStamp) const;
  19737. /** Returns the timestamp of the first event in the sequence.
  19738. @see getEndTime
  19739. */
  19740. double getStartTime() const;
  19741. /** Returns the timestamp of the last event in the sequence.
  19742. @see getStartTime
  19743. */
  19744. double getEndTime() const;
  19745. /** Returns the timestamp of the event at a given index.
  19746. If the index is out-of-range, this will return 0.0
  19747. */
  19748. double getEventTime (const int index) const;
  19749. /** Inserts a midi message into the sequence.
  19750. The index at which the new message gets inserted will depend on its timestamp,
  19751. because the sequence is kept sorted.
  19752. Remember to call updateMatchedPairs() after adding note-on events.
  19753. @param newMessage the new message to add (an internal copy will be made)
  19754. @param timeAdjustment an optional value to add to the timestamp of the message
  19755. that will be inserted
  19756. @see updateMatchedPairs
  19757. */
  19758. void addEvent (const MidiMessage& newMessage,
  19759. double timeAdjustment = 0);
  19760. /** Deletes one of the events in the sequence.
  19761. Remember to call updateMatchedPairs() after removing events.
  19762. @param index the index of the event to delete
  19763. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19764. if the event you're removing is a note-on
  19765. */
  19766. void deleteEvent (const int index,
  19767. const bool deleteMatchingNoteUp);
  19768. /** Merges another sequence into this one.
  19769. Remember to call updateMatchedPairs() after using this method.
  19770. @param other the sequence to add from
  19771. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19772. as they are read from the other sequence
  19773. @param firstAllowableDestTime events will not be added if their time is earlier
  19774. than this time. (This is after their time has been adjusted
  19775. by the timeAdjustmentDelta)
  19776. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19777. or greater than this time. (This is after their time has
  19778. been adjusted by the timeAdjustmentDelta)
  19779. */
  19780. void addSequence (const MidiMessageSequence& other,
  19781. double timeAdjustmentDelta,
  19782. double firstAllowableDestTime,
  19783. double endOfAllowableDestTimes);
  19784. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19785. Call this after moving messages about or deleting/adding messages, and it
  19786. will scan the list and make sure all the note-offs in the MidiEventHolder
  19787. structures are pointing at the correct ones.
  19788. */
  19789. void updateMatchedPairs();
  19790. /** Copies all the messages for a particular midi channel to another sequence.
  19791. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19792. @param destSequence the sequence that the chosen events should be copied to
  19793. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19794. channel) will also be copied across.
  19795. @see extractSysExMessages
  19796. */
  19797. void extractMidiChannelMessages (const int channelNumberToExtract,
  19798. MidiMessageSequence& destSequence,
  19799. const bool alsoIncludeMetaEvents) const;
  19800. /** Copies all midi sys-ex messages to another sequence.
  19801. @param destSequence this is the sequence to which any sys-exes in this sequence
  19802. will be added
  19803. @see extractMidiChannelMessages
  19804. */
  19805. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19806. /** Removes any messages in this sequence that have a specific midi channel.
  19807. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19808. */
  19809. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19810. /** Removes any sys-ex messages from this sequence.
  19811. */
  19812. void deleteSysExMessages();
  19813. /** Adds an offset to the timestamps of all events in the sequence.
  19814. @param deltaTime the amount to add to each timestamp.
  19815. */
  19816. void addTimeToMessages (const double deltaTime);
  19817. /** Scans through the sequence to determine the state of any midi controllers at
  19818. a given time.
  19819. This will create a sequence of midi controller changes that can be
  19820. used to set all midi controllers to the state they would be in at the
  19821. specified time within this sequence.
  19822. As well as controllers, it will also recreate the midi program number
  19823. and pitch bend position.
  19824. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19825. for other channels will be ignored.
  19826. @param time the time at which you want to find out the state - there are
  19827. no explicit units for this time measurement, it's the same units
  19828. as used for the timestamps of the messages
  19829. @param resultMessages an array to which midi controller-change messages will be added. This
  19830. will be the minimum number of controller changes to recreate the
  19831. state at the required time.
  19832. */
  19833. void createControllerUpdatesForTime (const int channelNumber,
  19834. const double time,
  19835. OwnedArray<MidiMessage>& resultMessages);
  19836. juce_UseDebuggingNewOperator
  19837. /** @internal */
  19838. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19839. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19840. private:
  19841. friend class MidiComparator;
  19842. friend class MidiFile;
  19843. OwnedArray <MidiEventHolder> list;
  19844. void sort();
  19845. };
  19846. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19847. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19848. #endif
  19849. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  19850. #endif
  19851. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19852. /********* Start of inlined file: juce_MidiFile.h *********/
  19853. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19854. #define __JUCE_MIDIFILE_JUCEHEADER__
  19855. /**
  19856. Reads/writes standard midi format files.
  19857. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19858. can then get the individual midi tracks from it using the getTrack() method.
  19859. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19860. to it using the addTrack() method, and then call its writeTo() method to stream
  19861. it out.
  19862. @see MidiMessageSequence
  19863. */
  19864. class JUCE_API MidiFile
  19865. {
  19866. public:
  19867. /** Creates an empty MidiFile object.
  19868. */
  19869. MidiFile() throw();
  19870. /** Destructor. */
  19871. ~MidiFile() throw();
  19872. /** Returns the number of tracks in the file.
  19873. @see getTrack, addTrack
  19874. */
  19875. int getNumTracks() const throw();
  19876. /** Returns a pointer to one of the tracks in the file.
  19877. @returns a pointer to the track, or 0 if the index is out-of-range
  19878. @see getNumTracks, addTrack
  19879. */
  19880. const MidiMessageSequence* getTrack (const int index) const throw();
  19881. /** Adds a midi track to the file.
  19882. This will make its own internal copy of the sequence that is passed-in.
  19883. @see getNumTracks, getTrack
  19884. */
  19885. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19886. /** Removes all midi tracks from the file.
  19887. @see getNumTracks
  19888. */
  19889. void clear() throw();
  19890. /** Returns the raw time format code that will be written to a stream.
  19891. After reading a midi file, this method will return the time-format that
  19892. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19893. or setSmpteTimeFormat() methods.
  19894. If the value returned is positive, it indicates the number of midi ticks
  19895. per quarter-note - see setTicksPerQuarterNote().
  19896. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19897. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19898. */
  19899. short getTimeFormat() const throw();
  19900. /** Sets the time format to use when this file is written to a stream.
  19901. If this is called, the file will be written as bars/beats using the
  19902. specified resolution, rather than SMPTE absolute times, as would be
  19903. used if setSmpteTimeFormat() had been called instead.
  19904. @param ticksPerQuarterNote e.g. 96, 960
  19905. @see setSmpteTimeFormat
  19906. */
  19907. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19908. /** Sets the time format to use when this file is written to a stream.
  19909. If this is called, the file will be written using absolute times, rather
  19910. than bars/beats as would be the case if setTicksPerBeat() had been called
  19911. instead.
  19912. @param framesPerSecond must be 24, 25, 29 or 30
  19913. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19914. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19915. timing, setSmpteTimeFormat (25, 40)
  19916. @see setTicksPerBeat
  19917. */
  19918. void setSmpteTimeFormat (const int framesPerSecond,
  19919. const int subframeResolution) throw();
  19920. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19921. Useful for finding the positions of all the tempo changes in a file.
  19922. @param tempoChangeEvents a list to which all the events will be added
  19923. */
  19924. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19925. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19926. Useful for finding the positions of all the tempo changes in a file.
  19927. @param timeSigEvents a list to which all the events will be added
  19928. */
  19929. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19930. /** Returns the latest timestamp in any of the tracks.
  19931. (Useful for finding the length of the file).
  19932. */
  19933. double getLastTimestamp() const;
  19934. /** Reads a midi file format stream.
  19935. After calling this, you can get the tracks that were read from the file by using the
  19936. getNumTracks() and getTrack() methods.
  19937. The timestamps of the midi events in the tracks will represent their positions in
  19938. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19939. method.
  19940. @returns true if the stream was read successfully
  19941. */
  19942. bool readFrom (InputStream& sourceStream);
  19943. /** Writes the midi tracks as a standard midi file.
  19944. @returns true if the operation succeeded.
  19945. */
  19946. bool writeTo (OutputStream& destStream);
  19947. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19948. This will use the midi time format and tempo/time signature info in the
  19949. tracks to convert all the timestamps to absolute values in seconds.
  19950. */
  19951. void convertTimestampTicksToSeconds();
  19952. juce_UseDebuggingNewOperator
  19953. /** @internal */
  19954. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19955. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19956. private:
  19957. MidiMessageSequence* tracks [128];
  19958. short numTracks, timeFormat;
  19959. MidiFile (const MidiFile&);
  19960. const MidiFile& operator= (const MidiFile&);
  19961. void readNextTrack (const char* data, int size);
  19962. void writeTrack (OutputStream& mainOut, const int trackNum);
  19963. };
  19964. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19965. /********* End of inlined file: juce_MidiFile.h *********/
  19966. #endif
  19967. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19968. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19969. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19970. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19971. /**
  19972. A set of routines to convert buffers of 32-bit floating point data to and from
  19973. various integer formats.
  19974. */
  19975. class JUCE_API AudioDataConverters
  19976. {
  19977. public:
  19978. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19979. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19980. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19981. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19982. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19983. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19984. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19985. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19986. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19987. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19988. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19989. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19990. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19991. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19992. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19993. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19994. enum DataFormat
  19995. {
  19996. int16LE,
  19997. int16BE,
  19998. int24LE,
  19999. int24BE,
  20000. int32LE,
  20001. int32BE,
  20002. float32LE,
  20003. float32BE,
  20004. };
  20005. static void convertFloatToFormat (const DataFormat destFormat,
  20006. const float* source, void* dest, int numSamples);
  20007. static void convertFormatToFloat (const DataFormat sourceFormat,
  20008. const void* source, float* dest, int numSamples);
  20009. static void interleaveSamples (const float** source, float* dest,
  20010. const int numSamples, const int numChannels);
  20011. static void deinterleaveSamples (const float* source, float** dest,
  20012. const int numSamples, const int numChannels);
  20013. };
  20014. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20015. /********* End of inlined file: juce_AudioDataConverters.h *********/
  20016. #endif
  20017. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20018. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20019. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20020. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20021. class AudioFormatReader;
  20022. class AudioFormatWriter;
  20023. /**
  20024. A multi-channel buffer of 32-bit floating point audio samples.
  20025. */
  20026. class JUCE_API AudioSampleBuffer
  20027. {
  20028. public:
  20029. /** Creates a buffer with a specified number of channels and samples.
  20030. The contents of the buffer will initially be undefined, so use clear() to
  20031. set all the samples to zero.
  20032. The buffer will allocate its memory internally, and this will be released
  20033. when the buffer is deleted.
  20034. */
  20035. AudioSampleBuffer (const int numChannels,
  20036. const int numSamples) throw();
  20037. /** Creates a buffer using a pre-allocated block of memory.
  20038. Note that if the buffer is resized or its number of channels is changed, it
  20039. will re-allocate memory internally and copy the existing data to this new area,
  20040. so it will then stop directly addressing this memory.
  20041. @param dataToReferTo a pre-allocated array containing pointers to the data
  20042. for each channel that should be used by this buffer. The
  20043. buffer will only refer to this memory, it won't try to delete
  20044. it when the buffer is deleted or resized.
  20045. @param numChannels the number of channels to use - this must correspond to the
  20046. number of elements in the array passed in
  20047. @param numSamples the number of samples to use - this must correspond to the
  20048. size of the arrays passed in
  20049. */
  20050. AudioSampleBuffer (float** dataToReferTo,
  20051. const int numChannels,
  20052. const int numSamples) throw();
  20053. /** Copies another buffer.
  20054. This buffer will make its own copy of the other's data, unless the buffer was created
  20055. using an external data buffer, in which case boths buffers will just point to the same
  20056. shared block of data.
  20057. */
  20058. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20059. /** Copies another buffer onto this one.
  20060. This buffer's size will be changed to that of the other buffer.
  20061. */
  20062. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20063. /** Destructor.
  20064. This will free any memory allocated by the buffer.
  20065. */
  20066. virtual ~AudioSampleBuffer() throw();
  20067. /** Returns the number of channels of audio data that this buffer contains.
  20068. @see getSampleData
  20069. */
  20070. int getNumChannels() const throw() { return numChannels; }
  20071. /** Returns the number of samples allocated in each of the buffer's channels.
  20072. @see getSampleData
  20073. */
  20074. int getNumSamples() const throw() { return size; }
  20075. /** Returns a pointer to a sample in one of the buffer's channels.
  20076. For speed, this doesn't check whether the channel and sample number
  20077. are legal, so be careful when using it!
  20078. */
  20079. float* getSampleData (const int channelNumber,
  20080. const int sampleOffset = 0) const throw();
  20081. /** Chages the buffer's size or number of channels.
  20082. This can expand or contract the buffer's length, and add or remove channels.
  20083. If keepExistingContent is true, it will try to preserve as much of the
  20084. old data as it can in the new buffer.
  20085. If clearExtraSpace is true, then any extra channels or space that is
  20086. allocated will be also be cleared. If false, then this space is left
  20087. uninitialised.
  20088. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20089. amount of memory that is currently allocated (but it will still increase it if
  20090. the new size is bigger than the amount it currently has). If this is false, then
  20091. a new allocation will be done so that the buffer uses takes up the minimum amount
  20092. of memory that it needs.
  20093. */
  20094. void setSize (const int newNumChannels,
  20095. const int newNumSamples,
  20096. const bool keepExistingContent = false,
  20097. const bool clearExtraSpace = false,
  20098. const bool avoidReallocating = false) throw();
  20099. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20100. There's also a constructor that lets you specify arrays like this, but this
  20101. lets you change the channels dynamically.
  20102. Note that if the buffer is resized or its number of channels is changed, it
  20103. will re-allocate memory internally and copy the existing data to this new area,
  20104. so it will then stop directly addressing this memory.
  20105. @param dataToReferTo a pre-allocated array containing pointers to the data
  20106. for each channel that should be used by this buffer. The
  20107. buffer will only refer to this memory, it won't try to delete
  20108. it when the buffer is deleted or resized.
  20109. @param numChannels the number of channels to use - this must correspond to the
  20110. number of elements in the array passed in
  20111. @param numSamples the number of samples to use - this must correspond to the
  20112. size of the arrays passed in
  20113. */
  20114. void setDataToReferTo (float** dataToReferTo,
  20115. const int numChannels,
  20116. const int numSamples) throw();
  20117. /** Clears all the samples in all channels. */
  20118. void clear() throw();
  20119. /** Clears a specified region of all the channels.
  20120. For speed, this doesn't check whether the channel and sample number
  20121. are in-range, so be careful!
  20122. */
  20123. void clear (const int startSample,
  20124. const int numSamples) throw();
  20125. /** Clears a specified region of just one channel.
  20126. For speed, this doesn't check whether the channel and sample number
  20127. are in-range, so be careful!
  20128. */
  20129. void clear (const int channel,
  20130. const int startSample,
  20131. const int numSamples) throw();
  20132. /** Applies a gain multiple to a region of one channel.
  20133. For speed, this doesn't check whether the channel and sample number
  20134. are in-range, so be careful!
  20135. */
  20136. void applyGain (const int channel,
  20137. const int startSample,
  20138. int numSamples,
  20139. const float gain) throw();
  20140. /** Applies a gain multiple to a region of all the channels.
  20141. For speed, this doesn't check whether the sample numbers
  20142. are in-range, so be careful!
  20143. */
  20144. void applyGain (const int startSample,
  20145. const int numSamples,
  20146. const float gain) throw();
  20147. /** Applies a range of gains to a region of a channel.
  20148. The gain that is applied to each sample will vary from
  20149. startGain on the first sample to endGain on the last Sample,
  20150. so it can be used to do basic fades.
  20151. For speed, this doesn't check whether the sample numbers
  20152. are in-range, so be careful!
  20153. */
  20154. void applyGainRamp (const int channel,
  20155. const int startSample,
  20156. int numSamples,
  20157. float startGain,
  20158. float endGain) throw();
  20159. /** Adds samples from another buffer to this one.
  20160. @param destChannel the channel within this buffer to add the samples to
  20161. @param destStartSample the start sample within this buffer's channel
  20162. @param source the source buffer to add from
  20163. @param sourceChannel the channel within the source buffer to read from
  20164. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20165. @param numSamples the number of samples to process
  20166. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20167. added to this buffer's samples
  20168. @see copyFrom
  20169. */
  20170. void addFrom (const int destChannel,
  20171. const int destStartSample,
  20172. const AudioSampleBuffer& source,
  20173. const int sourceChannel,
  20174. const int sourceStartSample,
  20175. int numSamples,
  20176. const float gainToApplyToSource = 1.0f) throw();
  20177. /** Adds samples from an array of floats to one of the channels.
  20178. @param destChannel the channel within this buffer to add the samples to
  20179. @param destStartSample the start sample within this buffer's channel
  20180. @param source the source data to use
  20181. @param numSamples the number of samples to process
  20182. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20183. added to this buffer's samples
  20184. @see copyFrom
  20185. */
  20186. void addFrom (const int destChannel,
  20187. const int destStartSample,
  20188. const float* source,
  20189. int numSamples,
  20190. const float gainToApplyToSource = 1.0f) throw();
  20191. /** Adds samples from an array of floats, applying a gain ramp to them.
  20192. @param destChannel the channel within this buffer to add the samples to
  20193. @param destStartSample the start sample within this buffer's channel
  20194. @param source the source data to use
  20195. @param numSamples the number of samples to process
  20196. @param startGain the gain to apply to the first sample (this is multiplied with
  20197. the source samples before they are added to this buffer)
  20198. @param endGain the gain to apply to the final sample. The gain is linearly
  20199. interpolated between the first and last samples.
  20200. */
  20201. void addFromWithRamp (const int destChannel,
  20202. const int destStartSample,
  20203. const float* source,
  20204. int numSamples,
  20205. float startGain,
  20206. float endGain) throw();
  20207. /** Copies samples from another buffer to this one.
  20208. @param destChannel the channel within this buffer to copy the samples to
  20209. @param destStartSample the start sample within this buffer's channel
  20210. @param source the source buffer to read from
  20211. @param sourceChannel the channel within the source buffer to read from
  20212. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20213. @param numSamples the number of samples to process
  20214. @see addFrom
  20215. */
  20216. void copyFrom (const int destChannel,
  20217. const int destStartSample,
  20218. const AudioSampleBuffer& source,
  20219. const int sourceChannel,
  20220. const int sourceStartSample,
  20221. int numSamples) throw();
  20222. /** Copies samples from an array of floats into one of the channels.
  20223. @param destChannel the channel within this buffer to copy the samples to
  20224. @param destStartSample the start sample within this buffer's channel
  20225. @param source the source buffer to read from
  20226. @param numSamples the number of samples to process
  20227. @see addFrom
  20228. */
  20229. void copyFrom (const int destChannel,
  20230. const int destStartSample,
  20231. const float* source,
  20232. int numSamples) throw();
  20233. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20234. @param destChannel the channel within this buffer to copy the samples to
  20235. @param destStartSample the start sample within this buffer's channel
  20236. @param source the source buffer to read from
  20237. @param numSamples the number of samples to process
  20238. @param gain the gain to apply
  20239. @see addFrom
  20240. */
  20241. void copyFrom (const int destChannel,
  20242. const int destStartSample,
  20243. const float* source,
  20244. int numSamples,
  20245. const float gain) throw();
  20246. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20247. @param destChannel the channel within this buffer to copy the samples to
  20248. @param destStartSample the start sample within this buffer's channel
  20249. @param source the source buffer to read from
  20250. @param numSamples the number of samples to process
  20251. @param startGain the gain to apply to the first sample (this is multiplied with
  20252. the source samples before they are copied to this buffer)
  20253. @param endGain the gain to apply to the final sample. The gain is linearly
  20254. interpolated between the first and last samples.
  20255. @see addFrom
  20256. */
  20257. void copyFromWithRamp (const int destChannel,
  20258. const int destStartSample,
  20259. const float* source,
  20260. int numSamples,
  20261. float startGain,
  20262. float endGain) throw();
  20263. /** Finds the highest and lowest sample values in a given range.
  20264. @param channel the channel to read from
  20265. @param startSample the start sample within the channel
  20266. @param numSamples the number of samples to check
  20267. @param minVal on return, the lowest value that was found
  20268. @param maxVal on return, the highest value that was found
  20269. */
  20270. void findMinMax (const int channel,
  20271. const int startSample,
  20272. int numSamples,
  20273. float& minVal,
  20274. float& maxVal) const throw();
  20275. /** Finds the highest absolute sample value within a region of a channel.
  20276. */
  20277. float getMagnitude (const int channel,
  20278. const int startSample,
  20279. const int numSamples) const throw();
  20280. /** Finds the highest absolute sample value within a region on all channels.
  20281. */
  20282. float getMagnitude (const int startSample,
  20283. const int numSamples) const throw();
  20284. /** Returns the root mean squared level for a region of a channel.
  20285. */
  20286. float getRMSLevel (const int channel,
  20287. const int startSample,
  20288. const int numSamples) const throw();
  20289. /** Fills a section of the buffer using an AudioReader as its source.
  20290. This will convert the reader's fixed- or floating-point data to
  20291. the buffer's floating-point format, and will try to intelligently
  20292. cope with mismatches between the number of channels in the reader
  20293. and the buffer.
  20294. @see writeToAudioWriter
  20295. */
  20296. void readFromAudioReader (AudioFormatReader* reader,
  20297. const int startSample,
  20298. const int numSamples,
  20299. const int readerStartSample,
  20300. const bool useReaderLeftChan,
  20301. const bool useReaderRightChan) throw();
  20302. /** Writes a section of this buffer to an audio writer.
  20303. This saves you having to mess about with channels or floating/fixed
  20304. point conversion.
  20305. @see readFromAudioReader
  20306. */
  20307. void writeToAudioWriter (AudioFormatWriter* writer,
  20308. const int startSample,
  20309. const int numSamples) const throw();
  20310. juce_UseDebuggingNewOperator
  20311. private:
  20312. int numChannels, size, allocatedBytes;
  20313. float** channels;
  20314. float* allocatedData;
  20315. float* preallocatedChannelSpace [32];
  20316. };
  20317. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20318. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20319. #endif
  20320. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20321. /********* Start of inlined file: juce_IIRFilter.h *********/
  20322. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20323. #define __JUCE_IIRFILTER_JUCEHEADER__
  20324. /**
  20325. An IIR filter that can perform low, high, or band-pass filtering on an
  20326. audio signal.
  20327. @see IIRFilterAudioSource
  20328. */
  20329. class JUCE_API IIRFilter
  20330. {
  20331. public:
  20332. /** Creates a filter.
  20333. Initially the filter is inactive, so will have no effect on samples that
  20334. you process with it. Use the appropriate method to turn it into the type
  20335. of filter needed.
  20336. */
  20337. IIRFilter() throw();
  20338. /** Creates a copy of another filter. */
  20339. IIRFilter (const IIRFilter& other) throw();
  20340. /** Destructor. */
  20341. ~IIRFilter() throw();
  20342. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20343. Note that this clears the processing state, but the type of filter and
  20344. its coefficients aren't changed. To put a filter into an inactive state, use
  20345. the makeInactive() method.
  20346. */
  20347. void reset() throw();
  20348. /** Performs the filter operation on the given set of samples.
  20349. */
  20350. void processSamples (float* const samples,
  20351. const int numSamples) throw();
  20352. /** Processes a single sample, without any locking or checking.
  20353. Use this if you need fast processing of a single value, but be aware that
  20354. this isn't thread-safe in the way that processSamples() is.
  20355. */
  20356. float processSingleSampleRaw (const float sample) throw();
  20357. /** Sets the filter up to act as a low-pass filter.
  20358. */
  20359. void makeLowPass (const double sampleRate,
  20360. const double frequency) throw();
  20361. /** Sets the filter up to act as a high-pass filter.
  20362. */
  20363. void makeHighPass (const double sampleRate,
  20364. const double frequency) throw();
  20365. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20366. The gain is a scale factor that the low frequencies are multiplied by, so values
  20367. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20368. attenuate them.
  20369. */
  20370. void makeLowShelf (const double sampleRate,
  20371. const double cutOffFrequency,
  20372. const double Q,
  20373. const float gainFactor) throw();
  20374. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20375. The gain is a scale factor that the high frequencies are multiplied by, so values
  20376. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20377. attenuate them.
  20378. */
  20379. void makeHighShelf (const double sampleRate,
  20380. const double cutOffFrequency,
  20381. const double Q,
  20382. const float gainFactor) throw();
  20383. /** Sets the filter up to act as a band pass filter centred around a
  20384. frequency, with a variable Q and gain.
  20385. The gain is a scale factor that the centre frequencies are multiplied by, so
  20386. values greater than 1.0 will boost the centre frequencies, values less than
  20387. 1.0 will attenuate them.
  20388. */
  20389. void makeBandPass (const double sampleRate,
  20390. const double centreFrequency,
  20391. const double Q,
  20392. const float gainFactor) throw();
  20393. /** Clears the filter's coefficients so that it becomes inactive.
  20394. */
  20395. void makeInactive() throw();
  20396. /** Makes this filter duplicate the set-up of another one.
  20397. */
  20398. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20399. juce_UseDebuggingNewOperator
  20400. protected:
  20401. CriticalSection processLock;
  20402. void setCoefficients (double c1, double c2, double c3,
  20403. double c4, double c5, double c6) throw();
  20404. bool active;
  20405. float coefficients[6];
  20406. float x1, x2, y1, y2;
  20407. // (use the copyCoefficientsFrom() method instead of this operator)
  20408. const IIRFilter& operator= (const IIRFilter&);
  20409. };
  20410. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20411. /********* End of inlined file: juce_IIRFilter.h *********/
  20412. #endif
  20413. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20414. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20415. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20416. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20417. /**
  20418. A subclass of AudioPlayHead can supply information about the position and
  20419. status of a moving play head during audio playback.
  20420. One of these can be supplied to an AudioProcessor object so that it can find
  20421. out about the position of the audio that it is rendering.
  20422. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20423. */
  20424. class JUCE_API AudioPlayHead
  20425. {
  20426. protected:
  20427. AudioPlayHead() {}
  20428. public:
  20429. virtual ~AudioPlayHead() {}
  20430. /** Frame rate types. */
  20431. enum FrameRateType
  20432. {
  20433. fps24 = 0,
  20434. fps25 = 1,
  20435. fps2997 = 2,
  20436. fps30 = 3,
  20437. fps2997drop = 4,
  20438. fps30drop = 5,
  20439. fpsUnknown = 99
  20440. };
  20441. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20442. */
  20443. struct CurrentPositionInfo
  20444. {
  20445. /** The tempo in BPM */
  20446. double bpm;
  20447. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20448. int timeSigNumerator;
  20449. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20450. int timeSigDenominator;
  20451. /** The current play position, in seconds from the start of the edit. */
  20452. double timeInSeconds;
  20453. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20454. double editOriginTime;
  20455. /** The current play position in pulses-per-quarter-note.
  20456. This is the number of quarter notes since the edit start.
  20457. */
  20458. double ppqPosition;
  20459. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20460. This is the number of quarter notes from the start of the edit to the
  20461. start of the current bar.
  20462. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20463. it's not available, the value will be 0.
  20464. */
  20465. double ppqPositionOfLastBarStart;
  20466. /** The video frame rate, if applicable. */
  20467. FrameRateType frameRate;
  20468. /** True if the transport is currently playing. */
  20469. bool isPlaying;
  20470. /** True if the transport is currently recording.
  20471. (When isRecording is true, then isPlaying will also be true).
  20472. */
  20473. bool isRecording;
  20474. };
  20475. /** Fills-in the given structure with details about the transport's
  20476. position at the start of the current processing block.
  20477. */
  20478. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20479. };
  20480. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20481. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20482. #endif
  20483. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20484. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20485. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20486. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20487. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20488. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20489. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20490. class AudioProcessor;
  20491. /**
  20492. Base class for the component that acts as the GUI for an AudioProcessor.
  20493. Derive your editor component from this class, and create an instance of it
  20494. by overriding the AudioProcessor::createEditor() method.
  20495. @see AudioProcessor, GenericAudioProcessorEditor
  20496. */
  20497. class JUCE_API AudioProcessorEditor : public Component
  20498. {
  20499. protected:
  20500. /** Creates an editor for the specified processor.
  20501. */
  20502. AudioProcessorEditor (AudioProcessor* const owner);
  20503. public:
  20504. /** Destructor. */
  20505. ~AudioProcessorEditor();
  20506. /** Returns a pointer to the processor that this editor represents. */
  20507. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20508. private:
  20509. AudioProcessor* const owner;
  20510. };
  20511. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20512. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20513. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20514. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20515. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20516. class AudioProcessor;
  20517. /**
  20518. Base class for listeners that want to know about changes to an AudioProcessor.
  20519. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20520. @see AudioProcessor
  20521. */
  20522. class JUCE_API AudioProcessorListener
  20523. {
  20524. public:
  20525. /** Destructor. */
  20526. virtual ~AudioProcessorListener() {}
  20527. /** Receives a callback when a parameter is changed.
  20528. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20529. many audio processors will change their parameter during their audio callback.
  20530. This means that not only has your handler code got to be completely thread-safe,
  20531. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20532. this event on your message thread, use this callback to trigger an AsyncUpdater
  20533. or ChangeBroadcaster which you can respond to on the message thread.
  20534. */
  20535. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20536. int parameterIndex,
  20537. float newValue) = 0;
  20538. /** Called to indicate that something else in the plugin has changed, like its
  20539. program, number of parameters, etc.
  20540. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20541. call it during their audio callback. This means that not only has your handler code
  20542. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20543. blocking. If you need to handle this event on your message thread, use this callback
  20544. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20545. message thread.
  20546. */
  20547. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20548. /** Indicates that a parameter change gesture has started.
  20549. E.g. if the user is dragging a slider, this would be called when they first
  20550. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20551. called when they release it.
  20552. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20553. call it during their audio callback. This means that not only has your handler code
  20554. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20555. blocking. If you need to handle this event on your message thread, use this callback
  20556. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20557. message thread.
  20558. @see audioProcessorParameterChangeGestureEnd
  20559. */
  20560. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20561. int parameterIndex);
  20562. /** Indicates that a parameter change gesture has finished.
  20563. E.g. if the user is dragging a slider, this would be called when they release
  20564. the mouse button.
  20565. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20566. call it during their audio callback. This means that not only has your handler code
  20567. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20568. blocking. If you need to handle this event on your message thread, use this callback
  20569. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20570. message thread.
  20571. @see audioPluginParameterChangeGestureStart
  20572. */
  20573. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20574. int parameterIndex);
  20575. };
  20576. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20577. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20578. /**
  20579. Base class for audio processing filters or plugins.
  20580. This is intended to act as a base class of audio filter that is general enough to
  20581. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20582. It is also used by the plugin hosting code as the wrapper around an instance
  20583. of a loaded plugin.
  20584. Derive your filter class from this base class, and if you're building a plugin,
  20585. you should implement a global function called createPluginFilter() which creates
  20586. and returns a new instance of your subclass.
  20587. */
  20588. class JUCE_API AudioProcessor
  20589. {
  20590. protected:
  20591. /** Constructor.
  20592. You can also do your initialisation tasks in the initialiseFilterInfo()
  20593. call, which will be made after this object has been created.
  20594. */
  20595. AudioProcessor();
  20596. public:
  20597. /** Destructor. */
  20598. virtual ~AudioProcessor();
  20599. /** Returns the name of this processor.
  20600. */
  20601. virtual const String getName() const = 0;
  20602. /** Called before playback starts, to let the filter prepare itself.
  20603. The sample rate is the target sample rate, and will remain constant until
  20604. playback stops.
  20605. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20606. samples that will be processed for each callback, but isn't any kind
  20607. of guarantee. The actual block sizes that the host uses may be different
  20608. each time the callback happens, and may be more or less than this value.
  20609. */
  20610. virtual void prepareToPlay (double sampleRate,
  20611. int estimatedSamplesPerBlock) = 0;
  20612. /** Called after playback has stopped, to let the filter free up any resources it
  20613. no longer needs.
  20614. */
  20615. virtual void releaseResources() = 0;
  20616. /** Renders the next block.
  20617. When this method is called, the buffer contains a number of channels which is
  20618. at least as great as the maximum number of input and output channels that
  20619. this filter is using. It will be filled with the filter's input data and
  20620. should be replaced with the filter's output.
  20621. So for example if your filter has 2 input channels and 4 output channels, then
  20622. the buffer will contain 4 channels, the first two being filled with the
  20623. input data. Your filter should read these, do its processing, and replace
  20624. the contents of all 4 channels with its output.
  20625. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20626. all filled with data, and your filter should overwrite the first 2 of these
  20627. with its output. But be VERY careful not to write anything to the last 3
  20628. channels, as these might be mapped to memory that the host assumes is read-only!
  20629. Note that if you have more outputs than inputs, then only those channels that
  20630. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20631. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20632. but the last two channels may contain garbage, so you should be careful not to
  20633. let this pass through without being overwritten or cleared.
  20634. Also note that the buffer may have more channels than are strictly necessary,
  20635. but your should only read/write from the ones that your filter is supposed to
  20636. be using.
  20637. The number of samples in these buffers is NOT guaranteed to be the same for every
  20638. callback, and may be more or less than the estimated value given to prepareToPlay().
  20639. Your code must be able to cope with variable-sized blocks, or you're going to get
  20640. clicks and crashes!
  20641. If the filter is receiving a midi input, then the midiMessages array will be filled
  20642. with the midi messages for this block. Each message's timestamp will indicate the
  20643. message's time, as a number of samples from the start of the block.
  20644. Any messages left in the midi buffer when this method has finished are assumed to
  20645. be the filter's midi output. This means that your filter should be careful to
  20646. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20647. Be very careful about what you do in this callback - it's going to be called by
  20648. the audio thread, so any kind of interaction with the UI is absolutely
  20649. out of the question. If you change a parameter in here and need to tell your UI to
  20650. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20651. the UI components register as listeners, and then call sendChangeMessage() inside the
  20652. processBlock() method to send out an asynchronous message. You could also use
  20653. the AsyncUpdater class in a similar way.
  20654. */
  20655. virtual void processBlock (AudioSampleBuffer& buffer,
  20656. MidiBuffer& midiMessages) = 0;
  20657. /** Returns the current AudioPlayHead object that should be used to find
  20658. out the state and position of the playhead.
  20659. You can call this from your processBlock() method, and use the AudioPlayHead
  20660. object to get the details about the time of the start of the block currently
  20661. being processed.
  20662. If the host hasn't supplied a playhead object, this will return 0.
  20663. */
  20664. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20665. /** Returns the current sample rate.
  20666. This can be called from your processBlock() method - it's not guaranteed
  20667. to be valid at any other time, and may return 0 if it's unknown.
  20668. */
  20669. double getSampleRate() const throw() { return sampleRate; }
  20670. /** Returns the current typical block size that is being used.
  20671. This can be called from your processBlock() method - it's not guaranteed
  20672. to be valid at any other time.
  20673. Remember it's not the ONLY block size that may be used when calling
  20674. processBlock, it's just the normal one. The actual block sizes used may be
  20675. larger or smaller than this, and will vary between successive calls.
  20676. */
  20677. int getBlockSize() const throw() { return blockSize; }
  20678. /** Returns the number of input channels that the host will be sending the filter.
  20679. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20680. number of channels that your filter would prefer to have, and this method lets
  20681. you know how many the host is actually using.
  20682. Note that this method is only valid during or after the prepareToPlay()
  20683. method call. Until that point, the number of channels will be unknown.
  20684. */
  20685. int getNumInputChannels() const throw() { return numInputChannels; }
  20686. /** Returns the number of output channels that the host will be sending the filter.
  20687. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20688. number of channels that your filter would prefer to have, and this method lets
  20689. you know how many the host is actually using.
  20690. Note that this method is only valid during or after the prepareToPlay()
  20691. method call. Until that point, the number of channels will be unknown.
  20692. */
  20693. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20694. /** Returns the name of one of the input channels, as returned by the host.
  20695. The host might not supply very useful names for channels, and this might be
  20696. something like "1", "2", "left", "right", etc.
  20697. */
  20698. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20699. /** Returns the name of one of the output channels, as returned by the host.
  20700. The host might not supply very useful names for channels, and this might be
  20701. something like "1", "2", "left", "right", etc.
  20702. */
  20703. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20704. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20705. virtual bool isInputChannelStereoPair (int index) const = 0;
  20706. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20707. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20708. /** This returns the number of samples delay that the filter imposes on the audio
  20709. passing through it.
  20710. The host will call this to find the latency - the filter itself should set this value
  20711. by calling setLatencySamples() as soon as it can during its initialisation.
  20712. */
  20713. int getLatencySamples() const throw() { return latencySamples; }
  20714. /** The filter should call this to set the number of samples delay that it introduces.
  20715. The filter should call this as soon as it can during initialisation, and can call it
  20716. later if the value changes.
  20717. */
  20718. void setLatencySamples (const int newLatency);
  20719. /** Returns true if the processor wants midi messages. */
  20720. virtual bool acceptsMidi() const = 0;
  20721. /** Returns true if the processor produces midi messages. */
  20722. virtual bool producesMidi() const = 0;
  20723. /** This returns a critical section that will automatically be locked while the host
  20724. is calling the processBlock() method.
  20725. Use it from your UI or other threads to lock access to variables that are used
  20726. by the process callback, but obviously be careful not to keep it locked for
  20727. too long, because that could cause stuttering playback. If you need to do something
  20728. that'll take a long time and need the processing to stop while it happens, use the
  20729. suspendProcessing() method instead.
  20730. @see suspendProcessing
  20731. */
  20732. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20733. /** Enables and disables the processing callback.
  20734. If you need to do something time-consuming on a thread and would like to make sure
  20735. the audio processing callback doesn't happen until you've finished, use this
  20736. to disable the callback and re-enable it again afterwards.
  20737. E.g.
  20738. @code
  20739. void loadNewPatch()
  20740. {
  20741. suspendProcessing (true);
  20742. ..do something that takes ages..
  20743. suspendProcessing (false);
  20744. }
  20745. @endcode
  20746. If the host tries to make an audio callback while processing is suspended, the
  20747. filter will return an empty buffer, but won't block the audio thread like it would
  20748. do if you use the getCallbackLock() critical section to synchronise access.
  20749. If you're going to use this, your processBlock() method must call isSuspended() and
  20750. check whether it's suspended or not. If it is, then it should skip doing any real
  20751. processing, either emitting silence or passing the input through unchanged.
  20752. @see getCallbackLock
  20753. */
  20754. void suspendProcessing (const bool shouldBeSuspended);
  20755. /** Returns true if processing is currently suspended.
  20756. @see suspendProcessing
  20757. */
  20758. bool isSuspended() const throw() { return suspended; }
  20759. /** A plugin can override this to be told when it should reset any playing voices.
  20760. The default implementation does nothing, but a host may call this to tell the
  20761. plugin that it should stop any tails or sounds that have been left running.
  20762. */
  20763. virtual void reset();
  20764. /** Returns true if the processor is being run in an offline mode for rendering.
  20765. If the processor is being run live on realtime signals, this returns false.
  20766. If the mode is unknown, this will assume it's realtime and return false.
  20767. This value may be unreliable until the prepareToPlay() method has been called,
  20768. and could change each time prepareToPlay() is called.
  20769. @see setNonRealtime()
  20770. */
  20771. bool isNonRealtime() const throw() { return nonRealtime; }
  20772. /** Called by the host to tell this processor whether it's being used in a non-realime
  20773. capacity for offline rendering or bouncing.
  20774. Whatever value is passed-in will be
  20775. */
  20776. void setNonRealtime (const bool isNonRealtime) throw();
  20777. /** Creates the filter's UI.
  20778. This can return 0 if you want a UI-less filter, in which case the host may create
  20779. a generic UI that lets the user twiddle the parameters directly.
  20780. If you do want to pass back a component, the component should be created and set to
  20781. the correct size before returning it.
  20782. Remember not to do anything silly like allowing your filter to keep a pointer to
  20783. the component that gets created - it could be deleted later without any warning, which
  20784. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20785. The correct way to handle the connection between an editor component and its
  20786. filter is to use something like a ChangeBroadcaster so that the editor can
  20787. register itself as a listener, and be told when a change occurs. This lets them
  20788. safely unregister themselves when they are deleted.
  20789. Here are a few things to bear in mind when writing an editor:
  20790. - Initially there won't be an editor, until the user opens one, or they might
  20791. not open one at all. Your filter mustn't rely on it being there.
  20792. - An editor object may be deleted and a replacement one created again at any time.
  20793. - It's safe to assume that an editor will be deleted before its filter.
  20794. */
  20795. virtual AudioProcessorEditor* createEditor() = 0;
  20796. /** Returns the active editor, if there is one.
  20797. Bear in mind this can return 0, even if an editor has previously been
  20798. opened.
  20799. */
  20800. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20801. /** Returns the active editor, or if there isn't one, it will create one.
  20802. This may call createEditor() internally to create the component.
  20803. */
  20804. AudioProcessorEditor* createEditorIfNeeded();
  20805. /** This must return the correct value immediately after the object has been
  20806. created, and mustn't change the number of parameters later.
  20807. */
  20808. virtual int getNumParameters() = 0;
  20809. /** Returns the name of a particular parameter. */
  20810. virtual const String getParameterName (int parameterIndex) = 0;
  20811. /** Called by the host to find out the value of one of the filter's parameters.
  20812. The host will expect the value returned to be between 0 and 1.0.
  20813. This could be called quite frequently, so try to make your code efficient.
  20814. It's also likely to be called by non-UI threads, so the code in here should
  20815. be thread-aware.
  20816. */
  20817. virtual float getParameter (int parameterIndex) = 0;
  20818. /** Returns the value of a parameter as a text string. */
  20819. virtual const String getParameterText (int parameterIndex) = 0;
  20820. /** The host will call this method to change the value of one of the filter's parameters.
  20821. The host may call this at any time, including during the audio processing
  20822. callback, so the filter has to process this very fast and avoid blocking.
  20823. If you want to set the value of a parameter internally, e.g. from your
  20824. editor component, then don't call this directly - instead, use the
  20825. setParameterNotifyingHost() method, which will also send a message to
  20826. the host telling it about the change. If the message isn't sent, the host
  20827. won't be able to automate your parameters properly.
  20828. The value passed will be between 0 and 1.0.
  20829. */
  20830. virtual void setParameter (int parameterIndex,
  20831. float newValue) = 0;
  20832. /** Your filter can call this when it needs to change one of its parameters.
  20833. This could happen when the editor or some other internal operation changes
  20834. a parameter. This method will call the setParameter() method to change the
  20835. value, and will then send a message to the host telling it about the change.
  20836. Note that to make sure the host correctly handles automation, you should call
  20837. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20838. tell the host when the user has started and stopped changing the parameter.
  20839. */
  20840. void setParameterNotifyingHost (int parameterIndex,
  20841. float newValue);
  20842. /** Returns true if the host can automate this parameter.
  20843. By default, this returns true for all parameters.
  20844. */
  20845. virtual bool isParameterAutomatable (int parameterIndex) const;
  20846. /** Should return true if this parameter is a "meta" parameter.
  20847. A meta-parameter is a parameter that changes other params. It is used
  20848. by some hosts (e.g. AudioUnit hosts).
  20849. By default this returns false.
  20850. */
  20851. virtual bool isMetaParameter (int parameterIndex) const;
  20852. /** Sends a signal to the host to tell it that the user is about to start changing this
  20853. parameter.
  20854. This allows the host to know when a parameter is actively being held by the user, and
  20855. it may use this information to help it record automation.
  20856. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20857. */
  20858. void beginParameterChangeGesture (int parameterIndex);
  20859. /** Tells the host that the user has finished changing this parameter.
  20860. This allows the host to know when a parameter is actively being held by the user, and
  20861. it may use this information to help it record automation.
  20862. A call to this method must follow a call to beginParameterChangeGesture().
  20863. */
  20864. void endParameterChangeGesture (int parameterIndex);
  20865. /** The filter can call this when something (apart from a parameter value) has changed.
  20866. It sends a hint to the host that something like the program, number of parameters,
  20867. etc, has changed, and that it should update itself.
  20868. */
  20869. void updateHostDisplay();
  20870. /** Returns the number of preset programs the filter supports.
  20871. The value returned must be valid as soon as this object is created, and
  20872. must not change over its lifetime.
  20873. This value shouldn't be less than 1.
  20874. */
  20875. virtual int getNumPrograms() = 0;
  20876. /** Returns the number of the currently active program.
  20877. */
  20878. virtual int getCurrentProgram() = 0;
  20879. /** Called by the host to change the current program.
  20880. */
  20881. virtual void setCurrentProgram (int index) = 0;
  20882. /** Must return the name of a given program. */
  20883. virtual const String getProgramName (int index) = 0;
  20884. /** Called by the host to rename a program.
  20885. */
  20886. virtual void changeProgramName (int index, const String& newName) = 0;
  20887. /** The host will call this method when it wants to save the filter's internal state.
  20888. This must copy any info about the filter's state into the block of memory provided,
  20889. so that the host can store this and later restore it using setStateInformation().
  20890. Note that there's also a getCurrentProgramStateInformation() method, which only
  20891. stores the current program, not the state of the entire filter.
  20892. See also the helper function copyXmlToBinary() for storing settings as XML.
  20893. @see getCurrentProgramStateInformation
  20894. */
  20895. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20896. /** The host will call this method if it wants to save the state of just the filter's
  20897. current program.
  20898. Unlike getStateInformation, this should only return the current program's state.
  20899. Not all hosts support this, and if you don't implement it, the base class
  20900. method just calls getStateInformation() instead. If you do implement it, be
  20901. sure to also implement getCurrentProgramStateInformation.
  20902. @see getStateInformation, setCurrentProgramStateInformation
  20903. */
  20904. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20905. /** This must restore the filter's state from a block of data previously created
  20906. using getStateInformation().
  20907. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20908. to restore just the current program, not the state of the entire filter.
  20909. See also the helper function getXmlFromBinary() for loading settings as XML.
  20910. @see setCurrentProgramStateInformation
  20911. */
  20912. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20913. /** The host will call this method if it wants to restore the state of just the filter's
  20914. current program.
  20915. Not all hosts support this, and if you don't implement it, the base class
  20916. method just calls setStateInformation() instead. If you do implement it, be
  20917. sure to also implement getCurrentProgramStateInformation.
  20918. @see setStateInformation, getCurrentProgramStateInformation
  20919. */
  20920. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20921. /** Adds a listener that will be called when an aspect of this processor changes. */
  20922. void addListener (AudioProcessorListener* const newListener) throw();
  20923. /** Removes a previously added listener. */
  20924. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20925. /** Not for public use - this is called before deleting an editor component. */
  20926. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20927. /** Not for public use - this is called to initialise the processor. */
  20928. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20929. /** Not for public use - this is called to initialise the processor before playing. */
  20930. void setPlayConfigDetails (const int numIns, const int numOuts,
  20931. const double sampleRate,
  20932. const int blockSize) throw();
  20933. juce_UseDebuggingNewOperator
  20934. protected:
  20935. /** Helper function that just converts an xml element into a binary blob.
  20936. Use this in your filter's getStateInformation() method if you want to
  20937. store its state as xml.
  20938. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20939. from a binary blob.
  20940. */
  20941. static void copyXmlToBinary (const XmlElement& xml,
  20942. JUCE_NAMESPACE::MemoryBlock& destData);
  20943. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20944. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20945. an XmlElement object that the caller must delete when no longer needed.
  20946. */
  20947. static XmlElement* getXmlFromBinary (const void* data,
  20948. const int sizeInBytes);
  20949. /** @internal */
  20950. AudioPlayHead* playHead;
  20951. /** @internal */
  20952. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20953. private:
  20954. VoidArray listeners;
  20955. AudioProcessorEditor* activeEditor;
  20956. double sampleRate;
  20957. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20958. bool suspended, nonRealtime;
  20959. CriticalSection callbackLock, listenerLock;
  20960. #ifdef JUCE_DEBUG
  20961. BitArray changingParams;
  20962. #endif
  20963. AudioProcessor (const AudioProcessor&);
  20964. const AudioProcessor& operator= (const AudioProcessor&);
  20965. };
  20966. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20967. /********* End of inlined file: juce_AudioProcessor.h *********/
  20968. #endif
  20969. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20970. #endif
  20971. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20972. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20973. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20974. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20975. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20976. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20977. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20978. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20979. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20980. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20981. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20982. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20983. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20984. /********* Start of inlined file: juce_PluginDescription.h *********/
  20985. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20986. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20987. /**
  20988. A small class to represent some facts about a particular type of plugin.
  20989. This class is for storing and managing the details about a plugin without
  20990. actually having to load an instance of it.
  20991. A KnownPluginList contains a list of PluginDescription objects.
  20992. @see KnownPluginList
  20993. */
  20994. class JUCE_API PluginDescription
  20995. {
  20996. public:
  20997. PluginDescription() throw();
  20998. PluginDescription (const PluginDescription& other) throw();
  20999. const PluginDescription& operator= (const PluginDescription& other) throw();
  21000. ~PluginDescription() throw();
  21001. /** The name of the plugin. */
  21002. String name;
  21003. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  21004. */
  21005. String pluginFormatName;
  21006. /** A category, such as "Dynamics", "Reverbs", etc.
  21007. */
  21008. String category;
  21009. /** The manufacturer. */
  21010. String manufacturerName;
  21011. /** The version. This string doesn't have any particular format. */
  21012. String version;
  21013. /** Either the file containing the plugin module, or some other unique way
  21014. of identifying it.
  21015. E.g. for an AU, this would be an ID string that the component manager
  21016. could use to retrieve the plugin. For a VST, it's the file path.
  21017. */
  21018. String fileOrIdentifier;
  21019. /** The last time the plugin file was changed.
  21020. This is handy when scanning for new or changed plugins.
  21021. */
  21022. Time lastFileModTime;
  21023. /** A unique ID for the plugin.
  21024. Note that this might not be unique between formats, e.g. a VST and some
  21025. other format might actually have the same id.
  21026. @see createIdentifierString
  21027. */
  21028. int uid;
  21029. /** True if the plugin identifies itself as a synthesiser. */
  21030. bool isInstrument;
  21031. /** The number of inputs. */
  21032. int numInputChannels;
  21033. /** The number of outputs. */
  21034. int numOutputChannels;
  21035. /** Returns true if the two descriptions refer the the same plugin.
  21036. This isn't quite as simple as them just having the same file (because of
  21037. shell plugins).
  21038. */
  21039. bool isDuplicateOf (const PluginDescription& other) const;
  21040. /** Returns a string that can be saved and used to uniquely identify the
  21041. plugin again.
  21042. This contains less info than the XML encoding, and is independent of the
  21043. plugin's file location, so can be used to store a plugin ID for use
  21044. across different machines.
  21045. */
  21046. const String createIdentifierString() const throw();
  21047. /** Creates an XML object containing these details.
  21048. @see loadFromXml
  21049. */
  21050. XmlElement* createXml() const;
  21051. /** Reloads the info in this structure from an XML record that was previously
  21052. saved with createXML().
  21053. Returns true if the XML was a valid plugin description.
  21054. */
  21055. bool loadFromXml (const XmlElement& xml);
  21056. juce_UseDebuggingNewOperator
  21057. };
  21058. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21059. /********* End of inlined file: juce_PluginDescription.h *********/
  21060. /**
  21061. Base class for an active instance of a plugin.
  21062. This derives from the AudioProcessor class, and adds some extra functionality
  21063. that helps when wrapping dynamically loaded plugins.
  21064. @see AudioProcessor, AudioPluginFormat
  21065. */
  21066. class JUCE_API AudioPluginInstance : public AudioProcessor
  21067. {
  21068. public:
  21069. /** Destructor.
  21070. Make sure that you delete any UI components that belong to this plugin before
  21071. deleting the plugin.
  21072. */
  21073. virtual ~AudioPluginInstance();
  21074. /** Fills-in the appropriate parts of this plugin description object.
  21075. */
  21076. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  21077. juce_UseDebuggingNewOperator
  21078. protected:
  21079. AudioPluginInstance();
  21080. AudioPluginInstance (const AudioPluginInstance&);
  21081. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  21082. };
  21083. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21084. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  21085. class PluginDescription;
  21086. /**
  21087. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  21088. Use the static getNumFormats() and getFormat() calls to find the types
  21089. of format that are available.
  21090. */
  21091. class JUCE_API AudioPluginFormat
  21092. {
  21093. public:
  21094. /** Destructor. */
  21095. virtual ~AudioPluginFormat();
  21096. /** Returns the format name.
  21097. E.g. "VST", "AudioUnit", etc.
  21098. */
  21099. virtual const String getName() const = 0;
  21100. /** This tries to create descriptions for all the plugin types available in
  21101. a binary module file.
  21102. The file will be some kind of DLL or bundle.
  21103. Normally there will only be one type returned, but some plugins
  21104. (e.g. VST shells) can use a single DLL to create a set of different plugin
  21105. subtypes, so in that case, each subtype is returned as a separate object.
  21106. */
  21107. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  21108. const String& fileOrIdentifier) = 0;
  21109. /** Tries to recreate a type from a previously generated PluginDescription.
  21110. @see PluginDescription::createInstance
  21111. */
  21112. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  21113. /** Should do a quick check to see if this file or directory might be a plugin of
  21114. this format.
  21115. This is for searching for potential files, so it shouldn't actually try to
  21116. load the plugin or do anything time-consuming.
  21117. */
  21118. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  21119. /** Returns a readable version of the name of the plugin that this identifier refers to.
  21120. */
  21121. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  21122. /** Checks whether this plugin could possibly be loaded.
  21123. It doesn't actually need to load it, just to check whether the file or component
  21124. still exists.
  21125. */
  21126. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  21127. /** Searches a suggested set of directories for any plugins in this format.
  21128. The path might be ignored, e.g. by AUs, which are found by the OS rather
  21129. than manually.
  21130. */
  21131. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  21132. const bool recursive) = 0;
  21133. /** Returns the typical places to look for this kind of plugin.
  21134. Note that if this returns no paths, it means that the format can't be scanned-for
  21135. (i.e. it's an internal format that doesn't live in files)
  21136. */
  21137. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  21138. juce_UseDebuggingNewOperator
  21139. protected:
  21140. AudioPluginFormat() throw();
  21141. AudioPluginFormat (const AudioPluginFormat&);
  21142. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  21143. };
  21144. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21145. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  21146. /**
  21147. This maintains a list of known AudioPluginFormats.
  21148. @see AudioPluginFormat
  21149. */
  21150. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  21151. {
  21152. public:
  21153. AudioPluginFormatManager() throw();
  21154. /** Destructor. */
  21155. ~AudioPluginFormatManager() throw();
  21156. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  21157. /** Adds any formats that it knows about, e.g. VST.
  21158. */
  21159. void addDefaultFormats();
  21160. /** Returns the number of types of format that are available.
  21161. Use getFormat() to get one of them.
  21162. */
  21163. int getNumFormats() throw();
  21164. /** Returns one of the available formats.
  21165. @see getNumFormats
  21166. */
  21167. AudioPluginFormat* getFormat (const int index) throw();
  21168. /** Adds a format to the list.
  21169. The object passed in will be owned and deleted by the manager.
  21170. */
  21171. void addFormat (AudioPluginFormat* const format) throw();
  21172. /** Tries to load the type for this description, by trying all the formats
  21173. that this manager knows about.
  21174. The caller is responsible for deleting the object that is returned.
  21175. If it can't load the plugin, it returns 0 and leaves a message in the
  21176. errorMessage string.
  21177. */
  21178. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  21179. String& errorMessage) const;
  21180. /** Checks that the file or component for this plugin actually still exists.
  21181. (This won't try to load the plugin)
  21182. */
  21183. bool doesPluginStillExist (const PluginDescription& description) const;
  21184. juce_UseDebuggingNewOperator
  21185. private:
  21186. OwnedArray <AudioPluginFormat> formats;
  21187. AudioPluginFormatManager (const AudioPluginFormatManager&);
  21188. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  21189. };
  21190. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21191. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21192. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21193. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21194. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21195. /********* Start of inlined file: juce_PopupMenu.h *********/
  21196. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21197. #define __JUCE_POPUPMENU_JUCEHEADER__
  21198. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21199. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21200. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21201. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21202. @see PopupMenu::addCustomItem
  21203. */
  21204. class JUCE_API PopupMenuCustomComponent : public Component
  21205. {
  21206. public:
  21207. /** Destructor. */
  21208. ~PopupMenuCustomComponent();
  21209. /** Chooses the size that this component would like to have.
  21210. Note that the size which this method returns isn't necessarily the one that
  21211. the menu will give it, as it will be stretched to fit the other items in
  21212. the menu.
  21213. */
  21214. virtual void getIdealSize (int& idealWidth,
  21215. int& idealHeight) = 0;
  21216. /** Dismisses the menu indicating that this item has been chosen.
  21217. This will cause the menu to exit from its modal state, returning
  21218. this item's id as the result.
  21219. */
  21220. void triggerMenuItem();
  21221. /** Returns true if this item should be highlighted because the mouse is
  21222. over it.
  21223. You can call this method in your paint() method to find out whether
  21224. to draw a highlight.
  21225. */
  21226. bool isItemHighlighted() const throw() { return isHighlighted; }
  21227. protected:
  21228. /** Constructor.
  21229. If isTriggeredAutomatically is true, then the menu will automatically detect
  21230. a click on this component and use that to trigger it. If it's false, then it's
  21231. up to your class to manually trigger the item if it wants to.
  21232. */
  21233. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21234. private:
  21235. friend class MenuItemInfo;
  21236. friend class MenuItemComponent;
  21237. friend class PopupMenuWindow;
  21238. int refCount_;
  21239. bool isHighlighted, isTriggeredAutomatically;
  21240. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21241. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21242. };
  21243. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21244. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21245. /** Creates and displays a popup-menu.
  21246. To show a popup-menu, you create one of these, add some items to it, then
  21247. call its show() method, which returns the id of the item the user selects.
  21248. E.g. @code
  21249. void MyWidget::mouseDown (const MouseEvent& e)
  21250. {
  21251. PopupMenu m;
  21252. m.addItem (1, "item 1");
  21253. m.addItem (2, "item 2");
  21254. const int result = m.show();
  21255. if (result == 0)
  21256. {
  21257. // user dismissed the menu without picking anything
  21258. }
  21259. else if (result == 1)
  21260. {
  21261. // user picked item 1
  21262. }
  21263. else if (result == 2)
  21264. {
  21265. // user picked item 2
  21266. }
  21267. }
  21268. @endcode
  21269. Submenus are easy too: @code
  21270. void MyWidget::mouseDown (const MouseEvent& e)
  21271. {
  21272. PopupMenu subMenu;
  21273. subMenu.addItem (1, "item 1");
  21274. subMenu.addItem (2, "item 2");
  21275. PopupMenu mainMenu;
  21276. mainMenu.addItem (3, "item 3");
  21277. mainMenu.addSubMenu ("other choices", subMenu);
  21278. const int result = m.show();
  21279. ...etc
  21280. }
  21281. @endcode
  21282. */
  21283. class JUCE_API PopupMenu
  21284. {
  21285. public:
  21286. /** Creates an empty popup menu. */
  21287. PopupMenu() throw();
  21288. /** Creates a copy of another menu. */
  21289. PopupMenu (const PopupMenu& other) throw();
  21290. /** Destructor. */
  21291. ~PopupMenu() throw();
  21292. /** Copies this menu from another one. */
  21293. const PopupMenu& operator= (const PopupMenu& other) throw();
  21294. /** Resets the menu, removing all its items. */
  21295. void clear() throw();
  21296. /** Appends a new text item for this menu to show.
  21297. @param itemResultId the number that will be returned from the show() method
  21298. if the user picks this item. The value should never be
  21299. zero, because that's used to indicate that the user didn't
  21300. select anything.
  21301. @param itemText the text to show.
  21302. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21303. picked
  21304. @param isTicked if true, the item will be shown with a tick next to it
  21305. @param iconToUse if this is non-zero, it should be an image that will be
  21306. displayed to the left of the item. This method will take its
  21307. own copy of the image passed-in, so there's no need to keep
  21308. it hanging around.
  21309. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21310. */
  21311. void addItem (const int itemResultId,
  21312. const String& itemText,
  21313. const bool isActive = true,
  21314. const bool isTicked = false,
  21315. const Image* const iconToUse = 0) throw();
  21316. /** Adds an item that represents one of the commands in a command manager object.
  21317. @param commandManager the manager to use to trigger the command and get information
  21318. about it
  21319. @param commandID the ID of the command
  21320. @param displayName if this is non-empty, then this string will be used instead of
  21321. the command's registered name
  21322. */
  21323. void addCommandItem (ApplicationCommandManager* commandManager,
  21324. const int commandID,
  21325. const String& displayName = String::empty) throw();
  21326. /** Appends a text item with a special colour.
  21327. This is the same as addItem(), but specifies a colour to use for the
  21328. text, which will override the default colours that are used by the
  21329. current look-and-feel. See addItem() for a description of the parameters.
  21330. */
  21331. void addColouredItem (const int itemResultId,
  21332. const String& itemText,
  21333. const Colour& itemTextColour,
  21334. const bool isActive = true,
  21335. const bool isTicked = false,
  21336. const Image* const iconToUse = 0) throw();
  21337. /** Appends a custom menu item.
  21338. This will add a user-defined component to use as a menu item. The component
  21339. passed in will be deleted by this menu when it's no longer needed.
  21340. @see PopupMenuCustomComponent
  21341. */
  21342. void addCustomItem (const int itemResultId,
  21343. PopupMenuCustomComponent* const customComponent) throw();
  21344. /** Appends a custom menu item that can't be used to trigger a result.
  21345. This will add a user-defined component to use as a menu item. Unlike the
  21346. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21347. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21348. delete the component when it's finished, so it's the caller's responsibility
  21349. to manage the component that is passed-in.
  21350. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21351. detection of a mouse-click on your component, and use that to trigger the
  21352. menu ID specified in itemResultId. If this is false, the menu item can't
  21353. be triggered, so itemResultId is not used.
  21354. @see PopupMenuCustomComponent
  21355. */
  21356. void addCustomItem (const int itemResultId,
  21357. Component* customComponent,
  21358. int idealWidth, int idealHeight,
  21359. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21360. /** Appends a sub-menu.
  21361. If the menu that's passed in is empty, it will appear as an inactive item.
  21362. */
  21363. void addSubMenu (const String& subMenuName,
  21364. const PopupMenu& subMenu,
  21365. const bool isActive = true,
  21366. Image* const iconToUse = 0,
  21367. const bool isTicked = false) throw();
  21368. /** Appends a separator to the menu, to help break it up into sections.
  21369. The menu class is smart enough not to display separators at the top or bottom
  21370. of the menu, and it will replace mutliple adjacent separators with a single
  21371. one, so your code can be quite free and easy about adding these, and it'll
  21372. always look ok.
  21373. */
  21374. void addSeparator() throw();
  21375. /** Adds a non-clickable text item to the menu.
  21376. This is a bold-font items which can be used as a header to separate the items
  21377. into named groups.
  21378. */
  21379. void addSectionHeader (const String& title) throw();
  21380. /** Returns the number of items that the menu currently contains.
  21381. (This doesn't count separators).
  21382. */
  21383. int getNumItems() const throw();
  21384. /** Returns true if the menu contains a command item that triggers the given command. */
  21385. bool containsCommandItem (const int commandID) const throw();
  21386. /** Returns true if the menu contains any items that can be used. */
  21387. bool containsAnyActiveItems() const throw();
  21388. /** Displays the menu and waits for the user to pick something.
  21389. This will display the menu modally, and return the ID of the item that the
  21390. user picks. If they click somewhere off the menu to get rid of it without
  21391. choosing anything, this will return 0.
  21392. The current location of the mouse will be used as the position to show the
  21393. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21394. on where this point is on the screen, the menu will appear above, below or
  21395. to the side of the point.
  21396. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21397. then when the menu first appears, it will make sure
  21398. that this item is visible. So if the menu has too many
  21399. items to fit on the screen, it will be scrolled to a
  21400. position where this item is visible.
  21401. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21402. than this if some items are too long to fit.
  21403. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21404. vertical column, the menu may be laid out as a series of
  21405. columns - this is the maximum number allowed. To use the
  21406. default value for this (probably about 7), you can pass
  21407. in zero.
  21408. @param standardItemHeight if this is non-zero, it will be used as the standard
  21409. height for menu items (apart from custom items)
  21410. @see showAt
  21411. */
  21412. int show (const int itemIdThatMustBeVisible = 0,
  21413. const int minimumWidth = 0,
  21414. const int maximumNumColumns = 0,
  21415. const int standardItemHeight = 0);
  21416. /** Displays the menu at a specific location.
  21417. This is the same as show(), but uses a specific location (in global screen
  21418. co-ordinates) rather than the current mouse position.
  21419. Note that the co-ordinates don't specify the top-left of the menu - they
  21420. indicate a point of interest, and the menu will position itself nearby to
  21421. this point, trying to keep it fully on-screen.
  21422. @see show()
  21423. */
  21424. int showAt (const int screenX,
  21425. const int screenY,
  21426. const int itemIdThatMustBeVisible = 0,
  21427. const int minimumWidth = 0,
  21428. const int maximumNumColumns = 0,
  21429. const int standardItemHeight = 0);
  21430. /** Displays the menu as if it's attached to a component such as a button.
  21431. This is similar to showAt(), but will position it next to the given component, e.g.
  21432. so that the menu's edge is aligned with that of the component. This is intended for
  21433. things like buttons that trigger a pop-up menu.
  21434. */
  21435. int showAt (Component* componentToAttachTo,
  21436. const int itemIdThatMustBeVisible = 0,
  21437. const int minimumWidth = 0,
  21438. const int maximumNumColumns = 0,
  21439. const int standardItemHeight = 0);
  21440. /** Closes any menus that are currently open.
  21441. This might be useful if you have a situation where your window is being closed
  21442. by some means other than a user action, and you'd like to make sure that menus
  21443. aren't left hanging around.
  21444. */
  21445. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21446. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21447. This can be called before show() if you need a customised menu. Be careful
  21448. not to delete the LookAndFeel object before the menu has been deleted.
  21449. */
  21450. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21451. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21452. These constants can be used either via the LookAndFeel::setColour()
  21453. method for the look and feel that is set for this menu with setLookAndFeel()
  21454. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21455. */
  21456. enum ColourIds
  21457. {
  21458. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21459. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21460. colour is specified when the item is added). */
  21461. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21462. addSectionHeader() method). */
  21463. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21464. highlighted menu item. */
  21465. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21466. highlighted item. */
  21467. };
  21468. /**
  21469. Allows you to iterate through the items in a pop-up menu, and examine
  21470. their properties.
  21471. To use this, just create one and repeatedly call its next() method. When this
  21472. returns true, all the member variables of the iterator are filled-out with
  21473. information describing the menu item. When it returns false, the end of the
  21474. list has been reached.
  21475. */
  21476. class JUCE_API MenuItemIterator
  21477. {
  21478. public:
  21479. /** Creates an iterator that will scan through the items in the specified
  21480. menu.
  21481. Be careful not to add any items to a menu while it is being iterated,
  21482. or things could get out of step.
  21483. */
  21484. MenuItemIterator (const PopupMenu& menu) throw();
  21485. /** Destructor. */
  21486. ~MenuItemIterator() throw();
  21487. /** Returns true if there is another item, and sets up all this object's
  21488. member variables to reflect that item's properties.
  21489. */
  21490. bool next() throw();
  21491. String itemName;
  21492. const PopupMenu* subMenu;
  21493. int itemId;
  21494. bool isSeparator;
  21495. bool isTicked;
  21496. bool isEnabled;
  21497. bool isCustomComponent;
  21498. bool isSectionHeader;
  21499. const Colour* customColour;
  21500. const Image* customImage;
  21501. ApplicationCommandManager* commandManager;
  21502. juce_UseDebuggingNewOperator
  21503. private:
  21504. const PopupMenu& menu;
  21505. int index;
  21506. MenuItemIterator (const MenuItemIterator&);
  21507. const MenuItemIterator& operator= (const MenuItemIterator&);
  21508. };
  21509. juce_UseDebuggingNewOperator
  21510. private:
  21511. friend class PopupMenuWindow;
  21512. friend class MenuItemIterator;
  21513. VoidArray items;
  21514. LookAndFeel* lookAndFeel;
  21515. bool separatorPending;
  21516. void addSeparatorIfPending();
  21517. int showMenu (const int x, const int y, const int w, const int h,
  21518. const int itemIdThatMustBeVisible,
  21519. const int minimumWidth,
  21520. const int maximumNumColumns,
  21521. const int standardItemHeight,
  21522. const bool alignToRectangle,
  21523. Component* const componentAttachedTo) throw();
  21524. friend class MenuBarComponent;
  21525. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21526. const int itemIdThatMustBeVisible,
  21527. const int minimumWidth,
  21528. const int maximumNumColumns,
  21529. const int standardItemHeight,
  21530. const bool alignToRectangle,
  21531. Component* menuBarComponent,
  21532. ApplicationCommandManager** managerOfChosenCommand,
  21533. Component* const componentAttachedTo) throw();
  21534. };
  21535. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21536. /********* End of inlined file: juce_PopupMenu.h *********/
  21537. /**
  21538. Manages a list of plugin types.
  21539. This can be easily edited, saved and loaded, and used to create instances of
  21540. the plugin types in it.
  21541. @see PluginListComponent
  21542. */
  21543. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21544. {
  21545. public:
  21546. /** Creates an empty list.
  21547. */
  21548. KnownPluginList();
  21549. /** Destructor. */
  21550. ~KnownPluginList();
  21551. /** Clears the list. */
  21552. void clear();
  21553. /** Returns the number of types currently in the list.
  21554. @see getType
  21555. */
  21556. int getNumTypes() const throw() { return types.size(); }
  21557. /** Returns one of the types.
  21558. @see getNumTypes
  21559. */
  21560. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21561. /** Looks for a type in the list which comes from this file.
  21562. */
  21563. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21564. /** Looks for a type in the list which matches a plugin type ID.
  21565. The identifierString parameter must have been created by
  21566. PluginDescription::createIdentifierString().
  21567. */
  21568. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21569. /** Adds a type manually from its description. */
  21570. bool addType (const PluginDescription& type);
  21571. /** Removes a type. */
  21572. void removeType (const int index) throw();
  21573. /** Looks for all types that can be loaded from a given file, and adds them
  21574. to the list.
  21575. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21576. re-tested if it's not already in the list, or if the file's modification
  21577. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21578. false, the file will always be reloaded and tested.
  21579. Returns true if any new types were added, and all the types found in this
  21580. file (even if it was already known and hasn't been re-scanned) get returned
  21581. in the array.
  21582. */
  21583. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21584. const bool dontRescanIfAlreadyInList,
  21585. OwnedArray <PluginDescription>& typesFound,
  21586. AudioPluginFormat& formatToUse);
  21587. /** Returns true if the specified file is already known about and if it
  21588. hasn't been modified since our entry was created.
  21589. */
  21590. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21591. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21592. If any types are found in the files, their descriptions are returned in the array.
  21593. */
  21594. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21595. OwnedArray <PluginDescription>& typesFound);
  21596. /** Sort methods used to change the order of the plugins in the list.
  21597. */
  21598. enum SortMethod
  21599. {
  21600. defaultOrder = 0,
  21601. sortAlphabetically,
  21602. sortByCategory,
  21603. sortByManufacturer,
  21604. sortByFileSystemLocation
  21605. };
  21606. /** Adds all the plugin types to a popup menu so that the user can select one.
  21607. Depending on the sort method, it may add sub-menus for categories,
  21608. manufacturers, etc.
  21609. Use getIndexChosenByMenu() to find out the type that was chosen.
  21610. */
  21611. void addToMenu (PopupMenu& menu,
  21612. const SortMethod sortMethod) const;
  21613. /** Converts a menu item index that has been chosen into its index in this list.
  21614. Returns -1 if it's not an ID that was used.
  21615. @see addToMenu
  21616. */
  21617. int getIndexChosenByMenu (const int menuResultCode) const;
  21618. /** Sorts the list. */
  21619. void sort (const SortMethod method);
  21620. /** Creates some XML that can be used to store the state of this list.
  21621. */
  21622. XmlElement* createXml() const;
  21623. /** Recreates the state of this list from its stored XML format.
  21624. */
  21625. void recreateFromXml (const XmlElement& xml);
  21626. juce_UseDebuggingNewOperator
  21627. private:
  21628. OwnedArray <PluginDescription> types;
  21629. KnownPluginList (const KnownPluginList&);
  21630. const KnownPluginList& operator= (const KnownPluginList&);
  21631. };
  21632. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21633. /********* End of inlined file: juce_KnownPluginList.h *********/
  21634. /**
  21635. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21636. Use one of these objects if you want to wire-up a set of AudioProcessors
  21637. and play back the result.
  21638. Processors can be added to the graph as "nodes" using addNode(), and once
  21639. added, you can connect any of their input or output channels to other
  21640. nodes using addConnection().
  21641. To play back a graph through an audio device, you might want to use an
  21642. AudioProcessorPlayer object.
  21643. */
  21644. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21645. public AsyncUpdater
  21646. {
  21647. public:
  21648. /** Creates an empty graph.
  21649. */
  21650. AudioProcessorGraph();
  21651. /** Destructor.
  21652. Any processor objects that have been added to the graph will also be deleted.
  21653. */
  21654. ~AudioProcessorGraph();
  21655. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21656. To create a node, call AudioProcessorGraph::addNode().
  21657. */
  21658. class Node : public ReferenceCountedObject
  21659. {
  21660. public:
  21661. /** Destructor.
  21662. */
  21663. ~Node();
  21664. /** The ID number assigned to this node.
  21665. This is assigned by the graph that owns it, and can't be changed.
  21666. */
  21667. const uint32 id;
  21668. /** The actual processor object that this node represents.
  21669. */
  21670. AudioProcessor* const processor;
  21671. /** A set of user-definable properties that are associated with this node.
  21672. This can be used to attach values to the node for whatever purpose seems
  21673. useful. For example, you might store an x and y position if your application
  21674. is displaying the nodes on-screen.
  21675. */
  21676. PropertySet properties;
  21677. /** A convenient typedef for referring to a pointer to a node object.
  21678. */
  21679. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21680. juce_UseDebuggingNewOperator
  21681. private:
  21682. friend class AudioProcessorGraph;
  21683. bool isPrepared;
  21684. Node (const uint32 id, AudioProcessor* const processor) throw();
  21685. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21686. void unprepare();
  21687. Node (const Node&);
  21688. const Node& operator= (const Node&);
  21689. };
  21690. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21691. To create a connection, use AudioProcessorGraph::addConnection().
  21692. */
  21693. struct Connection
  21694. {
  21695. public:
  21696. /** The ID number of the node which is the input source for this connection.
  21697. @see AudioProcessorGraph::getNodeForId
  21698. */
  21699. uint32 sourceNodeId;
  21700. /** The index of the output channel of the source node from which this
  21701. connection takes its data.
  21702. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21703. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21704. index of an audio output channel in the source node.
  21705. */
  21706. int sourceChannelIndex;
  21707. /** The ID number of the node which is the destination for this connection.
  21708. @see AudioProcessorGraph::getNodeForId
  21709. */
  21710. uint32 destNodeId;
  21711. /** The index of the input channel of the destination node to which this
  21712. connection delivers its data.
  21713. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21714. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21715. index of an audio input channel in the destination node.
  21716. */
  21717. int destChannelIndex;
  21718. juce_UseDebuggingNewOperator
  21719. private:
  21720. };
  21721. /** Deletes all nodes and connections from this graph.
  21722. Any processor objects in the graph will be deleted.
  21723. */
  21724. void clear();
  21725. /** Returns the number of nodes in the graph. */
  21726. int getNumNodes() const throw() { return nodes.size(); }
  21727. /** Returns a pointer to one of the nodes in the graph.
  21728. This will return 0 if the index is out of range.
  21729. @see getNodeForId
  21730. */
  21731. Node* getNode (const int index) const throw() { return nodes [index]; }
  21732. /** Searches the graph for a node with the given ID number and returns it.
  21733. If no such node was found, this returns 0.
  21734. @see getNode
  21735. */
  21736. Node* getNodeForId (const uint32 nodeId) const throw();
  21737. /** Adds a node to the graph.
  21738. This creates a new node in the graph, for the specified processor. Once you have
  21739. added a processor to the graph, the graph owns it and will delete it later when
  21740. it is no longer needed.
  21741. The optional nodeId parameter lets you specify an ID to use for the node, but
  21742. if the value is already in use, this new node will overwrite the old one.
  21743. If this succeeds, it returns a pointer to the newly-created node.
  21744. */
  21745. Node* addNode (AudioProcessor* const newProcessor,
  21746. uint32 nodeId = 0);
  21747. /** Deletes a node within the graph which has the specified ID.
  21748. This will also delete any connections that are attached to this node.
  21749. */
  21750. bool removeNode (const uint32 nodeId);
  21751. /** Returns the number of connections in the graph. */
  21752. int getNumConnections() const throw() { return connections.size(); }
  21753. /** Returns a pointer to one of the connections in the graph. */
  21754. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21755. /** Searches for a connection between some specified channels.
  21756. If no such connection is found, this returns 0.
  21757. */
  21758. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21759. const int sourceChannelIndex,
  21760. const uint32 destNodeId,
  21761. const int destChannelIndex) const throw();
  21762. /** Returns true if there is a connection between any of the channels of
  21763. two specified nodes.
  21764. */
  21765. bool isConnected (const uint32 possibleSourceNodeId,
  21766. const uint32 possibleDestNodeId) const throw();
  21767. /** Returns true if it would be legal to connect the specified points.
  21768. */
  21769. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21770. const uint32 destNodeId, const int destChannelIndex) const throw();
  21771. /** Attempts to connect two specified channels of two nodes.
  21772. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21773. to an audio one or other such nonsense), then it'll return false.
  21774. */
  21775. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21776. const uint32 destNodeId, const int destChannelIndex);
  21777. /** Deletes the connection with the specified index.
  21778. Returns true if a connection was actually deleted.
  21779. */
  21780. void removeConnection (const int index);
  21781. /** Deletes any connection between two specified points.
  21782. Returns true if a connection was actually deleted.
  21783. */
  21784. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21785. const uint32 destNodeId, const int destChannelIndex);
  21786. /** Removes all connections from the specified node.
  21787. */
  21788. bool disconnectNode (const uint32 nodeId);
  21789. /** Performs a sanity checks of all the connections.
  21790. This might be useful if some of the processors are doing things like changing
  21791. their channel counts, which could render some connections obsolete.
  21792. */
  21793. bool removeIllegalConnections();
  21794. /** A special number that represents the midi channel of a node.
  21795. This is used as a channel index value if you want to refer to the midi input
  21796. or output instead of an audio channel.
  21797. */
  21798. static const int midiChannelIndex;
  21799. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21800. in order to use the audio that comes into and out of the graph itself.
  21801. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21802. node in the graph which delivers the audio that is coming into the parent
  21803. graph. This allows you to stream the data to other nodes and process the
  21804. incoming audio.
  21805. Likewise, one of these in "output" mode can be sent data which it will add to
  21806. the sum of data being sent to the graph's output.
  21807. @see AudioProcessorGraph
  21808. */
  21809. class AudioGraphIOProcessor : public AudioPluginInstance
  21810. {
  21811. public:
  21812. /** Specifies the mode in which this processor will operate.
  21813. */
  21814. enum IODeviceType
  21815. {
  21816. audioInputNode, /**< In this mode, the processor has output channels
  21817. representing all the audio input channels that are
  21818. coming into its parent audio graph. */
  21819. audioOutputNode, /**< In this mode, the processor has input channels
  21820. representing all the audio output channels that are
  21821. going out of its parent audio graph. */
  21822. midiInputNode, /**< In this mode, the processor has a midi output which
  21823. delivers the same midi data that is arriving at its
  21824. parent graph. */
  21825. midiOutputNode /**< In this mode, the processor has a midi input and
  21826. any data sent to it will be passed out of the parent
  21827. graph. */
  21828. };
  21829. /** Returns the mode of this processor. */
  21830. IODeviceType getType() const throw() { return type; }
  21831. /** Returns the parent graph to which this processor belongs, or 0 if it
  21832. hasn't yet been added to one. */
  21833. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21834. /** True if this is an audio or midi input. */
  21835. bool isInput() const throw();
  21836. /** True if this is an audio or midi output. */
  21837. bool isOutput() const throw();
  21838. AudioGraphIOProcessor (const IODeviceType type);
  21839. ~AudioGraphIOProcessor();
  21840. const String getName() const;
  21841. void fillInPluginDescription (PluginDescription& d) const;
  21842. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21843. void releaseResources();
  21844. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21845. const String getInputChannelName (const int channelIndex) const;
  21846. const String getOutputChannelName (const int channelIndex) const;
  21847. bool isInputChannelStereoPair (int index) const;
  21848. bool isOutputChannelStereoPair (int index) const;
  21849. bool acceptsMidi() const;
  21850. bool producesMidi() const;
  21851. AudioProcessorEditor* createEditor();
  21852. int getNumParameters();
  21853. const String getParameterName (int);
  21854. float getParameter (int);
  21855. const String getParameterText (int);
  21856. void setParameter (int, float);
  21857. int getNumPrograms();
  21858. int getCurrentProgram();
  21859. void setCurrentProgram (int);
  21860. const String getProgramName (int);
  21861. void changeProgramName (int, const String&);
  21862. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21863. void setStateInformation (const void* data, int sizeInBytes);
  21864. /** @internal */
  21865. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21866. juce_UseDebuggingNewOperator
  21867. private:
  21868. const IODeviceType type;
  21869. AudioProcessorGraph* graph;
  21870. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21871. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21872. };
  21873. // AudioProcessor methods:
  21874. const String getName() const;
  21875. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21876. void releaseResources();
  21877. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21878. const String getInputChannelName (const int channelIndex) const;
  21879. const String getOutputChannelName (const int channelIndex) const;
  21880. bool isInputChannelStereoPair (int index) const;
  21881. bool isOutputChannelStereoPair (int index) const;
  21882. bool acceptsMidi() const;
  21883. bool producesMidi() const;
  21884. AudioProcessorEditor* createEditor() { return 0; }
  21885. int getNumParameters() { return 0; }
  21886. const String getParameterName (int) { return String::empty; }
  21887. float getParameter (int) { return 0; }
  21888. const String getParameterText (int) { return String::empty; }
  21889. void setParameter (int, float) { }
  21890. int getNumPrograms() { return 0; }
  21891. int getCurrentProgram() { return 0; }
  21892. void setCurrentProgram (int) { }
  21893. const String getProgramName (int) { return String::empty; }
  21894. void changeProgramName (int, const String&) { }
  21895. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21896. void setStateInformation (const void* data, int sizeInBytes);
  21897. /** @internal */
  21898. void handleAsyncUpdate();
  21899. juce_UseDebuggingNewOperator
  21900. private:
  21901. ReferenceCountedArray <Node> nodes;
  21902. OwnedArray <Connection> connections;
  21903. int lastNodeId;
  21904. AudioSampleBuffer renderingBuffers;
  21905. OwnedArray <MidiBuffer> midiBuffers;
  21906. CriticalSection renderLock;
  21907. VoidArray renderingOps;
  21908. friend class AudioGraphIOProcessor;
  21909. AudioSampleBuffer* currentAudioInputBuffer;
  21910. AudioSampleBuffer currentAudioOutputBuffer;
  21911. MidiBuffer* currentMidiInputBuffer;
  21912. MidiBuffer currentMidiOutputBuffer;
  21913. void clearRenderingSequence();
  21914. void buildRenderingSequence();
  21915. bool isAnInputTo (const uint32 possibleInputId,
  21916. const uint32 possibleDestinationId,
  21917. const int recursionCheck) const throw();
  21918. AudioProcessorGraph (const AudioProcessorGraph&);
  21919. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21920. };
  21921. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21922. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21923. #endif
  21924. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21925. #endif
  21926. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21927. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21928. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21929. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21930. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21931. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21932. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21933. class AudioIODevice;
  21934. /**
  21935. One of these is passed to an AudioIODevice object to stream the audio data
  21936. in and out.
  21937. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21938. method on its own high-priority audio thread, when it needs to send or receive
  21939. the next block of data.
  21940. @see AudioIODevice, AudioDeviceManager
  21941. */
  21942. class JUCE_API AudioIODeviceCallback
  21943. {
  21944. public:
  21945. /** Destructor. */
  21946. virtual ~AudioIODeviceCallback() {}
  21947. /** Processes a block of incoming and outgoing audio data.
  21948. The subclass's implementation should use the incoming audio for whatever
  21949. purposes it needs to, and must fill all the output channels with the next
  21950. block of output data before returning.
  21951. The channel data is arranged with the same array indices as the channel name
  21952. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21953. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21954. associated channel, so remember to check for this.
  21955. @param inputChannelData a set of arrays containing the audio data for each
  21956. incoming channel - this data is valid until the function
  21957. returns. There will be one channel of data for each input
  21958. channel that was enabled when the audio device was opened
  21959. (see AudioIODevice::open())
  21960. @param numInputChannels the number of pointers to channel data in the
  21961. inputChannelData array.
  21962. @param outputChannelData a set of arrays which need to be filled with the data
  21963. that should be sent to each outgoing channel of the device.
  21964. There will be one channel of data for each output channel
  21965. that was enabled when the audio device was opened (see
  21966. AudioIODevice::open())
  21967. The initial contents of the array is undefined, so the
  21968. callback function must fill all the channels with zeros if
  21969. its output is silence. Failing to do this could cause quite
  21970. an unpleasant noise!
  21971. @param numOutputChannels the number of pointers to channel data in the
  21972. outputChannelData array.
  21973. @param numSamples the number of samples in each channel of the input and
  21974. output arrays. The number of samples will depend on the
  21975. audio device's buffer size and will usually remain constant,
  21976. although this isn't guaranteed, so make sure your code can
  21977. cope with reasonable changes in the buffer size from one
  21978. callback to the next.
  21979. */
  21980. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21981. int numInputChannels,
  21982. float** outputChannelData,
  21983. int numOutputChannels,
  21984. int numSamples) = 0;
  21985. /** Called to indicate that the device is about to start calling back.
  21986. This will be called just before the audio callbacks begin, either when this
  21987. callback has just been added to an audio device, or after the device has been
  21988. restarted because of a sample-rate or block-size change.
  21989. You can use this opportunity to find out the sample rate and block size
  21990. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21991. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21992. @param device the audio IO device that will be used to drive the callback.
  21993. Note that if you're going to store this this pointer, it is
  21994. only valid until the next time that audioDeviceStopped is called.
  21995. */
  21996. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21997. /** Called to indicate that the device has stopped.
  21998. */
  21999. virtual void audioDeviceStopped() = 0;
  22000. };
  22001. /**
  22002. Base class for an audio device with synchronised input and output channels.
  22003. Subclasses of this are used to implement different protocols such as DirectSound,
  22004. ASIO, CoreAudio, etc.
  22005. To create one of these, you'll need to use the AudioIODeviceType class - see the
  22006. documentation for that class for more info.
  22007. For an easier way of managing audio devices and their settings, have a look at the
  22008. AudioDeviceManager class.
  22009. @see AudioIODeviceType, AudioDeviceManager
  22010. */
  22011. class JUCE_API AudioIODevice
  22012. {
  22013. public:
  22014. /** Destructor. */
  22015. virtual ~AudioIODevice();
  22016. /** Returns the device's name, (as set in the constructor). */
  22017. const String& getName() const throw() { return name; }
  22018. /** Returns the type of the device.
  22019. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  22020. */
  22021. const String& getTypeName() const throw() { return typeName; }
  22022. /** Returns the names of all the available output channels on this device.
  22023. To find out which of these are currently in use, call getActiveOutputChannels().
  22024. */
  22025. virtual const StringArray getOutputChannelNames() = 0;
  22026. /** Returns the names of all the available input channels on this device.
  22027. To find out which of these are currently in use, call getActiveInputChannels().
  22028. */
  22029. virtual const StringArray getInputChannelNames() = 0;
  22030. /** Returns the number of sample-rates this device supports.
  22031. To find out which rates are available on this device, use this method to
  22032. find out how many there are, and getSampleRate() to get the rates.
  22033. @see getSampleRate
  22034. */
  22035. virtual int getNumSampleRates() = 0;
  22036. /** Returns one of the sample-rates this device supports.
  22037. To find out which rates are available on this device, use getNumSampleRates() to
  22038. find out how many there are, and getSampleRate() to get the individual rates.
  22039. The sample rate is set by the open() method.
  22040. (Note that for DirectSound some rates might not work, depending on combinations
  22041. of i/o channels that are being opened).
  22042. @see getNumSampleRates
  22043. */
  22044. virtual double getSampleRate (int index) = 0;
  22045. /** Returns the number of sizes of buffer that are available.
  22046. @see getBufferSizeSamples, getDefaultBufferSize
  22047. */
  22048. virtual int getNumBufferSizesAvailable() = 0;
  22049. /** Returns one of the possible buffer-sizes.
  22050. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  22051. @returns a number of samples
  22052. @see getNumBufferSizesAvailable, getDefaultBufferSize
  22053. */
  22054. virtual int getBufferSizeSamples (int index) = 0;
  22055. /** Returns the default buffer-size to use.
  22056. @returns a number of samples
  22057. @see getNumBufferSizesAvailable, getBufferSizeSamples
  22058. */
  22059. virtual int getDefaultBufferSize() = 0;
  22060. /** Tries to open the device ready to play.
  22061. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  22062. input channel should be enabled
  22063. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  22064. output channel should be enabled
  22065. @param sampleRate the sample rate to try to use - to find out which rates are
  22066. available, see getNumSampleRates() and getSampleRate()
  22067. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  22068. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  22069. @returns an error description if there's a problem, or an empty string if it succeeds in
  22070. opening the device
  22071. @see close
  22072. */
  22073. virtual const String open (const BitArray& inputChannels,
  22074. const BitArray& outputChannels,
  22075. double sampleRate,
  22076. int bufferSizeSamples) = 0;
  22077. /** Closes and releases the device if it's open. */
  22078. virtual void close() = 0;
  22079. /** Returns true if the device is still open.
  22080. A device might spontaneously close itself if something goes wrong, so this checks if
  22081. it's still open.
  22082. */
  22083. virtual bool isOpen() = 0;
  22084. /** Starts the device actually playing.
  22085. This must be called after the device has been opened.
  22086. @param callback the callback to use for streaming the data.
  22087. @see AudioIODeviceCallback, open
  22088. */
  22089. virtual void start (AudioIODeviceCallback* callback) = 0;
  22090. /** Stops the device playing.
  22091. Once a device has been started, this will stop it. Any pending calls to the
  22092. callback class will be flushed before this method returns.
  22093. */
  22094. virtual void stop() = 0;
  22095. /** Returns true if the device is still calling back.
  22096. The device might mysteriously stop, so this checks whether it's
  22097. still playing.
  22098. */
  22099. virtual bool isPlaying() = 0;
  22100. /** Returns the last error that happened if anything went wrong. */
  22101. virtual const String getLastError() = 0;
  22102. /** Returns the buffer size that the device is currently using.
  22103. If the device isn't actually open, this value doesn't really mean much.
  22104. */
  22105. virtual int getCurrentBufferSizeSamples() = 0;
  22106. /** Returns the sample rate that the device is currently using.
  22107. If the device isn't actually open, this value doesn't really mean much.
  22108. */
  22109. virtual double getCurrentSampleRate() = 0;
  22110. /** Returns the device's current physical bit-depth.
  22111. If the device isn't actually open, this value doesn't really mean much.
  22112. */
  22113. virtual int getCurrentBitDepth() = 0;
  22114. /** Returns a mask showing which of the available output channels are currently
  22115. enabled.
  22116. @see getOutputChannelNames
  22117. */
  22118. virtual const BitArray getActiveOutputChannels() const = 0;
  22119. /** Returns a mask showing which of the available input channels are currently
  22120. enabled.
  22121. @see getInputChannelNames
  22122. */
  22123. virtual const BitArray getActiveInputChannels() const = 0;
  22124. /** Returns the device's output latency.
  22125. This is the delay in samples between a callback getting a block of data, and
  22126. that data actually getting played.
  22127. */
  22128. virtual int getOutputLatencyInSamples() = 0;
  22129. /** Returns the device's input latency.
  22130. This is the delay in samples between some audio actually arriving at the soundcard,
  22131. and the callback getting passed this block of data.
  22132. */
  22133. virtual int getInputLatencyInSamples() = 0;
  22134. /** True if this device can show a pop-up control panel for editing its settings.
  22135. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22136. to display it.
  22137. */
  22138. virtual bool hasControlPanel() const;
  22139. /** Shows a device-specific control panel if there is one.
  22140. This should only be called for devices which return true from hasControlPanel().
  22141. */
  22142. virtual bool showControlPanel();
  22143. protected:
  22144. /** Creates a device, setting its name and type member variables. */
  22145. AudioIODevice (const String& deviceName,
  22146. const String& typeName);
  22147. /** @internal */
  22148. String name, typeName;
  22149. };
  22150. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22151. /********* End of inlined file: juce_AudioIODevice.h *********/
  22152. /**
  22153. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  22154. To use one of these, just make it the callback used by your AudioIODevice, and
  22155. give it a processor to use by calling setProcessor().
  22156. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  22157. input to send both streams through the processor.
  22158. @see AudioProcessor, AudioProcessorGraph
  22159. */
  22160. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  22161. public MidiInputCallback
  22162. {
  22163. public:
  22164. /**
  22165. */
  22166. AudioProcessorPlayer();
  22167. /** Destructor. */
  22168. virtual ~AudioProcessorPlayer();
  22169. /** Sets the processor that should be played.
  22170. The processor that is passed in will not be deleted or owned by this object.
  22171. To stop anything playing, pass in 0 to this method.
  22172. */
  22173. void setProcessor (AudioProcessor* const processorToPlay);
  22174. /** Returns the current audio processor that is being played.
  22175. */
  22176. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  22177. /** Returns a midi message collector that you can pass midi messages to if you
  22178. want them to be injected into the midi stream that is being sent to the
  22179. processor.
  22180. */
  22181. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  22182. /** @internal */
  22183. void audioDeviceIOCallback (const float** inputChannelData,
  22184. int totalNumInputChannels,
  22185. float** outputChannelData,
  22186. int totalNumOutputChannels,
  22187. int numSamples);
  22188. /** @internal */
  22189. void audioDeviceAboutToStart (AudioIODevice* device);
  22190. /** @internal */
  22191. void audioDeviceStopped();
  22192. /** @internal */
  22193. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22194. juce_UseDebuggingNewOperator
  22195. private:
  22196. AudioProcessor* processor;
  22197. CriticalSection lock;
  22198. double sampleRate;
  22199. int blockSize;
  22200. bool isPrepared;
  22201. int numInputChans, numOutputChans;
  22202. float* channels [128];
  22203. AudioSampleBuffer tempBuffer;
  22204. MidiBuffer incomingMidi;
  22205. MidiMessageCollector messageCollector;
  22206. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22207. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22208. };
  22209. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22210. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22211. #endif
  22212. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22213. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22214. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22215. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22216. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22217. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22218. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22219. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22220. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22221. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22222. class EditableProperty;
  22223. /**
  22224. A base class for a component that goes in a PropertyPanel and displays one of
  22225. an item's properties.
  22226. Subclasses of this are used to display a property in various forms, e.g. a
  22227. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22228. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22229. A subclass must implement the refresh() method which will be called to tell the
  22230. component to update itself, and is also responsible for calling this it when the
  22231. item that it refers to is changed.
  22232. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22233. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22234. */
  22235. class JUCE_API PropertyComponent : public Component
  22236. {
  22237. public:
  22238. /** Creates a PropertyComponent.
  22239. @param propertyName the name is stored as this component's name, and is
  22240. used as the name displayed next to this component in
  22241. a property panel
  22242. @param preferredHeight the height that the component should be given - some
  22243. items may need to be larger than a normal row height.
  22244. This value can also be set if a subclass changes the
  22245. preferredHeight member variable.
  22246. */
  22247. PropertyComponent (const String& propertyName,
  22248. const int preferredHeight = 25);
  22249. /** Destructor. */
  22250. ~PropertyComponent();
  22251. /** Returns this item's preferred height.
  22252. This value is specified either in the constructor or by a subclass changing the
  22253. preferredHeight member variable.
  22254. */
  22255. int getPreferredHeight() const throw() { return preferredHeight; }
  22256. /** Updates the property component if the item it refers to has changed.
  22257. A subclass must implement this method, and other objects may call it to
  22258. force it to refresh itself.
  22259. The subclass should be economical in the amount of work is done, so for
  22260. example it should check whether it really needs to do a repaint rather than
  22261. just doing one every time this method is called, as it may be called when
  22262. the value being displayed hasn't actually changed.
  22263. */
  22264. virtual void refresh() = 0;
  22265. /** The default paint method fills the background and draws a label for the
  22266. item's name.
  22267. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22268. */
  22269. void paint (Graphics& g);
  22270. /** The default resize method positions any child component to the right of this
  22271. one, based on the look and feel's default label size.
  22272. */
  22273. void resized();
  22274. /** By default, this just repaints the component. */
  22275. void enablementChanged();
  22276. juce_UseDebuggingNewOperator
  22277. protected:
  22278. /** Used by the PropertyPanel to determine how high this component needs to be.
  22279. A subclass can update this value in its constructor but shouldn't alter it later
  22280. as changes won't necessarily be picked up.
  22281. */
  22282. int preferredHeight;
  22283. };
  22284. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22285. /********* End of inlined file: juce_PropertyComponent.h *********/
  22286. /********* Start of inlined file: juce_Viewport.h *********/
  22287. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22288. #define __JUCE_VIEWPORT_JUCEHEADER__
  22289. /********* Start of inlined file: juce_ScrollBar.h *********/
  22290. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22291. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22292. /********* Start of inlined file: juce_Button.h *********/
  22293. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22294. #define __JUCE_BUTTON_JUCEHEADER__
  22295. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22296. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22297. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22298. /********* Start of inlined file: juce_TooltipClient.h *********/
  22299. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22300. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22301. /**
  22302. Components that want to use pop-up tooltips should implement this interface.
  22303. A TooltipWindow will wait for the mouse to hover over a component that
  22304. implements the TooltipClient interface, and when it finds one, it will display
  22305. the tooltip returned by its getTooltip() method.
  22306. @see TooltipWindow, SettableTooltipClient
  22307. */
  22308. class JUCE_API TooltipClient
  22309. {
  22310. public:
  22311. /** Destructor. */
  22312. virtual ~TooltipClient() {}
  22313. /** Returns the string that this object wants to show as its tooltip. */
  22314. virtual const String getTooltip() = 0;
  22315. };
  22316. /**
  22317. An implementation of TooltipClient that stores the tooltip string and a method
  22318. for changing it.
  22319. This makes it easy to add a tooltip to a custom component, by simply adding this
  22320. as a base class and calling setTooltip().
  22321. Many of the Juce widgets already use this as a base class to implement their
  22322. tooltips.
  22323. @see TooltipClient, TooltipWindow
  22324. */
  22325. class JUCE_API SettableTooltipClient : public TooltipClient
  22326. {
  22327. public:
  22328. /** Destructor. */
  22329. virtual ~SettableTooltipClient() {}
  22330. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22331. virtual const String getTooltip() { return tooltipString; }
  22332. juce_UseDebuggingNewOperator
  22333. protected:
  22334. String tooltipString;
  22335. };
  22336. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22337. /********* End of inlined file: juce_TooltipClient.h *********/
  22338. /**
  22339. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22340. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22341. object.
  22342. The TooltipWindow object will then stay invisible, waiting until the mouse
  22343. hovers for the specified length of time - it will then see if it's currently
  22344. over a component which implements the TooltipClient interface, and if so,
  22345. it will make itself visible to show the tooltip in the appropriate place.
  22346. @see TooltipClient, SettableTooltipClient
  22347. */
  22348. class JUCE_API TooltipWindow : public Component,
  22349. private Timer
  22350. {
  22351. public:
  22352. /** Creates a tooltip window.
  22353. Make sure your app only creates one instance of this class, otherwise you'll
  22354. get multiple overlaid tooltips appearing. The window will initially be invisible
  22355. and will make itself visible when it needs to display a tip.
  22356. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22357. methods.
  22358. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22359. otherwise the tooltip will be added to the given parent
  22360. component.
  22361. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22362. before a tooltip will be shown
  22363. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22364. */
  22365. TooltipWindow (Component* parentComponent = 0,
  22366. const int millisecondsBeforeTipAppears = 700);
  22367. /** Destructor. */
  22368. ~TooltipWindow();
  22369. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22370. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22371. methods.
  22372. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22373. */
  22374. enum ColourIds
  22375. {
  22376. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22377. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22378. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22379. };
  22380. juce_UseDebuggingNewOperator
  22381. private:
  22382. const int millisecondsBeforeTipAppears;
  22383. int mouseX, mouseY, mouseClicks;
  22384. unsigned int lastCompChangeTime, lastHideTime;
  22385. Component* lastComponentUnderMouse;
  22386. bool changedCompsSinceShown;
  22387. String tipShowing, lastTipUnderMouse;
  22388. void paint (Graphics& g);
  22389. void mouseEnter (const MouseEvent& e);
  22390. void timerCallback();
  22391. static const String getTipFor (Component* const c);
  22392. void showFor (Component* const c, const String& tip);
  22393. void hide();
  22394. TooltipWindow (const TooltipWindow&);
  22395. const TooltipWindow& operator= (const TooltipWindow&);
  22396. };
  22397. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22398. /********* End of inlined file: juce_TooltipWindow.h *********/
  22399. class Button;
  22400. /**
  22401. Used to receive callbacks when a button is clicked.
  22402. @see Button::addButtonListener, Button::removeButtonListener
  22403. */
  22404. class JUCE_API ButtonListener
  22405. {
  22406. public:
  22407. /** Destructor. */
  22408. virtual ~ButtonListener() {}
  22409. /** Called when the button is clicked. */
  22410. virtual void buttonClicked (Button* button) = 0;
  22411. /** Called when the button's state changes. */
  22412. virtual void buttonStateChanged (Button*) {}
  22413. };
  22414. /**
  22415. A base class for buttons.
  22416. This contains all the logic for button behaviours such as enabling/disabling,
  22417. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22418. and radio groups, etc.
  22419. @see TextButton, DrawableButton, ToggleButton
  22420. */
  22421. class JUCE_API Button : public Component,
  22422. public SettableTooltipClient,
  22423. public ApplicationCommandManagerListener,
  22424. private KeyListener
  22425. {
  22426. protected:
  22427. /** Creates a button.
  22428. @param buttonName the text to put in the button (the component's name is also
  22429. initially set to this string, but these can be changed later
  22430. using the setName() and setButtonText() methods)
  22431. */
  22432. Button (const String& buttonName);
  22433. public:
  22434. /** Destructor. */
  22435. virtual ~Button();
  22436. /** Changes the button's text.
  22437. @see getButtonText
  22438. */
  22439. void setButtonText (const String& newText) throw();
  22440. /** Returns the text displayed in the button.
  22441. @see setButtonText
  22442. */
  22443. const String getButtonText() const throw() { return text; }
  22444. /** Returns true if the button is currently being held down by the mouse.
  22445. @see isOver
  22446. */
  22447. bool isDown() const throw();
  22448. /** Returns true if the mouse is currently over the button.
  22449. This will be also be true if the mouse is being held down.
  22450. @see isDown
  22451. */
  22452. bool isOver() const throw();
  22453. /** A button has an on/off state associated with it, and this changes that.
  22454. By default buttons are 'off' and for simple buttons that you click to perform
  22455. an action you won't change this. Toggle buttons, however will want to
  22456. change their state when turned on or off.
  22457. @param shouldBeOn whether to set the button's toggle state to be on or
  22458. off. If it's a member of a button group, this will
  22459. always try to turn it on, and to turn off any other
  22460. buttons in the group
  22461. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22462. the button will be repainted but no notification will
  22463. be sent
  22464. @see getToggleState, setRadioGroupId
  22465. */
  22466. void setToggleState (const bool shouldBeOn,
  22467. const bool sendChangeNotification);
  22468. /** Returns true if the button in 'on'.
  22469. By default buttons are 'off' and for simple buttons that you click to perform
  22470. an action you won't change this. Toggle buttons, however will want to
  22471. change their state when turned on or off.
  22472. @see setToggleState
  22473. */
  22474. bool getToggleState() const throw() { return isOn; }
  22475. /** This tells the button to automatically flip the toggle state when
  22476. the button is clicked.
  22477. If set to true, then before the clicked() callback occurs, the toggle-state
  22478. of the button is flipped.
  22479. */
  22480. void setClickingTogglesState (const bool shouldToggle) throw();
  22481. /** Returns true if this button is set to be an automatic toggle-button.
  22482. This returns the last value that was passed to setClickingTogglesState().
  22483. */
  22484. bool getClickingTogglesState() const throw();
  22485. /** Enables the button to act as a member of a mutually-exclusive group
  22486. of 'radio buttons'.
  22487. If the group ID is set to a non-zero number, then this button will
  22488. act as part of a group of buttons with the same ID, only one of
  22489. which can be 'on' at the same time. Note that when it's part of
  22490. a group, clicking a toggle-button that's 'on' won't turn it off.
  22491. To find other buttons with the same ID, this button will search through
  22492. its sibling components for ToggleButtons, so all the buttons for a
  22493. particular group must be placed inside the same parent component.
  22494. Set the group ID back to zero if you want it to act as a normal toggle
  22495. button again.
  22496. @see getRadioGroupId
  22497. */
  22498. void setRadioGroupId (const int newGroupId);
  22499. /** Returns the ID of the group to which this button belongs.
  22500. (See setRadioGroupId() for an explanation of this).
  22501. */
  22502. int getRadioGroupId() const throw() { return radioGroupId; }
  22503. /** Registers a listener to receive events when this button's state changes.
  22504. If the listener is already registered, this will not register it again.
  22505. @see removeButtonListener
  22506. */
  22507. void addButtonListener (ButtonListener* const newListener) throw();
  22508. /** Removes a previously-registered button listener
  22509. @see addButtonListener
  22510. */
  22511. void removeButtonListener (ButtonListener* const listener) throw();
  22512. /** Causes the button to act as if it's been clicked.
  22513. This will asynchronously make the button draw itself going down and up, and
  22514. will then call back the clicked() method as if mouse was clicked on it.
  22515. @see clicked
  22516. */
  22517. virtual void triggerClick();
  22518. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22519. When the button is pressed, it will use the given manager to trigger the
  22520. command ID.
  22521. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22522. before this button is. To disable the command triggering, call this method and
  22523. pass 0 for the parameters.
  22524. If generateTooltip is true, then the button's tooltip will be automatically
  22525. generated based on the name of this command and its current shortcut key.
  22526. @see addShortcut, getCommandID
  22527. */
  22528. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22529. const int commandID,
  22530. const bool generateTooltip);
  22531. /** Returns the command ID that was set by setCommandToTrigger().
  22532. */
  22533. int getCommandID() const throw() { return commandID; }
  22534. /** Assigns a shortcut key to trigger the button.
  22535. The button registers itself with its top-level parent component for keypresses.
  22536. Note that a different way of linking buttons to keypresses is by using the
  22537. setKeyPressToTrigger() method to invoke a command - the difference being that
  22538. setting a shortcut allows the button to be temporarily linked to a keypress
  22539. only while it's on-screen.
  22540. @see clearShortcuts
  22541. */
  22542. void addShortcut (const KeyPress& key);
  22543. /** Removes all key shortcuts that had been set for this button.
  22544. @see addShortcut
  22545. */
  22546. void clearShortcuts();
  22547. /** Returns true if the given keypress is a shortcut for this button.
  22548. @see addShortcut
  22549. */
  22550. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22551. /** Sets an auto-repeat speed for the button when it is held down.
  22552. (Auto-repeat is disabled by default).
  22553. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22554. triggering the next click. If this is zero, auto-repeat
  22555. is disabled
  22556. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22557. triggered
  22558. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22559. get faster, the longer the button is held down, up to the
  22560. minimum interval specified here
  22561. */
  22562. void setRepeatSpeed (const int initialDelayInMillisecs,
  22563. const int repeatDelayInMillisecs,
  22564. const int minimumDelayInMillisecs = -1) throw();
  22565. /** Sets whether the button click should happen when the mouse is pressed or released.
  22566. By default the button is only considered to have been clicked when the mouse is
  22567. released, but setting this to true will make it call the clicked() method as soon
  22568. as the button is pressed.
  22569. This is useful if the button is being used to show a pop-up menu, as it allows
  22570. the click to be used as a drag onto the menu.
  22571. */
  22572. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22573. /** Returns the number of milliseconds since the last time the button
  22574. went into the 'down' state.
  22575. */
  22576. uint32 getMillisecondsSinceButtonDown() const throw();
  22577. /** (overridden from Component to do special stuff). */
  22578. void setVisible (bool shouldBeVisible);
  22579. /** Sets the tooltip for this button.
  22580. @see TooltipClient, TooltipWindow
  22581. */
  22582. void setTooltip (const String& newTooltip);
  22583. // (implementation of the TooltipClient method)
  22584. const String getTooltip();
  22585. /** A combination of these flags are used by setConnectedEdges().
  22586. */
  22587. enum ConnectedEdgeFlags
  22588. {
  22589. ConnectedOnLeft = 1,
  22590. ConnectedOnRight = 2,
  22591. ConnectedOnTop = 4,
  22592. ConnectedOnBottom = 8
  22593. };
  22594. /** Hints about which edges of the button might be connected to adjoining buttons.
  22595. The value passed in is a bitwise combination of any of the values in the
  22596. ConnectedEdgeFlags enum.
  22597. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22598. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22599. without rounded corners on the edges that connect. It's only a hint, so the
  22600. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22601. button.
  22602. */
  22603. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22604. /** Returns the set of flags passed into setConnectedEdges(). */
  22605. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22606. /** Indicates whether the button adjoins another one on its left edge.
  22607. @see setConnectedEdges
  22608. */
  22609. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22610. /** Indicates whether the button adjoins another one on its right edge.
  22611. @see setConnectedEdges
  22612. */
  22613. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22614. /** Indicates whether the button adjoins another one on its top edge.
  22615. @see setConnectedEdges
  22616. */
  22617. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22618. /** Indicates whether the button adjoins another one on its bottom edge.
  22619. @see setConnectedEdges
  22620. */
  22621. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22622. /** Used by setState(). */
  22623. enum ButtonState
  22624. {
  22625. buttonNormal,
  22626. buttonOver,
  22627. buttonDown
  22628. };
  22629. /** Can be used to force the button into a particular state.
  22630. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22631. from happening.
  22632. The state that you set here will only last until it is automatically changed when the mouse
  22633. enters or exits the button, or the mouse-button is pressed or released.
  22634. */
  22635. void setState (const ButtonState newState);
  22636. juce_UseDebuggingNewOperator
  22637. protected:
  22638. /** This method is called when the button has been clicked.
  22639. Subclasses can override this to perform whatever they actions they need
  22640. to do.
  22641. Alternatively, a ButtonListener can be added to the button, and these listeners
  22642. will be called when the click occurs.
  22643. @see triggerClick
  22644. */
  22645. virtual void clicked();
  22646. /** This method is called when the button has been clicked.
  22647. By default it just calls clicked(), but you might want to override it to handle
  22648. things like clicking when a modifier key is pressed, etc.
  22649. @see ModifierKeys
  22650. */
  22651. virtual void clicked (const ModifierKeys& modifiers);
  22652. /** Subclasses should override this to actually paint the button's contents.
  22653. It's better to use this than the paint method, because it gives you information
  22654. about the over/down state of the button.
  22655. @param g the graphics context to use
  22656. @param isMouseOverButton true if the button is either in the 'over' or
  22657. 'down' state
  22658. @param isButtonDown true if the button should be drawn in the 'down' position
  22659. */
  22660. virtual void paintButton (Graphics& g,
  22661. bool isMouseOverButton,
  22662. bool isButtonDown) = 0;
  22663. /** Called when the button's up/down/over state changes.
  22664. Subclasses can override this if they need to do something special when the button
  22665. goes up or down.
  22666. @see isDown, isOver
  22667. */
  22668. virtual void buttonStateChanged();
  22669. /** @internal */
  22670. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22671. /** @internal */
  22672. void handleCommandMessage (int commandId);
  22673. /** @internal */
  22674. void mouseEnter (const MouseEvent& e);
  22675. /** @internal */
  22676. void mouseExit (const MouseEvent& e);
  22677. /** @internal */
  22678. void mouseDown (const MouseEvent& e);
  22679. /** @internal */
  22680. void mouseDrag (const MouseEvent& e);
  22681. /** @internal */
  22682. void mouseUp (const MouseEvent& e);
  22683. /** @internal */
  22684. bool keyPressed (const KeyPress& key);
  22685. /** @internal */
  22686. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22687. /** @internal */
  22688. bool keyStateChanged (Component* originatingComponent);
  22689. /** @internal */
  22690. void paint (Graphics& g);
  22691. /** @internal */
  22692. void parentHierarchyChanged();
  22693. /** @internal */
  22694. void focusGained (FocusChangeType cause);
  22695. /** @internal */
  22696. void focusLost (FocusChangeType cause);
  22697. /** @internal */
  22698. void enablementChanged();
  22699. /** @internal */
  22700. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22701. /** @internal */
  22702. void applicationCommandListChanged();
  22703. private:
  22704. Array <KeyPress> shortcuts;
  22705. Component* keySource;
  22706. String text;
  22707. SortedSet <void*> buttonListeners;
  22708. friend class InternalButtonRepeatTimer;
  22709. Timer* repeatTimer;
  22710. uint32 buttonPressTime, lastTimeCallbackTime;
  22711. ApplicationCommandManager* commandManagerToUse;
  22712. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22713. int radioGroupId, commandID, connectedEdgeFlags;
  22714. ButtonState buttonState;
  22715. bool isOn : 1;
  22716. bool clickTogglesState : 1;
  22717. bool needsToRelease : 1;
  22718. bool needsRepainting : 1;
  22719. bool isKeyDown : 1;
  22720. bool triggerOnMouseDown : 1;
  22721. bool generateTooltip : 1;
  22722. void repeatTimerCallback() throw();
  22723. Timer& getRepeatTimer() throw();
  22724. ButtonState updateState (const MouseEvent* const e) throw();
  22725. bool isShortcutPressed() const throw();
  22726. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22727. void flashButtonState() throw();
  22728. void sendClickMessage (const ModifierKeys& modifiers);
  22729. void sendStateMessage();
  22730. Button (const Button&);
  22731. const Button& operator= (const Button&);
  22732. };
  22733. #endif // __JUCE_BUTTON_JUCEHEADER__
  22734. /********* End of inlined file: juce_Button.h *********/
  22735. class ScrollBar;
  22736. /**
  22737. A class for receiving events from a ScrollBar.
  22738. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22739. method, and it will be called when the bar's position changes.
  22740. @see ScrollBar::addListener, ScrollBar::removeListener
  22741. */
  22742. class JUCE_API ScrollBarListener
  22743. {
  22744. public:
  22745. /** Destructor. */
  22746. virtual ~ScrollBarListener() {}
  22747. /** Called when a ScrollBar is moved.
  22748. @param scrollBarThatHasMoved the bar that has moved
  22749. @param newRangeStart the new range start of this bar
  22750. */
  22751. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22752. const double newRangeStart) = 0;
  22753. };
  22754. /**
  22755. A scrollbar component.
  22756. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22757. sets the range of values it can represent. Then you can use setCurrentRange() to
  22758. change the position and size of the scrollbar's 'thumb'.
  22759. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22760. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22761. they moved it to.
  22762. The scrollbar will adjust its own visibility according to whether its thumb size
  22763. allows it to actually be scrolled.
  22764. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22765. instead of handling a scrollbar directly.
  22766. @see ScrollBarListener
  22767. */
  22768. class JUCE_API ScrollBar : public Component,
  22769. public AsyncUpdater,
  22770. private Timer
  22771. {
  22772. public:
  22773. /** Creates a Scrollbar.
  22774. @param isVertical whether it should be a vertical or horizontal bar
  22775. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22776. */
  22777. ScrollBar (const bool isVertical,
  22778. const bool buttonsAreVisible = true);
  22779. /** Destructor. */
  22780. ~ScrollBar();
  22781. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22782. bool isVertical() const throw() { return vertical; }
  22783. /** Changes the scrollbar's direction.
  22784. You'll also need to resize the bar appropriately - this just changes its internal
  22785. layout.
  22786. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22787. */
  22788. void setOrientation (const bool shouldBeVertical) throw();
  22789. /** Shows or hides the scrollbar's buttons. */
  22790. void setButtonVisibility (const bool buttonsAreVisible);
  22791. /** Tells the scrollbar whether to make itself invisible when not needed.
  22792. The default behaviour is for a scrollbar to become invisible when the thumb
  22793. fills the whole of its range (i.e. when it can't be moved). Setting this
  22794. value to false forces the bar to always be visible.
  22795. */
  22796. void setAutoHide (const bool shouldHideWhenFullRange);
  22797. /** Sets the minimum and maximum values that the bar will move between.
  22798. The bar's thumb will always be constrained so that the top of the thumb
  22799. will be >= minimum, and the bottom of the thumb <= maximum.
  22800. @see setCurrentRange
  22801. */
  22802. void setRangeLimits (const double minimum,
  22803. const double maximum) throw();
  22804. /** Returns the lower value that the thumb can be set to.
  22805. This is the value set by setRangeLimits().
  22806. */
  22807. double getMinimumRangeLimit() const throw() { return minimum; }
  22808. /** Returns the upper value that the thumb can be set to.
  22809. This is the value set by setRangeLimits().
  22810. */
  22811. double getMaximumRangeLimit() const throw() { return maximum; }
  22812. /** Changes the position of the scrollbar's 'thumb'.
  22813. This sets both the position and size of the thumb - to just set the position without
  22814. changing the size, you can use setCurrentRangeStart().
  22815. If this method call actually changes the scrollbar's position, it will trigger an
  22816. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22817. are registered.
  22818. @param newStart the top (or left) of the thumb, in the range
  22819. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22820. value is beyond these limits, it will be clipped.
  22821. @param newSize the size of the thumb, such that
  22822. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22823. size is beyond these limits, it will be clipped.
  22824. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22825. */
  22826. void setCurrentRange (double newStart,
  22827. double newSize) throw();
  22828. /** Moves the bar's thumb position.
  22829. This will move the thumb position without changing the thumb size. Note
  22830. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22831. If this method call actually changes the scrollbar's position, it will trigger an
  22832. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22833. are registered.
  22834. @see setCurrentRange
  22835. */
  22836. void setCurrentRangeStart (double newStart) throw();
  22837. /** Returns the position of the top of the thumb.
  22838. @see setCurrentRangeStart
  22839. */
  22840. double getCurrentRangeStart() const throw() { return rangeStart; }
  22841. /** Returns the current size of the thumb.
  22842. @see setCurrentRange
  22843. */
  22844. double getCurrentRangeSize() const throw() { return rangeSize; }
  22845. /** Sets the amount by which the up and down buttons will move the bar.
  22846. The value here is in terms of the total range, and is added or subtracted
  22847. from the thumb position when the user clicks an up/down (or left/right) button.
  22848. */
  22849. void setSingleStepSize (const double newSingleStepSize) throw();
  22850. /** Moves the scrollbar by a number of single-steps.
  22851. This will move the bar by a multiple of its single-step interval (as
  22852. specified using the setSingleStepSize() method).
  22853. A positive value here will move the bar down or to the right, a negative
  22854. value moves it up or to the left.
  22855. */
  22856. void moveScrollbarInSteps (const int howManySteps) throw();
  22857. /** Moves the scroll bar up or down in pages.
  22858. This will move the bar by a multiple of its current thumb size, effectively
  22859. doing a page-up or down.
  22860. A positive value here will move the bar down or to the right, a negative
  22861. value moves it up or to the left.
  22862. */
  22863. void moveScrollbarInPages (const int howManyPages) throw();
  22864. /** Scrolls to the top (or left).
  22865. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22866. */
  22867. void scrollToTop() throw();
  22868. /** Scrolls to the bottom (or right).
  22869. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22870. */
  22871. void scrollToBottom() throw();
  22872. /** Changes the delay before the up and down buttons autorepeat when they are held
  22873. down.
  22874. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22875. @see Button::setRepeatSpeed
  22876. */
  22877. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22878. const int repeatDelayInMillisecs,
  22879. const int minimumDelayInMillisecs = -1) throw();
  22880. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22881. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22882. methods.
  22883. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22884. */
  22885. enum ColourIds
  22886. {
  22887. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22888. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22889. 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. */
  22890. };
  22891. /** Registers a listener that will be called when the scrollbar is moved. */
  22892. void addListener (ScrollBarListener* const listener) throw();
  22893. /** Deregisters a previously-registered listener. */
  22894. void removeListener (ScrollBarListener* const listener) throw();
  22895. /** @internal */
  22896. bool keyPressed (const KeyPress& key);
  22897. /** @internal */
  22898. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22899. /** @internal */
  22900. void lookAndFeelChanged();
  22901. /** @internal */
  22902. void handleAsyncUpdate();
  22903. /** @internal */
  22904. void mouseDown (const MouseEvent& e);
  22905. /** @internal */
  22906. void mouseDrag (const MouseEvent& e);
  22907. /** @internal */
  22908. void mouseUp (const MouseEvent& e);
  22909. /** @internal */
  22910. void paint (Graphics& g);
  22911. /** @internal */
  22912. void resized();
  22913. juce_UseDebuggingNewOperator
  22914. private:
  22915. double minimum, maximum;
  22916. double rangeStart, rangeSize;
  22917. double singleStepSize, dragStartRange;
  22918. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22919. int dragStartMousePos, lastMousePos;
  22920. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22921. bool vertical, isDraggingThumb, alwaysVisible;
  22922. Button* upButton;
  22923. Button* downButton;
  22924. SortedSet <void*> listeners;
  22925. void updateThumbPosition() throw();
  22926. void timerCallback();
  22927. ScrollBar (const ScrollBar&);
  22928. const ScrollBar& operator= (const ScrollBar&);
  22929. };
  22930. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22931. /********* End of inlined file: juce_ScrollBar.h *********/
  22932. /**
  22933. A Viewport is used to contain a larger child component, and allows the child
  22934. to be automatically scrolled around.
  22935. To use a Viewport, just create one and set the component that goes inside it
  22936. using the setViewedComponent() method. When the child component changes size,
  22937. the Viewport will adjust its scrollbars accordingly.
  22938. A subclass of the viewport can be created which will receive calls to its
  22939. visibleAreaChanged() method when the subcomponent changes position or size.
  22940. */
  22941. class JUCE_API Viewport : public Component,
  22942. private ComponentListener,
  22943. private ScrollBarListener
  22944. {
  22945. public:
  22946. /** Creates a Viewport.
  22947. The viewport is initially empty - use the setViewedComponent() method to
  22948. add a child component for it to manage.
  22949. */
  22950. Viewport (const String& componentName = String::empty);
  22951. /** Destructor. */
  22952. ~Viewport();
  22953. /** Sets the component that this viewport will contain and scroll around.
  22954. This will add the given component to this Viewport and position it at
  22955. (0, 0).
  22956. (Don't add or remove any child components directly using the normal
  22957. Component::addChildComponent() methods).
  22958. @param newViewedComponent the component to add to this viewport (this pointer
  22959. may be null). The component passed in will be deleted
  22960. by the Viewport when it's no longer needed
  22961. @see getViewedComponent
  22962. */
  22963. void setViewedComponent (Component* const newViewedComponent);
  22964. /** Returns the component that's currently being used inside the Viewport.
  22965. @see setViewedComponent
  22966. */
  22967. Component* getViewedComponent() const throw() { return contentComp; }
  22968. /** Changes the position of the viewed component.
  22969. The inner component will be moved so that the pixel at the top left of
  22970. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22971. within the inner component.
  22972. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22973. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22974. */
  22975. void setViewPosition (const int xPixelsOffset,
  22976. const int yPixelsOffset);
  22977. /** Changes the view position as a proportion of the distance it can move.
  22978. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22979. visible area in the top-left, and (1, 1) would put it as far down and
  22980. to the right as it's possible to go whilst keeping the child component
  22981. on-screen.
  22982. */
  22983. void setViewPositionProportionately (const double proportionX,
  22984. const double proportionY);
  22985. /** Returns the position within the child component of the top-left of its visible area.
  22986. @see getViewWidth, setViewPosition
  22987. */
  22988. int getViewPositionX() const throw() { return lastVX; }
  22989. /** Returns the position within the child component of the top-left of its visible area.
  22990. @see getViewHeight, setViewPosition
  22991. */
  22992. int getViewPositionY() const throw() { return lastVY; }
  22993. /** Returns the width of the visible area of the child component.
  22994. This may be less than the width of this Viewport if there's a vertical scrollbar
  22995. or if the child component is itself smaller.
  22996. */
  22997. int getViewWidth() const throw() { return lastVW; }
  22998. /** Returns the height of the visible area of the child component.
  22999. This may be less than the height of this Viewport if there's a horizontal scrollbar
  23000. or if the child component is itself smaller.
  23001. */
  23002. int getViewHeight() const throw() { return lastVH; }
  23003. /** Returns the width available within this component for the contents.
  23004. This will be the width of the viewport component minus the width of a
  23005. vertical scrollbar (if visible).
  23006. */
  23007. int getMaximumVisibleWidth() const throw();
  23008. /** Returns the height available within this component for the contents.
  23009. This will be the height of the viewport component minus the space taken up
  23010. by a horizontal scrollbar (if visible).
  23011. */
  23012. int getMaximumVisibleHeight() const throw();
  23013. /** Callback method that is called when the visible area changes.
  23014. This will be called when the visible area is moved either be scrolling or
  23015. by calls to setViewPosition(), etc.
  23016. */
  23017. virtual void visibleAreaChanged (int visibleX, int visibleY,
  23018. int visibleW, int visibleH);
  23019. /** Turns scrollbars on or off.
  23020. If set to false, the scrollbars won't ever appear. When true (the default)
  23021. they will appear only when needed.
  23022. */
  23023. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  23024. const bool showHorizontalScrollbarIfNeeded);
  23025. /** True if the vertical scrollbar is enabled.
  23026. @see setScrollBarsShown
  23027. */
  23028. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  23029. /** True if the horizontal scrollbar is enabled.
  23030. @see setScrollBarsShown
  23031. */
  23032. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  23033. /** Changes the width of the scrollbars.
  23034. If this isn't specified, the default width from the LookAndFeel class will be used.
  23035. @see LookAndFeel::getDefaultScrollbarWidth
  23036. */
  23037. void setScrollBarThickness (const int thickness);
  23038. /** Returns the thickness of the scrollbars.
  23039. @see setScrollBarThickness
  23040. */
  23041. int getScrollBarThickness() const throw();
  23042. /** Changes the distance that a single-step click on a scrollbar button
  23043. will move the viewport.
  23044. */
  23045. void setSingleStepSizes (const int stepX, const int stepY);
  23046. /** Shows or hides the buttons on any scrollbars that are used.
  23047. @see ScrollBar::setButtonVisibility
  23048. */
  23049. void setScrollBarButtonVisibility (const bool buttonsVisible);
  23050. /** Returns a pointer to the scrollbar component being used.
  23051. Handy if you need to customise the bar somehow.
  23052. */
  23053. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  23054. /** Returns a pointer to the scrollbar component being used.
  23055. Handy if you need to customise the bar somehow.
  23056. */
  23057. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  23058. juce_UseDebuggingNewOperator
  23059. /** @internal */
  23060. void resized();
  23061. /** @internal */
  23062. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  23063. /** @internal */
  23064. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23065. /** @internal */
  23066. bool keyPressed (const KeyPress& key);
  23067. /** @internal */
  23068. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  23069. /** @internal */
  23070. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23071. private:
  23072. Component* contentComp;
  23073. int lastVX, lastVY, lastVW, lastVH;
  23074. int scrollBarThickness;
  23075. int singleStepX, singleStepY;
  23076. bool showHScrollbar, showVScrollbar;
  23077. Component* contentHolder;
  23078. ScrollBar* verticalScrollBar;
  23079. ScrollBar* horizontalScrollBar;
  23080. void updateVisibleRegion();
  23081. Viewport (const Viewport&);
  23082. const Viewport& operator= (const Viewport&);
  23083. };
  23084. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  23085. /********* End of inlined file: juce_Viewport.h *********/
  23086. /**
  23087. A panel that holds a list of PropertyComponent objects.
  23088. This panel displays a list of PropertyComponents, and allows them to be organised
  23089. into collapsible sections.
  23090. To use, simply create one of these and add your properties to it with addProperties()
  23091. or addSection().
  23092. @see PropertyComponent
  23093. */
  23094. class JUCE_API PropertyPanel : public Component
  23095. {
  23096. public:
  23097. /** Creates an empty property panel. */
  23098. PropertyPanel();
  23099. /** Destructor. */
  23100. ~PropertyPanel();
  23101. /** Deletes all property components from the panel.
  23102. */
  23103. void clear();
  23104. /** Adds a set of properties to the panel.
  23105. The components in the list will be owned by this object and will be automatically
  23106. deleted later on when no longer needed.
  23107. These properties are added without them being inside a named section. If you
  23108. want them to be kept together in a collapsible section, use addSection() instead.
  23109. */
  23110. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  23111. /** Adds a set of properties to the panel.
  23112. These properties are added at the bottom of the list, under a section heading with
  23113. a plus/minus button that allows it to be opened and closed.
  23114. The components in the list will be owned by this object and will be automatically
  23115. deleted later on when no longer needed.
  23116. To add properies without them being in a section, use addProperties().
  23117. */
  23118. void addSection (const String& sectionTitle,
  23119. const Array <PropertyComponent*>& newPropertyComponents,
  23120. const bool shouldSectionInitiallyBeOpen = true);
  23121. /** Calls the refresh() method of all PropertyComponents in the panel */
  23122. void refreshAll() const;
  23123. /** Returns a list of all the names of sections in the panel.
  23124. These are the sections that have been added with addSection().
  23125. */
  23126. const StringArray getSectionNames() const;
  23127. /** Returns true if the section at this index is currently open.
  23128. The index is from 0 up to the number of items returned by getSectionNames().
  23129. */
  23130. bool isSectionOpen (const int sectionIndex) const;
  23131. /** Opens or closes one of the sections.
  23132. The index is from 0 up to the number of items returned by getSectionNames().
  23133. */
  23134. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  23135. /** Enables or disables one of the sections.
  23136. The index is from 0 up to the number of items returned by getSectionNames().
  23137. */
  23138. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  23139. /** Saves the current state of open/closed sections so it can be restored later.
  23140. The caller is responsible for deleting the object that is returned.
  23141. To restore this state, use restoreOpennessState().
  23142. @see restoreOpennessState
  23143. */
  23144. XmlElement* getOpennessState() const;
  23145. /** Restores a previously saved arrangement of open/closed sections.
  23146. This will try to restore a snapshot of the panel's state that was created by
  23147. the getOpennessState() method. If any of the sections named in the original
  23148. XML aren't present, they will be ignored.
  23149. @see getOpennessState
  23150. */
  23151. void restoreOpennessState (const XmlElement& newState);
  23152. /** Sets a message to be displayed when there are no properties in the panel.
  23153. The default message is "nothing selected".
  23154. */
  23155. void setMessageWhenEmpty (const String& newMessage);
  23156. /** Returns the message that is displayed when there are no properties.
  23157. @see setMessageWhenEmpty
  23158. */
  23159. const String& getMessageWhenEmpty() const throw();
  23160. /** @internal */
  23161. void paint (Graphics& g);
  23162. /** @internal */
  23163. void resized();
  23164. juce_UseDebuggingNewOperator
  23165. private:
  23166. Viewport* viewport;
  23167. Component* propertyHolderComponent;
  23168. String messageWhenEmpty;
  23169. void updatePropHolderLayout() const;
  23170. void updatePropHolderLayout (const int width) const;
  23171. };
  23172. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  23173. /********* End of inlined file: juce_PropertyPanel.h *********/
  23174. /**
  23175. A type of UI component that displays the parameters of an AudioProcessor as
  23176. a simple list of sliders.
  23177. This can be used for showing an editor for a processor that doesn't supply
  23178. its own custom editor.
  23179. @see AudioProcessor
  23180. */
  23181. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  23182. {
  23183. public:
  23184. GenericAudioProcessorEditor (AudioProcessor* const owner);
  23185. ~GenericAudioProcessorEditor();
  23186. void paint (Graphics& g);
  23187. void resized();
  23188. juce_UseDebuggingNewOperator
  23189. private:
  23190. PropertyPanel* panel;
  23191. };
  23192. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23193. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23194. #endif
  23195. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23196. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23197. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23198. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23199. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23200. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23201. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23202. /********* Start of inlined file: juce_AudioSource.h *********/
  23203. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23204. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23205. /**
  23206. Used by AudioSource::getNextAudioBlock().
  23207. */
  23208. struct JUCE_API AudioSourceChannelInfo
  23209. {
  23210. /** The destination buffer to fill with audio data.
  23211. When the AudioSource::getNextAudioBlock() method is called, the active section
  23212. of this buffer should be filled with whatever output the source produces.
  23213. Only the samples specified by the startSample and numSamples members of this structure
  23214. should be affected by the call.
  23215. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23216. method can be treated as the input if the source is performing some kind of filter operation,
  23217. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23218. a handy way of doing this.
  23219. The number of channels in the buffer could be anything, so the AudioSource
  23220. must cope with this in whatever way is appropriate for its function.
  23221. */
  23222. AudioSampleBuffer* buffer;
  23223. /** The first sample in the buffer from which the callback is expected
  23224. to write data. */
  23225. int startSample;
  23226. /** The number of samples in the buffer which the callback is expected to
  23227. fill with data. */
  23228. int numSamples;
  23229. /** Convenient method to clear the buffer if the source is not producing any data. */
  23230. void clearActiveBufferRegion() const
  23231. {
  23232. if (buffer != 0)
  23233. buffer->clear (startSample, numSamples);
  23234. }
  23235. };
  23236. /**
  23237. Base class for objects that can produce a continuous stream of audio.
  23238. @see AudioFormatReaderSource, ResamplingAudioSource
  23239. */
  23240. class JUCE_API AudioSource
  23241. {
  23242. protected:
  23243. /** Creates an AudioSource. */
  23244. AudioSource() throw() {}
  23245. public:
  23246. /** Destructor. */
  23247. virtual ~AudioSource() {}
  23248. /** Tells the source to prepare for playing.
  23249. The source can use this opportunity to initialise anything it needs to.
  23250. Note that this method could be called more than once in succession without
  23251. a matching call to releaseResources(), so make sure your code is robust and
  23252. can handle that kind of situation.
  23253. @param samplesPerBlockExpected the number of samples that the source
  23254. will be expected to supply each time its
  23255. getNextAudioBlock() method is called. This
  23256. number may vary slightly, because it will be dependent
  23257. on audio hardware callbacks, and these aren't
  23258. guaranteed to always use a constant block size, so
  23259. the source should be able to cope with small variations.
  23260. @param sampleRate the sample rate that the output will be used at - this
  23261. is needed by sources such as tone generators.
  23262. @see releaseResources, getNextAudioBlock
  23263. */
  23264. virtual void prepareToPlay (int samplesPerBlockExpected,
  23265. double sampleRate) = 0;
  23266. /** Allows the source to release anything it no longer needs after playback has stopped.
  23267. This will be called when the source is no longer going to have its getNextAudioBlock()
  23268. method called, so it should release any spare memory, etc. that it might have
  23269. allocated during the prepareToPlay() call.
  23270. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23271. releaseResources(), and it may be called more than once in succession, so make sure your
  23272. code is robust and doesn't make any assumptions about when it will be called.
  23273. @see prepareToPlay, getNextAudioBlock
  23274. */
  23275. virtual void releaseResources() = 0;
  23276. /** Called repeatedly to fetch subsequent blocks of audio data.
  23277. After calling the prepareToPlay() method, this callback will be made each
  23278. time the audio playback hardware (or whatever other destination the audio
  23279. data is going to) needs another block of data.
  23280. It will generally be called on a high-priority system thread, or possibly even
  23281. an interrupt, so be careful not to do too much work here, as that will cause
  23282. audio glitches!
  23283. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23284. */
  23285. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23286. };
  23287. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23288. /********* End of inlined file: juce_AudioSource.h *********/
  23289. /**
  23290. A type of AudioSource which can be repositioned.
  23291. The basic AudioSource just streams continuously with no idea of a current
  23292. time or length, so the PositionableAudioSource is used for a finite stream
  23293. that has a current read position.
  23294. @see AudioSource, AudioTransportSource
  23295. */
  23296. class JUCE_API PositionableAudioSource : public AudioSource
  23297. {
  23298. protected:
  23299. /** Creates the PositionableAudioSource. */
  23300. PositionableAudioSource() throw() {}
  23301. public:
  23302. /** Destructor */
  23303. ~PositionableAudioSource() {}
  23304. /** Tells the stream to move to a new position.
  23305. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23306. should return samples from this position.
  23307. Note that this may be called on a different thread to getNextAudioBlock(),
  23308. so the subclass should make sure it's synchronised.
  23309. */
  23310. virtual void setNextReadPosition (int newPosition) = 0;
  23311. /** Returns the position from which the next block will be returned.
  23312. @see setNextReadPosition
  23313. */
  23314. virtual int getNextReadPosition() const = 0;
  23315. /** Returns the total length of the stream (in samples). */
  23316. virtual int getTotalLength() const = 0;
  23317. /** Returns true if this source is actually playing in a loop. */
  23318. virtual bool isLooping() const = 0;
  23319. };
  23320. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23321. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23322. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23323. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23324. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23325. class AudioFormat;
  23326. /**
  23327. Reads samples from an audio file stream.
  23328. A subclass that reads a specific type of audio format will be created by
  23329. an AudioFormat object.
  23330. @see AudioFormat, AudioFormatWriter
  23331. */
  23332. class JUCE_API AudioFormatReader
  23333. {
  23334. protected:
  23335. /** Creates an AudioFormatReader object.
  23336. @param sourceStream the stream to read from - this will be deleted
  23337. by this object when it is no longer needed. (Some
  23338. specialised readers might not use this parameter and
  23339. can leave it as 0).
  23340. @param formatName the description that will be returned by the getFormatName()
  23341. method
  23342. */
  23343. AudioFormatReader (InputStream* const sourceStream,
  23344. const String& formatName);
  23345. public:
  23346. /** Destructor. */
  23347. virtual ~AudioFormatReader();
  23348. /** Returns a description of what type of format this is.
  23349. E.g. "AIFF"
  23350. */
  23351. const String getFormatName() const throw() { return formatName; }
  23352. /** Reads samples from the stream.
  23353. @param destSamples an array of buffers into which the sample data for each
  23354. channel will be written.
  23355. If the format is fixed-point, each channel will be written
  23356. as an array of 32-bit signed integers using the full
  23357. range -0x80000000 to 0x7fffffff, regardless of the source's
  23358. bit-depth. If it is a floating-point format, you should cast
  23359. the resulting array to a (float**) to get the values (in the
  23360. range -1.0 to 1.0 or beyond)
  23361. If the format is stereo, then destSamples[0] is the left channel
  23362. data, and destSamples[1] is the right channel.
  23363. The array passed in should be zero-terminated, and it's ok to
  23364. pass in an array with a different number of channels than
  23365. the number in the stream, so if you pass in an array with only
  23366. one channel and the stream is stereo, the reader will
  23367. put a merged sum of the stereo channels into the single
  23368. destination channel.
  23369. @param startSample the offset into the audio stream from which the samples
  23370. should be read, as a number of samples from the start of the
  23371. stream. It's ok for this to be beyond the start or end of the
  23372. available data - any samples that can't be read will be padded
  23373. with zeros.
  23374. @param numSamples the number of samples to read. If this is greater than the
  23375. number of samples available, the result will be padded with
  23376. zeros
  23377. @returns true if the operation succeeded, false if there was an error. Note
  23378. that reading sections of data beyond the extent of the stream isn't an
  23379. error - the reader should just return zeros for these regions
  23380. @see readMaxLevels
  23381. */
  23382. virtual bool read (int** destSamples,
  23383. int64 startSample,
  23384. int numSamples) = 0;
  23385. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23386. This will read a block of samples from the stream, and measure the
  23387. highest and lowest sample levels from the channels in that section, returning
  23388. these as normalised floating-point levels.
  23389. @param startSample the offset into the audio stream to start reading from. It's
  23390. ok for this to be beyond the start or end of the stream.
  23391. @param numSamples how many samples to read
  23392. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23393. @param highestLeft on return, this is the highest absolute sample from the left channel
  23394. @param lowestRight on return, this is the lowest absolute sample from the right
  23395. channel (if there is one)
  23396. @param highestRight on return, this is the highest absolute sample from the right
  23397. channel (if there is one)
  23398. @see read
  23399. */
  23400. virtual void readMaxLevels (int64 startSample,
  23401. int64 numSamples,
  23402. float& lowestLeft,
  23403. float& highestLeft,
  23404. float& lowestRight,
  23405. float& highestRight);
  23406. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23407. This will read from the source, either forwards or backwards between two sample
  23408. positions, until it finds a sample whose magnitude lies between two specified levels.
  23409. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23410. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23411. points when you're searching for a continuous range of samples
  23412. @param startSample the first sample to look at
  23413. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23414. the search will go backwards
  23415. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23416. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23417. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23418. of this many consecutive samples, all of which lie
  23419. within the target range. When it finds such a sequence,
  23420. it returns the position of the first in-range sample
  23421. it found (i.e. the earliest one if scanning forwards, the
  23422. latest one if scanning backwards)
  23423. */
  23424. int64 searchForLevel (int64 startSample,
  23425. int64 numSamplesToSearch,
  23426. const double magnitudeRangeMinimum,
  23427. const double magnitudeRangeMaximum,
  23428. const int minimumConsecutiveSamples);
  23429. /** The sample-rate of the stream. */
  23430. double sampleRate;
  23431. /** The number of bits per sample, e.g. 16, 24, 32. */
  23432. unsigned int bitsPerSample;
  23433. /** The total number of samples in the audio stream. */
  23434. int64 lengthInSamples;
  23435. /** The total number of channels in the audio stream. */
  23436. unsigned int numChannels;
  23437. /** Indicates whether the data is floating-point or fixed. */
  23438. bool usesFloatingPointData;
  23439. /** A set of metadata values that the reader has pulled out of the stream.
  23440. Exactly what these values are depends on the format, so you can
  23441. check out the format implementation code to see what kind of stuff
  23442. they understand.
  23443. */
  23444. StringPairArray metadataValues;
  23445. /** The input stream, for use by subclasses. */
  23446. InputStream* input;
  23447. juce_UseDebuggingNewOperator
  23448. private:
  23449. String formatName;
  23450. AudioFormatReader (const AudioFormatReader&);
  23451. const AudioFormatReader& operator= (const AudioFormatReader&);
  23452. };
  23453. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23454. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23455. /**
  23456. A type of AudioSource that will read from an AudioFormatReader.
  23457. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23458. */
  23459. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23460. {
  23461. public:
  23462. /** Creates an AudioFormatReaderSource for a given reader.
  23463. @param sourceReader the reader to use as the data source
  23464. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23465. when this object is deleted; if false it will be
  23466. left up to the caller to manage its lifetime
  23467. */
  23468. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23469. const bool deleteReaderWhenThisIsDeleted);
  23470. /** Destructor. */
  23471. ~AudioFormatReaderSource();
  23472. /** Toggles loop-mode.
  23473. If set to true, it will continuously loop the input source. If false,
  23474. it will just emit silence after the source has finished.
  23475. @see isLooping
  23476. */
  23477. void setLooping (const bool shouldLoop) throw();
  23478. /** Returns whether loop-mode is turned on or not. */
  23479. bool isLooping() const { return looping; }
  23480. /** Returns the reader that's being used. */
  23481. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23482. /** Implementation of the AudioSource method. */
  23483. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23484. /** Implementation of the AudioSource method. */
  23485. void releaseResources();
  23486. /** Implementation of the AudioSource method. */
  23487. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23488. /** Implements the PositionableAudioSource method. */
  23489. void setNextReadPosition (int newPosition);
  23490. /** Implements the PositionableAudioSource method. */
  23491. int getNextReadPosition() const;
  23492. /** Implements the PositionableAudioSource method. */
  23493. int getTotalLength() const;
  23494. juce_UseDebuggingNewOperator
  23495. private:
  23496. AudioFormatReader* reader;
  23497. bool deleteReader;
  23498. int volatile nextPlayPos;
  23499. bool volatile looping;
  23500. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23501. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23502. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23503. };
  23504. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23505. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23506. #endif
  23507. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23508. #endif
  23509. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23510. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23511. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23512. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23513. /**
  23514. Wrapper class to continuously stream audio from an audio source to an
  23515. AudioIODevice.
  23516. This object acts as an AudioIODeviceCallback, so can be attached to an
  23517. output device, and will stream audio from an AudioSource.
  23518. */
  23519. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23520. {
  23521. public:
  23522. /** Creates an empty AudioSourcePlayer. */
  23523. AudioSourcePlayer();
  23524. /** Destructor.
  23525. Make sure this object isn't still being used by an AudioIODevice before
  23526. deleting it!
  23527. */
  23528. virtual ~AudioSourcePlayer();
  23529. /** Changes the current audio source to play from.
  23530. If the source passed in is already being used, this method will do nothing.
  23531. If the source is not null, its prepareToPlay() method will be called
  23532. before it starts being used for playback.
  23533. If there's another source currently playing, its releaseResources() method
  23534. will be called after it has been swapped for the new one.
  23535. @param newSource the new source to use - this will NOT be deleted
  23536. by this object when no longer needed, so it's the
  23537. caller's responsibility to manage it.
  23538. */
  23539. void setSource (AudioSource* newSource);
  23540. /** Returns the source that's playing.
  23541. May return 0 if there's no source.
  23542. */
  23543. AudioSource* getCurrentSource() const throw() { return source; }
  23544. /** Sets a gain to apply to the audio data. */
  23545. void setGain (const float newGain) throw();
  23546. /** Implementation of the AudioIODeviceCallback method. */
  23547. void audioDeviceIOCallback (const float** inputChannelData,
  23548. int totalNumInputChannels,
  23549. float** outputChannelData,
  23550. int totalNumOutputChannels,
  23551. int numSamples);
  23552. /** Implementation of the AudioIODeviceCallback method. */
  23553. void audioDeviceAboutToStart (AudioIODevice* device);
  23554. /** Implementation of the AudioIODeviceCallback method. */
  23555. void audioDeviceStopped();
  23556. juce_UseDebuggingNewOperator
  23557. private:
  23558. CriticalSection readLock;
  23559. AudioSource* source;
  23560. double sampleRate;
  23561. int bufferSize;
  23562. float* channels [128];
  23563. float* outputChans [128];
  23564. const float* inputChans [128];
  23565. AudioSampleBuffer tempBuffer;
  23566. float lastGain, gain;
  23567. AudioSourcePlayer (const AudioSourcePlayer&);
  23568. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23569. };
  23570. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23571. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23572. #endif
  23573. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23574. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23575. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23576. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23577. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23578. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23579. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23580. /**
  23581. An AudioSource which takes another source as input, and buffers it using a thread.
  23582. Create this as a wrapper around another thread, and it will read-ahead with
  23583. a background thread to smooth out playback. You can either create one of these
  23584. directly, or use it indirectly using an AudioTransportSource.
  23585. @see PositionableAudioSource, AudioTransportSource
  23586. */
  23587. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23588. {
  23589. public:
  23590. /** Creates a BufferingAudioSource.
  23591. @param source the input source to read from
  23592. @param deleteSourceWhenDeleted if true, then the input source object will
  23593. be deleted when this object is deleted
  23594. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23595. */
  23596. BufferingAudioSource (PositionableAudioSource* source,
  23597. const bool deleteSourceWhenDeleted,
  23598. int numberOfSamplesToBuffer);
  23599. /** Destructor.
  23600. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23601. flag was set in the constructor.
  23602. */
  23603. ~BufferingAudioSource();
  23604. /** Implementation of the AudioSource method. */
  23605. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23606. /** Implementation of the AudioSource method. */
  23607. void releaseResources();
  23608. /** Implementation of the AudioSource method. */
  23609. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23610. /** Implements the PositionableAudioSource method. */
  23611. void setNextReadPosition (int newPosition);
  23612. /** Implements the PositionableAudioSource method. */
  23613. int getNextReadPosition() const;
  23614. /** Implements the PositionableAudioSource method. */
  23615. int getTotalLength() const { return source->getTotalLength(); }
  23616. /** Implements the PositionableAudioSource method. */
  23617. bool isLooping() const { return source->isLooping(); }
  23618. juce_UseDebuggingNewOperator
  23619. private:
  23620. PositionableAudioSource* source;
  23621. bool deleteSourceWhenDeleted;
  23622. int numberOfSamplesToBuffer;
  23623. AudioSampleBuffer buffer;
  23624. CriticalSection bufferStartPosLock;
  23625. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23626. bool wasSourceLooping;
  23627. double volatile sampleRate;
  23628. friend class SharedBufferingAudioSourceThread;
  23629. bool readNextBufferChunk();
  23630. void readBufferSection (int start, int length, int bufferOffset);
  23631. BufferingAudioSource (const BufferingAudioSource&);
  23632. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23633. };
  23634. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23635. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23636. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23637. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23638. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23639. /**
  23640. A type of AudioSource that takes an input source and changes its sample rate.
  23641. @see AudioSource
  23642. */
  23643. class JUCE_API ResamplingAudioSource : public AudioSource
  23644. {
  23645. public:
  23646. /** Creates a ResamplingAudioSource for a given input source.
  23647. @param inputSource the input source to read from
  23648. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23649. this object is deleted
  23650. */
  23651. ResamplingAudioSource (AudioSource* const inputSource,
  23652. const bool deleteInputWhenDeleted);
  23653. /** Destructor. */
  23654. ~ResamplingAudioSource();
  23655. /** Changes the resampling ratio.
  23656. (This value can be changed at any time, even while the source is running).
  23657. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23658. values will speed it up; lower values will slow it
  23659. down. The ratio must be greater than 0
  23660. */
  23661. void setResamplingRatio (const double samplesInPerOutputSample);
  23662. /** Returns the current resampling ratio.
  23663. This is the value that was set by setResamplingRatio().
  23664. */
  23665. double getResamplingRatio() const throw() { return ratio; }
  23666. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23667. void releaseResources();
  23668. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23669. juce_UseDebuggingNewOperator
  23670. private:
  23671. AudioSource* const input;
  23672. const bool deleteInputWhenDeleted;
  23673. double ratio, lastRatio;
  23674. AudioSampleBuffer buffer;
  23675. int bufferPos, sampsInBuffer;
  23676. double subSampleOffset;
  23677. double coefficients[6];
  23678. CriticalSection ratioLock;
  23679. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23680. void createLowPass (const double proportionalRate);
  23681. struct FilterState
  23682. {
  23683. double x1, x2, y1, y2;
  23684. };
  23685. FilterState filterStates[2];
  23686. void resetFilters();
  23687. void applyFilter (float* samples, int num, FilterState& fs);
  23688. ResamplingAudioSource (const ResamplingAudioSource&);
  23689. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23690. };
  23691. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23692. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23693. /**
  23694. An AudioSource that takes a PositionableAudioSource and allows it to be
  23695. played, stopped, started, etc.
  23696. This can also be told use a buffer and background thread to read ahead, and
  23697. if can correct for different sample-rates.
  23698. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23699. to control playback of an audio file.
  23700. @see AudioSource, AudioSourcePlayer
  23701. */
  23702. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23703. public ChangeBroadcaster
  23704. {
  23705. public:
  23706. /** Creates an AudioTransportSource.
  23707. After creating one of these, use the setSource() method to select an input source.
  23708. */
  23709. AudioTransportSource();
  23710. /** Destructor. */
  23711. ~AudioTransportSource();
  23712. /** Sets the reader that is being used as the input source.
  23713. This will stop playback, reset the position to 0 and change to the new reader.
  23714. The source passed in will not be deleted by this object, so must be managed by
  23715. the caller.
  23716. @param newSource the new input source to use. This may be zero
  23717. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23718. is zero, no reading ahead will be done; if it's
  23719. greater than zero, a BufferingAudioSource will be used
  23720. to do the reading-ahead
  23721. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23722. rate of the source, and playback will be sample-rate
  23723. adjusted to maintain playback at the correct pitch. If
  23724. this is 0, no sample-rate adjustment will be performed
  23725. */
  23726. void setSource (PositionableAudioSource* const newSource,
  23727. int readAheadBufferSize = 0,
  23728. double sourceSampleRateToCorrectFor = 0.0);
  23729. /** Changes the current playback position in the source stream.
  23730. The next time the getNextAudioBlock() method is called, this
  23731. is the time from which it'll read data.
  23732. @see getPosition
  23733. */
  23734. void setPosition (double newPosition);
  23735. /** Returns the position that the next data block will be read from
  23736. This is a time in seconds.
  23737. */
  23738. double getCurrentPosition() const;
  23739. /** Returns true if the player has stopped because its input stream ran out of data.
  23740. */
  23741. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23742. /** Starts playing (if a source has been selected).
  23743. If it starts playing, this will send a message to any ChangeListeners
  23744. that are registered with this object.
  23745. */
  23746. void start();
  23747. /** Stops playing.
  23748. If it's actually playing, this will send a message to any ChangeListeners
  23749. that are registered with this object.
  23750. */
  23751. void stop();
  23752. /** Returns true if it's currently playing. */
  23753. bool isPlaying() const throw() { return playing; }
  23754. /** Changes the gain to apply to the output.
  23755. @param newGain a factor by which to multiply the outgoing samples,
  23756. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23757. */
  23758. void setGain (const float newGain) throw();
  23759. /** Returns the current gain setting.
  23760. @see setGain
  23761. */
  23762. float getGain() const throw() { return gain; }
  23763. /** Implementation of the AudioSource method. */
  23764. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23765. /** Implementation of the AudioSource method. */
  23766. void releaseResources();
  23767. /** Implementation of the AudioSource method. */
  23768. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23769. /** Implements the PositionableAudioSource method. */
  23770. void setNextReadPosition (int newPosition);
  23771. /** Implements the PositionableAudioSource method. */
  23772. int getNextReadPosition() const;
  23773. /** Implements the PositionableAudioSource method. */
  23774. int getTotalLength() const;
  23775. /** Implements the PositionableAudioSource method. */
  23776. bool isLooping() const;
  23777. juce_UseDebuggingNewOperator
  23778. private:
  23779. PositionableAudioSource* source;
  23780. ResamplingAudioSource* resamplerSource;
  23781. BufferingAudioSource* bufferingSource;
  23782. PositionableAudioSource* positionableSource;
  23783. AudioSource* masterSource;
  23784. CriticalSection callbackLock;
  23785. float volatile gain, lastGain;
  23786. bool volatile playing, stopped;
  23787. double sampleRate, sourceSampleRate;
  23788. int blockSize, readAheadBufferSize;
  23789. bool isPrepared, inputStreamEOF;
  23790. AudioTransportSource (const AudioTransportSource&);
  23791. const AudioTransportSource& operator= (const AudioTransportSource&);
  23792. };
  23793. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23794. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23795. #endif
  23796. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23797. #endif
  23798. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23799. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23800. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23801. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23802. /**
  23803. An AudioSource that takes the audio from another source, and re-maps its
  23804. input and output channels to a different arrangement.
  23805. You can use this to increase or decrease the number of channels that an
  23806. audio source uses, or to re-order those channels.
  23807. Call the reset() method before using it to set up a default mapping, and then
  23808. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23809. create an appropriate mapping, otherwise no channels will be connected and
  23810. it'll produce silence.
  23811. @see AudioSource
  23812. */
  23813. class ChannelRemappingAudioSource : public AudioSource
  23814. {
  23815. public:
  23816. /** Creates a remapping source that will pass on audio from the given input.
  23817. @param source the input source to use. Make sure that this doesn't
  23818. get deleted before the ChannelRemappingAudioSource object
  23819. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23820. when this object is deleted, if false, the caller is
  23821. responsible for its deletion
  23822. */
  23823. ChannelRemappingAudioSource (AudioSource* const source,
  23824. const bool deleteSourceWhenDeleted);
  23825. /** Destructor. */
  23826. ~ChannelRemappingAudioSource();
  23827. /** Specifies a number of channels that this audio source must produce from its
  23828. getNextAudioBlock() callback.
  23829. */
  23830. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23831. /** Clears any mapped channels.
  23832. After this, no channels are mapped, so this object will produce silence. Create
  23833. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23834. */
  23835. void clearAllMappings() throw();
  23836. /** Creates an input channel mapping.
  23837. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23838. data will be sent to destChannelIndex of our input source.
  23839. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23840. source specified when this object was created).
  23841. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23842. during our getNextAudioBlock() callback
  23843. */
  23844. void setInputChannelMapping (const int destChannelIndex,
  23845. const int sourceChannelIndex) throw();
  23846. /** Creates an output channel mapping.
  23847. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23848. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23849. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23850. (i.e. the source specified when this object was created).
  23851. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23852. during our getNextAudioBlock() callback
  23853. */
  23854. void setOutputChannelMapping (const int sourceChannelIndex,
  23855. const int destChannelIndex) throw();
  23856. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23857. our input audio source.
  23858. */
  23859. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23860. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23861. source will be sent to.
  23862. */
  23863. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23864. /** Returns an XML object to encapsulate the state of the mappings.
  23865. @see restoreFromXml
  23866. */
  23867. XmlElement* createXml() const throw();
  23868. /** Restores the mappings from an XML object created by createXML().
  23869. @see createXml
  23870. */
  23871. void restoreFromXml (const XmlElement& e) throw();
  23872. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23873. void releaseResources();
  23874. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23875. juce_UseDebuggingNewOperator
  23876. private:
  23877. int requiredNumberOfChannels;
  23878. Array <int> remappedInputs, remappedOutputs;
  23879. AudioSource* const source;
  23880. const bool deleteSourceWhenDeleted;
  23881. AudioSampleBuffer buffer;
  23882. AudioSourceChannelInfo remappedInfo;
  23883. CriticalSection lock;
  23884. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23885. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23886. };
  23887. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23888. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23889. #endif
  23890. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23891. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23892. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23893. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23894. /**
  23895. An AudioSource that performs an IIR filter on another source.
  23896. */
  23897. class JUCE_API IIRFilterAudioSource : public AudioSource
  23898. {
  23899. public:
  23900. /** Creates a IIRFilterAudioSource for a given input source.
  23901. @param inputSource the input source to read from
  23902. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23903. this object is deleted
  23904. */
  23905. IIRFilterAudioSource (AudioSource* const inputSource,
  23906. const bool deleteInputWhenDeleted);
  23907. /** Destructor. */
  23908. ~IIRFilterAudioSource();
  23909. /** Changes the filter to use the same parameters as the one being passed in.
  23910. */
  23911. void setFilterParameters (const IIRFilter& newSettings);
  23912. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23913. void releaseResources();
  23914. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23915. juce_UseDebuggingNewOperator
  23916. private:
  23917. AudioSource* const input;
  23918. const bool deleteInputWhenDeleted;
  23919. OwnedArray <IIRFilter> iirFilters;
  23920. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23921. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23922. };
  23923. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23924. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23925. #endif
  23926. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23927. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23928. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23929. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23930. /**
  23931. An AudioSource that mixes together the output of a set of other AudioSources.
  23932. Input sources can be added and removed while the mixer is running as long as their
  23933. prepareToPlay() and releaseResources() methods are called before and after adding
  23934. them to the mixer.
  23935. */
  23936. class JUCE_API MixerAudioSource : public AudioSource
  23937. {
  23938. public:
  23939. /** Creates a MixerAudioSource.
  23940. */
  23941. MixerAudioSource();
  23942. /** Destructor. */
  23943. ~MixerAudioSource();
  23944. /** Adds an input source to the mixer.
  23945. If the mixer is running you'll need to make sure that the input source
  23946. is ready to play by calling its prepareToPlay() method before adding it.
  23947. If the mixer is stopped, then its input sources will be automatically
  23948. prepared when the mixer's prepareToPlay() method is called.
  23949. @param newInput the source to add to the mixer
  23950. @param deleteWhenRemoved if true, then this source will be deleted when
  23951. the mixer is deleted or when removeAllInputs() is
  23952. called (unless the source is previously removed
  23953. with the removeInputSource method)
  23954. */
  23955. void addInputSource (AudioSource* newInput,
  23956. const bool deleteWhenRemoved);
  23957. /** Removes an input source.
  23958. If the mixer is running, this will remove the source but not call its
  23959. releaseResources() method, so the caller might want to do this manually.
  23960. @param input the source to remove
  23961. @param deleteSource whether to delete this source after it's been removed
  23962. */
  23963. void removeInputSource (AudioSource* input,
  23964. const bool deleteSource);
  23965. /** Removes all the input sources.
  23966. If the mixer is running, this will remove the sources but not call their
  23967. releaseResources() method, so the caller might want to do this manually.
  23968. Any sources which were added with the deleteWhenRemoved flag set will be
  23969. deleted by this method.
  23970. */
  23971. void removeAllInputs();
  23972. /** Implementation of the AudioSource method.
  23973. This will call prepareToPlay() on all its input sources.
  23974. */
  23975. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23976. /** Implementation of the AudioSource method.
  23977. This will call releaseResources() on all its input sources.
  23978. */
  23979. void releaseResources();
  23980. /** Implementation of the AudioSource method. */
  23981. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23982. juce_UseDebuggingNewOperator
  23983. private:
  23984. VoidArray inputs;
  23985. BitArray inputsToDelete;
  23986. CriticalSection lock;
  23987. AudioSampleBuffer tempBuffer;
  23988. double currentSampleRate;
  23989. int bufferSizeExpected;
  23990. MixerAudioSource (const MixerAudioSource&);
  23991. const MixerAudioSource& operator= (const MixerAudioSource&);
  23992. };
  23993. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23994. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23995. #endif
  23996. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23997. #endif
  23998. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23999. #endif
  24000. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24001. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24002. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24003. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24004. /**
  24005. A simple AudioSource that generates a sine wave.
  24006. */
  24007. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24008. {
  24009. public:
  24010. /** Creates a ToneGeneratorAudioSource. */
  24011. ToneGeneratorAudioSource();
  24012. /** Destructor. */
  24013. ~ToneGeneratorAudioSource();
  24014. /** Sets the signal's amplitude. */
  24015. void setAmplitude (const float newAmplitude);
  24016. /** Sets the signal's frequency. */
  24017. void setFrequency (const double newFrequencyHz);
  24018. /** Implementation of the AudioSource method. */
  24019. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24020. /** Implementation of the AudioSource method. */
  24021. void releaseResources();
  24022. /** Implementation of the AudioSource method. */
  24023. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24024. juce_UseDebuggingNewOperator
  24025. private:
  24026. double frequency, sampleRate;
  24027. double currentPhase, phasePerSample;
  24028. float amplitude;
  24029. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24030. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24031. };
  24032. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24033. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24034. #endif
  24035. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24036. /********* Start of inlined file: juce_MidiOutput.h *********/
  24037. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24038. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24039. /**
  24040. Represents a midi output device.
  24041. To create one of these, use the static getDevices() method to find out what
  24042. outputs are available, then use the openDevice() method to try to open one.
  24043. @see MidiInput
  24044. */
  24045. class JUCE_API MidiOutput : private Thread
  24046. {
  24047. public:
  24048. /** Returns a list of the available midi output devices.
  24049. You can open one of the devices by passing its index into the
  24050. openDevice() method.
  24051. @see getDefaultDeviceIndex, openDevice
  24052. */
  24053. static const StringArray getDevices();
  24054. /** Returns the index of the default midi output device to use.
  24055. This refers to the index in the list returned by getDevices().
  24056. */
  24057. static int getDefaultDeviceIndex();
  24058. /** Tries to open one of the midi output devices.
  24059. This will return a MidiOutput object if it manages to open it. You can then
  24060. send messages to this device, and delete it when no longer needed.
  24061. If the device can't be opened, this will return a null pointer.
  24062. @param deviceIndex the index of a device from the list returned by getDevices()
  24063. @see getDevices
  24064. */
  24065. static MidiOutput* openDevice (int deviceIndex);
  24066. #if JUCE_LINUX || DOXYGEN
  24067. /** LINUX ONLY - This will try to create a new midi output device.
  24068. This will attempt to create a new midi output device that other apps can connect
  24069. to and use as their midi input.
  24070. Returns 0 if a device can't be created.
  24071. @param deviceName the name to use for the new device
  24072. */
  24073. static MidiOutput* createNewDevice (const String& deviceName);
  24074. #endif
  24075. /** Destructor. */
  24076. virtual ~MidiOutput();
  24077. /** Makes this device output a midi message.
  24078. @see MidiMessage
  24079. */
  24080. virtual void sendMessageNow (const MidiMessage& message);
  24081. /** Sends a midi reset to the device. */
  24082. virtual void reset();
  24083. /** Returns the current volume setting for this device. */
  24084. virtual bool getVolume (float& leftVol,
  24085. float& rightVol);
  24086. /** Changes the overall volume for this device. */
  24087. virtual void setVolume (float leftVol,
  24088. float rightVol);
  24089. /** This lets you supply a block of messages that will be sent out at some point
  24090. in the future.
  24091. The MidiOutput class has an internal thread that can send out timestamped
  24092. messages - this appends a set of messages to its internal buffer, ready for
  24093. sending.
  24094. This will only work if you've already started the thread with startBackgroundThread().
  24095. A time is supplied, at which the block of messages should be sent. This time uses
  24096. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24097. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24098. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24099. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24100. real time.
  24101. */
  24102. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24103. const double millisecondCounterToStartAt,
  24104. double samplesPerSecondForBuffer) throw();
  24105. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24106. */
  24107. virtual void clearAllPendingMessages() throw();
  24108. /** Starts up a background thread so that the device can send blocks of data.
  24109. Call this to get the device ready, before using sendBlockOfMessages().
  24110. */
  24111. virtual void startBackgroundThread() throw();
  24112. /** Stops the background thread, and clears any pending midi events.
  24113. @see startBackgroundThread
  24114. */
  24115. virtual void stopBackgroundThread() throw();
  24116. juce_UseDebuggingNewOperator
  24117. protected:
  24118. void* internal;
  24119. struct PendingMessage
  24120. {
  24121. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24122. MidiMessage message;
  24123. PendingMessage* next;
  24124. juce_UseDebuggingNewOperator
  24125. };
  24126. CriticalSection lock;
  24127. PendingMessage* firstMessage;
  24128. MidiOutput() throw();
  24129. MidiOutput (const MidiOutput&);
  24130. void run();
  24131. };
  24132. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24133. /********* End of inlined file: juce_MidiOutput.h *********/
  24134. #endif
  24135. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24136. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  24137. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24138. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24139. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  24140. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24141. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24142. class AudioDeviceManager;
  24143. class Component;
  24144. /**
  24145. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24146. To get a list of available audio driver types, use the createDeviceTypes()
  24147. method. Each of the objects returned can then be used to list the available
  24148. devices of that type. E.g.
  24149. @code
  24150. OwnedArray <AudioIODeviceType> types;
  24151. AudioIODeviceType::createDeviceTypes (types);
  24152. for (int i = 0; i < types.size(); ++i)
  24153. {
  24154. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24155. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24156. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24157. for (int j = 0; j < deviceNames.size(); ++j)
  24158. {
  24159. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24160. ...
  24161. }
  24162. }
  24163. @endcode
  24164. For an easier way of managing audio devices and their settings, have a look at the
  24165. AudioDeviceManager class.
  24166. @see AudioIODevice, AudioDeviceManager
  24167. */
  24168. class JUCE_API AudioIODeviceType
  24169. {
  24170. public:
  24171. /** Returns the name of this type of driver that this object manages.
  24172. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24173. */
  24174. const String& getTypeName() const throw() { return typeName; }
  24175. /** Refreshes the object's cached list of known devices.
  24176. This must be called at least once before calling getDeviceNames() or any of
  24177. the other device creation methods.
  24178. */
  24179. virtual void scanForDevices() = 0;
  24180. /** Returns the list of available devices of this type.
  24181. The scanForDevices() method must have been called to create this list.
  24182. @param wantInputNames only really used by DirectSound where devices are split up
  24183. into inputs and outputs, this indicates whether to use
  24184. the input or output name to refer to a pair of devices.
  24185. */
  24186. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  24187. /** Returns the name of the default device.
  24188. This will be one of the names from the getDeviceNames() list.
  24189. @param forInput if true, this means that a default input device should be
  24190. returned; if false, it should return the default output
  24191. */
  24192. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  24193. /** Returns the index of a given device in the list of device names.
  24194. If asInput is true, it shows the index in the inputs list, otherwise it
  24195. looks for it in the outputs list.
  24196. */
  24197. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  24198. /** Returns true if two different devices can be used for the input and output.
  24199. */
  24200. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24201. /** Creates one of the devices of this type.
  24202. The deviceName must be one of the strings returned by getDeviceNames(), and
  24203. scanForDevices() must have been called before this method is used.
  24204. */
  24205. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24206. const String& inputDeviceName) = 0;
  24207. struct DeviceSetupDetails
  24208. {
  24209. AudioDeviceManager* manager;
  24210. int minNumInputChannels, maxNumInputChannels;
  24211. int minNumOutputChannels, maxNumOutputChannels;
  24212. bool useStereoPairs;
  24213. };
  24214. /** Destructor. */
  24215. virtual ~AudioIODeviceType();
  24216. protected:
  24217. AudioIODeviceType (const tchar* const typeName);
  24218. private:
  24219. String typeName;
  24220. AudioIODeviceType (const AudioIODeviceType&);
  24221. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  24222. };
  24223. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24224. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  24225. /********* Start of inlined file: juce_ComboBox.h *********/
  24226. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24227. #define __JUCE_COMBOBOX_JUCEHEADER__
  24228. /********* Start of inlined file: juce_Label.h *********/
  24229. #ifndef __JUCE_LABEL_JUCEHEADER__
  24230. #define __JUCE_LABEL_JUCEHEADER__
  24231. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24232. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24233. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24234. /**
  24235. Object for monitoring a component, and later testing whether it's still valid.
  24236. Slightly obscure, this one, but it's used internally for making sure that
  24237. after some callbacks, a component hasn't been deleted. It's more reliable than
  24238. just using isValidComponent(), which can provide false-positives if a new
  24239. component is created at the same memory location as an old one.
  24240. */
  24241. class JUCE_API ComponentDeletionWatcher
  24242. {
  24243. public:
  24244. /** Creates a watcher for a given component.
  24245. The component must be valid at the time it's passed in.
  24246. */
  24247. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24248. /** Destructor. */
  24249. ~ComponentDeletionWatcher() throw();
  24250. /** Returns true if the component has been deleted since the time that this
  24251. object was created.
  24252. */
  24253. bool hasBeenDeleted() const throw();
  24254. /** Returns the component that's being watched, or null if it has been deleted. */
  24255. const Component* getComponent() const throw();
  24256. juce_UseDebuggingNewOperator
  24257. private:
  24258. const Component* const componentToWatch;
  24259. const uint32 componentUID;
  24260. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24261. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24262. };
  24263. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24264. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24265. /********* Start of inlined file: juce_TextEditor.h *********/
  24266. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24267. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24268. /********* Start of inlined file: juce_UndoManager.h *********/
  24269. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24270. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24271. /********* Start of inlined file: juce_UndoableAction.h *********/
  24272. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24273. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24274. /**
  24275. Used by the UndoManager class to store an action which can be done
  24276. and undone.
  24277. @see UndoManager
  24278. */
  24279. class JUCE_API UndoableAction
  24280. {
  24281. protected:
  24282. /** Creates an action. */
  24283. UndoableAction() throw() {}
  24284. public:
  24285. /** Destructor. */
  24286. virtual ~UndoableAction() {}
  24287. /** Overridden by a subclass to perform the action.
  24288. This method is called by the UndoManager, and shouldn't be used directly by
  24289. applications.
  24290. Be careful not to make any calls in a perform() method that could call
  24291. recursively back into the UndoManager::perform() method
  24292. @returns true if the action could be performed.
  24293. @see UndoManager::perform
  24294. */
  24295. virtual bool perform() = 0;
  24296. /** Overridden by a subclass to undo the action.
  24297. This method is called by the UndoManager, and shouldn't be used directly by
  24298. applications.
  24299. Be careful not to make any calls in an undo() method that could call
  24300. recursively back into the UndoManager::perform() method
  24301. @returns true if the action could be undone without any errors.
  24302. @see UndoManager::perform
  24303. */
  24304. virtual bool undo() = 0;
  24305. /** Returns a value to indicate how much memory this object takes up.
  24306. Because the UndoManager keeps a list of UndoableActions, this is used
  24307. to work out how much space each one will take up, so that the UndoManager
  24308. can work out how many to keep.
  24309. The default value returned here is 10 - units are arbitrary and
  24310. don't have to be accurate.
  24311. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24312. UndoManager::setMaxNumberOfStoredUnits
  24313. */
  24314. virtual int getSizeInUnits() { return 10; }
  24315. };
  24316. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24317. /********* End of inlined file: juce_UndoableAction.h *********/
  24318. /**
  24319. Manages a list of undo/redo commands.
  24320. An UndoManager object keeps a list of past actions and can use these actions
  24321. to move backwards and forwards through an undo history.
  24322. To use it, create subclasses of UndoableAction which perform all the
  24323. actions you need, then when you need to actually perform an action, create one
  24324. and pass it to the UndoManager's perform() method.
  24325. The manager also uses the concept of 'transactions' to group the actions
  24326. together - all actions performed between calls to beginNewTransaction() are
  24327. grouped together and are all undone/redone as a group.
  24328. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24329. when actions are performed or undone.
  24330. @see UndoableAction
  24331. */
  24332. class JUCE_API UndoManager : public ChangeBroadcaster
  24333. {
  24334. public:
  24335. /** Creates an UndoManager.
  24336. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24337. to indicate how much storage it takes up
  24338. (UndoableAction::getSizeInUnits()), so this
  24339. lets you specify the maximum total number of
  24340. units that the undomanager is allowed to
  24341. keep in memory before letting the older actions
  24342. drop off the end of the list.
  24343. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24344. that will be kept, even if this involves exceeding
  24345. the amount of space specified in maxNumberOfUnitsToKeep
  24346. */
  24347. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24348. const int minimumTransactionsToKeep = 30);
  24349. /** Destructor. */
  24350. ~UndoManager();
  24351. /** Deletes all stored actions in the list. */
  24352. void clearUndoHistory();
  24353. /** Returns the current amount of space to use for storing UndoableAction objects.
  24354. @see setMaxNumberOfStoredUnits
  24355. */
  24356. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24357. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24358. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24359. to indicate how much storage it takes up
  24360. (UndoableAction::getSizeInUnits()), so this
  24361. lets you specify the maximum total number of
  24362. units that the undomanager is allowed to
  24363. keep in memory before letting the older actions
  24364. drop off the end of the list.
  24365. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24366. that will be kept, even if this involves exceeding
  24367. the amount of space specified in maxNumberOfUnitsToKeep
  24368. @see getNumberOfUnitsTakenUpByStoredCommands
  24369. */
  24370. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24371. const int minimumTransactionsToKeep);
  24372. /** Performs an action and adds it to the undo history list.
  24373. @param action the action to perform - this will be deleted by the UndoManager
  24374. when no longer needed
  24375. @param actionName if this string is non-empty, the current transaction will be
  24376. given this name; if it's empty, the current transaction name will
  24377. be left unchanged. See setCurrentTransactionName()
  24378. @returns true if the command succeeds - see UndoableAction::perform
  24379. @see beginNewTransaction
  24380. */
  24381. bool perform (UndoableAction* const action,
  24382. const String& actionName = String::empty);
  24383. /** Starts a new group of actions that together will be treated as a single transaction.
  24384. All actions that are passed to the perform() method between calls to this
  24385. method are grouped together and undone/redone together by a single call to
  24386. undo() or redo().
  24387. @param actionName a description of the transaction that is about to be
  24388. performed
  24389. */
  24390. void beginNewTransaction (const String& actionName = String::empty);
  24391. /** Changes the name stored for the current transaction.
  24392. Each transaction is given a name when the beginNewTransaction() method is
  24393. called, but this can be used to change that name without starting a new
  24394. transaction.
  24395. */
  24396. void setCurrentTransactionName (const String& newName);
  24397. /** Returns true if there's at least one action in the list to undo.
  24398. @see getUndoDescription, undo, canRedo
  24399. */
  24400. bool canUndo() const;
  24401. /** Returns the description of the transaction that would be next to get undone.
  24402. The description returned is the one that was passed into beginNewTransaction
  24403. before the set of actions was performed.
  24404. @see undo
  24405. */
  24406. const String getUndoDescription() const;
  24407. /** Tries to roll-back the last transaction.
  24408. @returns true if the transaction can be undone, and false if it fails, or
  24409. if there aren't any transactions to undo
  24410. */
  24411. bool undo();
  24412. /** Tries to roll-back any actions that were added to the current transaction.
  24413. This will perform an undo() only if there are some actions in the undo list
  24414. that were added after the last call to beginNewTransaction().
  24415. This is useful because it lets you call beginNewTransaction(), then
  24416. perform an operation which may or may not actually perform some actions, and
  24417. then call this method to get rid of any actions that might have been done
  24418. without it rolling back the previous transaction if nothing was actually
  24419. done.
  24420. @returns true if any actions were undone.
  24421. */
  24422. bool undoCurrentTransactionOnly();
  24423. /** Returns a list of the UndoableAction objects that have been performed during the
  24424. transaction that is currently open.
  24425. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24426. were to be called now.
  24427. The first item in the list is the earliest action performed.
  24428. */
  24429. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24430. /** Returns true if there's at least one action in the list to redo.
  24431. @see getRedoDescription, redo, canUndo
  24432. */
  24433. bool canRedo() const;
  24434. /** Returns the description of the transaction that would be next to get redone.
  24435. The description returned is the one that was passed into beginNewTransaction
  24436. before the set of actions was performed.
  24437. @see redo
  24438. */
  24439. const String getRedoDescription() const;
  24440. /** Tries to redo the last transaction that was undone.
  24441. @returns true if the transaction can be redone, and false if it fails, or
  24442. if there aren't any transactions to redo
  24443. */
  24444. bool redo();
  24445. juce_UseDebuggingNewOperator
  24446. private:
  24447. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24448. StringArray transactionNames;
  24449. String currentTransactionName;
  24450. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24451. bool newTransaction, reentrancyCheck;
  24452. // disallow copy constructor
  24453. UndoManager (const UndoManager&);
  24454. const UndoManager& operator= (const UndoManager&);
  24455. };
  24456. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24457. /********* End of inlined file: juce_UndoManager.h *********/
  24458. class TextEditor;
  24459. class TextHolderComponent;
  24460. /**
  24461. Receives callbacks from a TextEditor component when it changes.
  24462. @see TextEditor::addListener
  24463. */
  24464. class JUCE_API TextEditorListener
  24465. {
  24466. public:
  24467. /** Destructor. */
  24468. virtual ~TextEditorListener() {}
  24469. /** Called when the user changes the text in some way. */
  24470. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24471. /** Called when the user presses the return key. */
  24472. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24473. /** Called when the user presses the escape key. */
  24474. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24475. /** Called when the text editor loses focus. */
  24476. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24477. };
  24478. /**
  24479. A component containing text that can be edited.
  24480. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24481. fonts and colours.
  24482. @see TextEditorListener, Label
  24483. */
  24484. class JUCE_API TextEditor : public Component,
  24485. public SettableTooltipClient
  24486. {
  24487. public:
  24488. /** Creates a new, empty text editor.
  24489. @param componentName the name to pass to the component for it to use as its name
  24490. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24491. for all characters that are drawn on screen - e.g. to create
  24492. a password-style textbox containing circular blobs instead of text,
  24493. you could set this value to 0x25cf, which is the unicode character
  24494. for a black splodge (not all fonts include this, though), or 0x2022,
  24495. which is a bullet (probably the best choice for linux).
  24496. */
  24497. TextEditor (const String& componentName = String::empty,
  24498. const tchar passwordCharacter = 0);
  24499. /** Destructor. */
  24500. virtual ~TextEditor();
  24501. /** Puts the editor into either multi- or single-line mode.
  24502. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24503. editor.
  24504. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24505. on if you want a multi-line editor with line-breaks.
  24506. @see isMultiLine, setReturnKeyStartsNewLine
  24507. */
  24508. void setMultiLine (const bool shouldBeMultiLine,
  24509. const bool shouldWordWrap = true);
  24510. /** Returns true if the editor is in multi-line mode.
  24511. */
  24512. bool isMultiLine() const throw();
  24513. /** Changes the behaviour of the return key.
  24514. If set to true, the return key will insert a new-line into the text; if false
  24515. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24516. method. By default this is set to false, and when true it will only insert
  24517. new-lines when in multi-line mode (see setMultiLine()).
  24518. */
  24519. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24520. /** Returns the value set by setReturnKeyStartsNewLine().
  24521. See setReturnKeyStartsNewLine() for more info.
  24522. */
  24523. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24524. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24525. or whether it gets ignored.
  24526. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24527. between components.
  24528. */
  24529. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24530. /** Returns true if the tab key is being used for input.
  24531. @see setTabKeyUsedAsCharacter
  24532. */
  24533. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24534. /** Changes the editor to read-only mode.
  24535. By default, the text editor is not read-only. If you're making it read-only, you
  24536. might also want to call setCaretVisible (false) to get rid of the caret.
  24537. The text can still be highlighted and copied when in read-only mode.
  24538. @see isReadOnly, setCaretVisible
  24539. */
  24540. void setReadOnly (const bool shouldBeReadOnly);
  24541. /** Returns true if the editor is in read-only mode.
  24542. */
  24543. bool isReadOnly() const throw();
  24544. /** Makes the caret visible or invisible.
  24545. By default the caret is visible.
  24546. @see setCaretColour, setCaretPosition
  24547. */
  24548. void setCaretVisible (const bool shouldBeVisible) throw();
  24549. /** Returns true if the caret is enabled.
  24550. @see setCaretVisible
  24551. */
  24552. bool isCaretVisible() const throw() { return caretVisible; }
  24553. /** Enables/disables a vertical scrollbar.
  24554. (This only applies when in multi-line mode). When the text gets too long to fit
  24555. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24556. this is enabled, the scrollbar will be hidden unless it's needed.
  24557. By default the scrollbar is enabled.
  24558. */
  24559. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24560. /** Returns true if scrollbars are enabled.
  24561. @see setScrollbarsShown
  24562. */
  24563. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24564. /** Changes the password character used to disguise the text.
  24565. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24566. for all characters that are drawn on screen - e.g. to create
  24567. a password-style textbox containing circular blobs instead of text,
  24568. you could set this value to 0x25cf, which is the unicode character
  24569. for a black splodge (not all fonts include this, though), or 0x2022,
  24570. which is a bullet (probably the best choice for linux).
  24571. */
  24572. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24573. /** Returns the current password character.
  24574. @see setPasswordCharacter
  24575. l */
  24576. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24577. /** Allows a right-click menu to appear for the editor.
  24578. (This defaults to being enabled).
  24579. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24580. of options such as cut/copy/paste, undo/redo, etc.
  24581. */
  24582. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24583. /** Returns true if the right-click menu is enabled.
  24584. @see setPopupMenuEnabled
  24585. */
  24586. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24587. /** Returns true if a popup-menu is currently being displayed.
  24588. */
  24589. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24590. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24591. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24592. methods.
  24593. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24594. */
  24595. enum ColourIds
  24596. {
  24597. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24598. transparent if necessary. */
  24599. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24600. that because the editor can contain multiple colours, calling this
  24601. method won't change the colour of existing text - to do that, call
  24602. applyFontToAllText() after calling this method.*/
  24603. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24604. the text - this can be transparent if you don't want to show any
  24605. highlighting.*/
  24606. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24607. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24608. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24609. the edge of the component. */
  24610. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24611. the edge of the component when it has focus. */
  24612. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24613. around the edge of the editor. */
  24614. };
  24615. /** Sets the font to use for newly added text.
  24616. This will change the font that will be used next time any text is added or entered
  24617. into the editor. It won't change the font of any existing text - to do that, use
  24618. applyFontToAllText() instead.
  24619. @see applyFontToAllText
  24620. */
  24621. void setFont (const Font& newFont) throw();
  24622. /** Applies a font to all the text in the editor.
  24623. This will also set the current font to use for any new text that's added.
  24624. @see setFont
  24625. */
  24626. void applyFontToAllText (const Font& newFont);
  24627. /** Returns the font that's currently being used for new text.
  24628. @see setFont
  24629. */
  24630. const Font getFont() const throw();
  24631. /** If set to true, focusing on the editor will highlight all its text.
  24632. (Set to false by default).
  24633. This is useful for boxes where you expect the user to re-enter all the
  24634. text when they focus on the component, rather than editing what's already there.
  24635. */
  24636. void setSelectAllWhenFocused (const bool b) throw();
  24637. /** Sets limits on the characters that can be entered.
  24638. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24639. limit is set
  24640. @param allowedCharacters if this is non-empty, then only characters that occur in
  24641. this string are allowed to be entered into the editor.
  24642. */
  24643. void setInputRestrictions (const int maxTextLength,
  24644. const String& allowedCharacters = String::empty) throw();
  24645. /** When the text editor is empty, it can be set to display a message.
  24646. This is handy for things like telling the user what to type in the box - the
  24647. string is only displayed, it's not taken to actually be the contents of
  24648. the editor.
  24649. */
  24650. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24651. /** Changes the size of the scrollbars that are used.
  24652. Handy if you need smaller scrollbars for a small text box.
  24653. */
  24654. void setScrollBarThickness (const int newThicknessPixels);
  24655. /** Shows or hides the buttons on any scrollbars that are used.
  24656. @see ScrollBar::setButtonVisibility
  24657. */
  24658. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24659. /** Registers a listener to be told when things happen to the text.
  24660. @see removeListener
  24661. */
  24662. void addListener (TextEditorListener* const newListener) throw();
  24663. /** Deregisters a listener.
  24664. @see addListener
  24665. */
  24666. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24667. /** Returns the entire contents of the editor. */
  24668. const String getText() const throw();
  24669. /** Returns a section of the contents of the editor. */
  24670. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24671. /** Returns true if there are no characters in the editor.
  24672. This is more efficient than calling getText().isEmpty().
  24673. */
  24674. bool isEmpty() const throw();
  24675. /** Sets the entire content of the editor.
  24676. This will clear the editor and insert the given text (using the current text colour
  24677. and font). You can set the current text colour using
  24678. @code setColour (TextEditor::textColourId, ...);
  24679. @endcode
  24680. @param newText the text to add
  24681. @param sendTextChangeMessage if true, this will cause a change message to
  24682. be sent to all the listeners.
  24683. @see insertText
  24684. */
  24685. void setText (const String& newText,
  24686. const bool sendTextChangeMessage = true);
  24687. /** Inserts some text at the current cursor position.
  24688. If a section of the text is highlighted, it will be replaced by
  24689. this string, otherwise it will be inserted.
  24690. To delete a section of text, you can use setHighlightedRegion() to
  24691. highlight it, and call insertTextAtCursor (String::empty).
  24692. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24693. */
  24694. void insertTextAtCursor (String textToInsert);
  24695. /** Deletes all the text from the editor. */
  24696. void clear();
  24697. /** Deletes the currently selected region, and puts it on the clipboard.
  24698. @see copy, paste, SystemClipboard
  24699. */
  24700. void cut();
  24701. /** Copies any currently selected region to the clipboard.
  24702. @see cut, paste, SystemClipboard
  24703. */
  24704. void copy();
  24705. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24706. @see cut, copy, SystemClipboard
  24707. */
  24708. void paste();
  24709. /** Moves the caret to be in front of a given character.
  24710. @see getCaretPosition
  24711. */
  24712. void setCaretPosition (const int newIndex) throw();
  24713. /** Returns the current index of the caret.
  24714. @see setCaretPosition
  24715. */
  24716. int getCaretPosition() const throw();
  24717. /** Attempts to scroll the text editor so that the caret ends up at
  24718. a specified position.
  24719. This won't affect the caret's position within the text, it tries to scroll
  24720. the entire editor vertically and horizontally so that the caret is sitting
  24721. at the given position (relative to the top-left of this component).
  24722. Depending on the amount of text available, it might not be possible to
  24723. scroll far enough for the caret to reach this exact position, but it
  24724. will go as far as it can in that direction.
  24725. */
  24726. void scrollEditorToPositionCaret (const int desiredCaretX,
  24727. const int desiredCaretY) throw();
  24728. /** Get the graphical position of the caret.
  24729. The rectangle returned is relative to the component's top-left corner.
  24730. @see scrollEditorToPositionCaret
  24731. */
  24732. const Rectangle getCaretRectangle() throw();
  24733. /** Selects a section of the text.
  24734. */
  24735. void setHighlightedRegion (int startIndex,
  24736. int numberOfCharactersToHighlight) throw();
  24737. /** Returns the first character that is selected.
  24738. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24739. will return 0.
  24740. @see setHighlightedRegion, getHighlightedRegionLength
  24741. */
  24742. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24743. /** Returns the number of characters that are selected.
  24744. @see setHighlightedRegion, getHighlightedRegionStart
  24745. */
  24746. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24747. /** Returns the section of text that is currently selected. */
  24748. const String getHighlightedText() const throw();
  24749. /** Finds the index of the character at a given position.
  24750. The co-ordinates are relative to the component's top-left.
  24751. */
  24752. int getTextIndexAt (const int x, const int y) throw();
  24753. /** Counts the number of characters in the text.
  24754. This is quicker than getting the text as a string if you just need to know
  24755. the length.
  24756. */
  24757. int getTotalNumChars() throw();
  24758. /** Returns the total width of the text, as it is currently laid-out.
  24759. This may be larger than the size of the TextEditor, and can change when
  24760. the TextEditor is resized or the text changes.
  24761. */
  24762. int getTextWidth() const throw();
  24763. /** Returns the maximum height of the text, as it is currently laid-out.
  24764. This may be larger than the size of the TextEditor, and can change when
  24765. the TextEditor is resized or the text changes.
  24766. */
  24767. int getTextHeight() const throw();
  24768. /** Changes the size of the gap at the top and left-edge of the editor.
  24769. By default there's a gap of 4 pixels.
  24770. */
  24771. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24772. /** Changes the size of border left around the edge of the component.
  24773. @see getBorder
  24774. */
  24775. void setBorder (const BorderSize& border) throw();
  24776. /** Returns the size of border around the edge of the component.
  24777. @see setBorder
  24778. */
  24779. const BorderSize getBorder() const throw();
  24780. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24781. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24782. set to false, it won't.
  24783. */
  24784. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24785. /** @internal */
  24786. void paint (Graphics& g);
  24787. /** @internal */
  24788. void paintOverChildren (Graphics& g);
  24789. /** @internal */
  24790. void mouseDown (const MouseEvent& e);
  24791. /** @internal */
  24792. void mouseUp (const MouseEvent& e);
  24793. /** @internal */
  24794. void mouseDrag (const MouseEvent& e);
  24795. /** @internal */
  24796. void mouseDoubleClick (const MouseEvent& e);
  24797. /** @internal */
  24798. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24799. /** @internal */
  24800. bool keyPressed (const KeyPress& key);
  24801. /** @internal */
  24802. bool keyStateChanged();
  24803. /** @internal */
  24804. void focusGained (FocusChangeType cause);
  24805. /** @internal */
  24806. void focusLost (FocusChangeType cause);
  24807. /** @internal */
  24808. void resized();
  24809. /** @internal */
  24810. void enablementChanged();
  24811. /** @internal */
  24812. void colourChanged();
  24813. juce_UseDebuggingNewOperator
  24814. protected:
  24815. /** This adds the items to the popup menu.
  24816. By default it adds the cut/copy/paste items, but you can override this if
  24817. you need to replace these with your own items.
  24818. If you want to add your own items to the existing ones, you can override this,
  24819. call the base class's addPopupMenuItems() method, then append your own items.
  24820. When the menu has been shown, performPopupMenuAction() will be called to
  24821. perform the item that the user has chosen.
  24822. The default menu items will be added using item IDs in the range
  24823. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24824. menu IDs.
  24825. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24826. a pointer to the info about it, or may be null if the menu is being triggered
  24827. by some other means.
  24828. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24829. */
  24830. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24831. const MouseEvent* mouseClickEvent);
  24832. /** This is called to perform one of the items that was shown on the popup menu.
  24833. If you've overridden addPopupMenuItems(), you should also override this
  24834. to perform the actions that you've added.
  24835. If you've overridden addPopupMenuItems() but have still left the default items
  24836. on the menu, remember to call the superclass's performPopupMenuAction()
  24837. so that it can perform the default actions if that's what the user clicked on.
  24838. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24839. */
  24840. virtual void performPopupMenuAction (const int menuItemID);
  24841. /** Scrolls the minimum distance needed to get the caret into view. */
  24842. void scrollToMakeSureCursorIsVisible() throw();
  24843. /** @internal */
  24844. void moveCaret (int newCaretPos) throw();
  24845. /** @internal */
  24846. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24847. /** Used internally to dispatch a text-change message. */
  24848. void textChanged() throw();
  24849. /** Begins a new transaction in the UndoManager.
  24850. */
  24851. void newTransaction() throw();
  24852. /** Used internally to trigger an undo or redo. */
  24853. void doUndoRedo (const bool isRedo);
  24854. /** Can be overridden to intercept return key presses directly */
  24855. virtual void returnPressed();
  24856. /** Can be overridden to intercept escape key presses directly */
  24857. virtual void escapePressed();
  24858. /** @internal */
  24859. void handleCommandMessage (int commandId);
  24860. private:
  24861. Viewport* viewport;
  24862. TextHolderComponent* textHolder;
  24863. BorderSize borderSize;
  24864. bool readOnly : 1;
  24865. bool multiline : 1;
  24866. bool wordWrap : 1;
  24867. bool returnKeyStartsNewLine : 1;
  24868. bool caretVisible : 1;
  24869. bool popupMenuEnabled : 1;
  24870. bool selectAllTextWhenFocused : 1;
  24871. bool scrollbarVisible : 1;
  24872. bool wasFocused : 1;
  24873. bool caretFlashState : 1;
  24874. bool keepCursorOnScreen : 1;
  24875. bool tabKeyUsed : 1;
  24876. bool menuActive : 1;
  24877. UndoManager undoManager;
  24878. float cursorX, cursorY, cursorHeight;
  24879. int maxTextLength;
  24880. int selectionStart, selectionEnd;
  24881. int leftIndent, topIndent;
  24882. unsigned int lastTransactionTime;
  24883. Font currentFont;
  24884. int totalNumChars, caretPosition;
  24885. VoidArray sections;
  24886. String textToShowWhenEmpty;
  24887. Colour colourForTextWhenEmpty;
  24888. tchar passwordCharacter;
  24889. enum
  24890. {
  24891. notDragging,
  24892. draggingSelectionStart,
  24893. draggingSelectionEnd
  24894. } dragType;
  24895. String allowedCharacters;
  24896. SortedSet <void*> listeners;
  24897. friend class TextEditorInsertAction;
  24898. friend class TextEditorRemoveAction;
  24899. void coalesceSimilarSections() throw();
  24900. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24901. void clearInternal (UndoManager* const um) throw();
  24902. void insert (const String& text,
  24903. const int insertIndex,
  24904. const Font& font,
  24905. const Colour& colour,
  24906. UndoManager* const um,
  24907. const int caretPositionToMoveTo) throw();
  24908. void reinsert (const int insertIndex,
  24909. const VoidArray& sections) throw();
  24910. void remove (const int startIndex,
  24911. int endIndex,
  24912. UndoManager* const um,
  24913. const int caretPositionToMoveTo) throw();
  24914. void getCharPosition (const int index,
  24915. float& x, float& y,
  24916. float& lineHeight) const throw();
  24917. void updateCaretPosition() throw();
  24918. int indexAtPosition (const float x,
  24919. const float y) throw();
  24920. int findWordBreakAfter (const int position) const throw();
  24921. int findWordBreakBefore (const int position) const throw();
  24922. friend class TextHolderComponent;
  24923. friend class TextEditorViewport;
  24924. void drawContent (Graphics& g);
  24925. void updateTextHolderSize() throw();
  24926. float getWordWrapWidth() const throw();
  24927. void timerCallbackInt();
  24928. void repaintCaret();
  24929. void repaintText (int textStartIndex, int textEndIndex);
  24930. TextEditor (const TextEditor&);
  24931. const TextEditor& operator= (const TextEditor&);
  24932. };
  24933. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24934. /********* End of inlined file: juce_TextEditor.h *********/
  24935. class Label;
  24936. /**
  24937. A class for receiving events from a Label.
  24938. You can register a LabelListener with a Label using the Label::addListener()
  24939. method, and it will be called when the text of the label changes, either because
  24940. of a call to Label::setText() or by the user editing the text (if the label is
  24941. editable).
  24942. @see Label::addListener, Label::removeListener
  24943. */
  24944. class JUCE_API LabelListener
  24945. {
  24946. public:
  24947. /** Destructor. */
  24948. virtual ~LabelListener() {}
  24949. /** Called when a Label's text has changed.
  24950. */
  24951. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24952. };
  24953. /**
  24954. A component that displays a text string, and can optionally become a text
  24955. editor when clicked.
  24956. */
  24957. class JUCE_API Label : public Component,
  24958. public SettableTooltipClient,
  24959. protected TextEditorListener,
  24960. private ComponentListener
  24961. {
  24962. public:
  24963. /** Creates a Label.
  24964. @param componentName the name to give the component
  24965. @param labelText the text to show in the label
  24966. */
  24967. Label (const String& componentName,
  24968. const String& labelText);
  24969. /** Destructor. */
  24970. ~Label();
  24971. /** Changes the label text.
  24972. If broadcastChangeMessage is true and the new text is different to the current
  24973. text, then the class will broadcast a change message to any LabelListeners that
  24974. are registered.
  24975. */
  24976. void setText (const String& newText,
  24977. const bool broadcastChangeMessage);
  24978. /** Returns the label's current text.
  24979. @param returnActiveEditorContents if this is true and the label is currently
  24980. being edited, then this method will return the
  24981. text as it's being shown in the editor. If false,
  24982. then the value returned here won't be updated until
  24983. the user has finished typing and pressed the return
  24984. key.
  24985. */
  24986. const String getText (const bool returnActiveEditorContents = false) const throw();
  24987. /** Changes the font to use to draw the text.
  24988. @see getFont
  24989. */
  24990. void setFont (const Font& newFont) throw();
  24991. /** Returns the font currently being used.
  24992. @see setFont
  24993. */
  24994. const Font& getFont() const throw();
  24995. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24996. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24997. methods.
  24998. Note that you can also use the constants from TextEditor::ColourIds to change the
  24999. colour of the text editor that is opened when a label is editable.
  25000. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25001. */
  25002. enum ColourIds
  25003. {
  25004. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  25005. textColourId = 0x1000281, /**< The colour for the text. */
  25006. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25007. Leave this transparent to not have an outline. */
  25008. };
  25009. /** Sets the style of justification to be used for positioning the text.
  25010. (The default is Justification::centredLeft)
  25011. */
  25012. void setJustificationType (const Justification& justification) throw();
  25013. /** Returns the type of justification, as set in setJustificationType(). */
  25014. const Justification getJustificationType() const throw() { return justification; }
  25015. /** Changes the gap that is left between the edge of the component and the text.
  25016. By default there's a small gap left at the sides of the component to allow for
  25017. the drawing of the border, but you can change this if necessary.
  25018. */
  25019. void setBorderSize (int horizontalBorder, int verticalBorder);
  25020. /** Returns the size of the horizontal gap being left around the text.
  25021. */
  25022. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25023. /** Returns the size of the vertical gap being left around the text.
  25024. */
  25025. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25026. /** Makes this label "stick to" another component.
  25027. This will cause the label to follow another component around, staying
  25028. either to its left or above it.
  25029. @param owner the component to follow
  25030. @param onLeft if true, the label will stay on the left of its component; if
  25031. false, it will stay above it.
  25032. */
  25033. void attachToComponent (Component* owner,
  25034. const bool onLeft);
  25035. /** If this label has been attached to another component using attachToComponent, this
  25036. returns the other component.
  25037. Returns 0 if the label is not attached.
  25038. */
  25039. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25040. /** If the label is attached to the left of another component, this returns true.
  25041. Returns false if the label is above the other component. This is only relevent if
  25042. attachToComponent() has been called.
  25043. */
  25044. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25045. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25046. using ellipsis.
  25047. @see Graphics::drawFittedText
  25048. */
  25049. void setMinimumHorizontalScale (const float newScale);
  25050. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25051. /** Registers a listener that will be called when the label's text changes. */
  25052. void addListener (LabelListener* const listener) throw();
  25053. /** Deregisters a previously-registered listener. */
  25054. void removeListener (LabelListener* const listener) throw();
  25055. /** Makes the label turn into a TextEditor when clicked.
  25056. By default this is turned off.
  25057. If turned on, then single- or double-clicking will turn the label into
  25058. an editor. If the user then changes the text, then the ChangeBroadcaster
  25059. base class will be used to send change messages to any listeners that
  25060. have registered.
  25061. If the user changes the text, the textWasEdited() method will be called
  25062. afterwards, and subclasses can override this if they need to do anything
  25063. special.
  25064. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25065. @param editOnDoubleClick if true, a double-click is needed to start editing
  25066. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25067. edited will discard any changes; if false, then this will
  25068. commit the changes.
  25069. @see showEditor, setEditorColours, TextEditor
  25070. */
  25071. void setEditable (const bool editOnSingleClick,
  25072. const bool editOnDoubleClick = false,
  25073. const bool lossOfFocusDiscardsChanges = false) throw();
  25074. /** Returns true if this option was set using setEditable(). */
  25075. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25076. /** Returns true if this option was set using setEditable(). */
  25077. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25078. /** Returns true if this option has been set in a call to setEditable(). */
  25079. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25080. /** Returns true if the user can edit this label's text. */
  25081. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25082. /** Makes the editor appear as if the label had been clicked by the user.
  25083. @see textWasEdited, setEditable
  25084. */
  25085. void showEditor();
  25086. /** Hides the editor if it was being shown.
  25087. @param discardCurrentEditorContents if true, the label's text will be
  25088. reset to whatever it was before the editor
  25089. was shown; if false, the current contents of the
  25090. editor will be used to set the label's text
  25091. before it is hidden.
  25092. */
  25093. void hideEditor (const bool discardCurrentEditorContents);
  25094. /** Returns true if the editor is currently focused and active. */
  25095. bool isBeingEdited() const throw();
  25096. juce_UseDebuggingNewOperator
  25097. protected:
  25098. /** @internal */
  25099. void paint (Graphics& g);
  25100. /** @internal */
  25101. void resized();
  25102. /** @internal */
  25103. void mouseUp (const MouseEvent& e);
  25104. /** @internal */
  25105. void mouseDoubleClick (const MouseEvent& e);
  25106. /** @internal */
  25107. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25108. /** @internal */
  25109. void componentParentHierarchyChanged (Component& component);
  25110. /** @internal */
  25111. void componentVisibilityChanged (Component& component);
  25112. /** @internal */
  25113. void inputAttemptWhenModal();
  25114. /** @internal */
  25115. void focusGained (FocusChangeType);
  25116. /** @internal */
  25117. void enablementChanged();
  25118. /** @internal */
  25119. KeyboardFocusTraverser* createFocusTraverser();
  25120. /** @internal */
  25121. void textEditorTextChanged (TextEditor& editor);
  25122. /** @internal */
  25123. void textEditorReturnKeyPressed (TextEditor& editor);
  25124. /** @internal */
  25125. void textEditorEscapeKeyPressed (TextEditor& editor);
  25126. /** @internal */
  25127. void textEditorFocusLost (TextEditor& editor);
  25128. /** @internal */
  25129. void colourChanged();
  25130. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25131. Subclasses can override this if they need to customise this component in some way.
  25132. */
  25133. virtual TextEditor* createEditorComponent();
  25134. /** Called after the user changes the text.
  25135. */
  25136. virtual void textWasEdited();
  25137. /** Called when the text has been altered.
  25138. */
  25139. virtual void textWasChanged();
  25140. private:
  25141. String text;
  25142. Font font;
  25143. Justification justification;
  25144. TextEditor* editor;
  25145. SortedSet <void*> listeners;
  25146. Component* ownerComponent;
  25147. ComponentDeletionWatcher* deletionWatcher;
  25148. int horizontalBorderSize, verticalBorderSize;
  25149. float minimumHorizontalScale;
  25150. bool editSingleClick : 1;
  25151. bool editDoubleClick : 1;
  25152. bool lossOfFocusDiscardsChanges : 1;
  25153. bool leftOfOwnerComp : 1;
  25154. bool updateFromTextEditorContents();
  25155. void callChangeListeners();
  25156. Label (const Label&);
  25157. const Label& operator= (const Label&);
  25158. };
  25159. #endif // __JUCE_LABEL_JUCEHEADER__
  25160. /********* End of inlined file: juce_Label.h *********/
  25161. class ComboBox;
  25162. /**
  25163. A class for receiving events from a ComboBox.
  25164. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25165. method, and it will be called when the selected item in the box changes.
  25166. @see ComboBox::addListener, ComboBox::removeListener
  25167. */
  25168. class JUCE_API ComboBoxListener
  25169. {
  25170. public:
  25171. /** Destructor. */
  25172. virtual ~ComboBoxListener() {}
  25173. /** Called when a ComboBox has its selected item changed.
  25174. */
  25175. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25176. };
  25177. /**
  25178. A component that lets the user choose from a drop-down list of choices.
  25179. The combo-box has a list of text strings, each with an associated id number,
  25180. that will be shown in the drop-down list when the user clicks on the component.
  25181. The currently selected choice is displayed in the combo-box, and this can
  25182. either be read-only text, or editable.
  25183. To find out when the user selects a different item or edits the text, you
  25184. can register a ComboBoxListener to receive callbacks.
  25185. @see ComboBoxListener
  25186. */
  25187. class JUCE_API ComboBox : public Component,
  25188. public SettableTooltipClient,
  25189. private LabelListener,
  25190. private AsyncUpdater
  25191. {
  25192. public:
  25193. /** Creates a combo-box.
  25194. On construction, the text field will be empty, so you should call the
  25195. setSelectedId() or setText() method to choose the initial value before
  25196. displaying it.
  25197. @param componentName the name to set for the component (see Component::setName())
  25198. */
  25199. ComboBox (const String& componentName);
  25200. /** Destructor. */
  25201. ~ComboBox();
  25202. /** Sets whether the test in the combo-box is editable.
  25203. The default state for a new ComboBox is non-editable, and can only be changed
  25204. by choosing from the drop-down list.
  25205. */
  25206. void setEditableText (const bool isEditable);
  25207. /** Returns true if the text is directly editable.
  25208. @see setEditableText
  25209. */
  25210. bool isTextEditable() const throw();
  25211. /** Sets the style of justification to be used for positioning the text.
  25212. The default is Justification::centredLeft. The text is displayed using a
  25213. Label component inside the ComboBox.
  25214. */
  25215. void setJustificationType (const Justification& justification) throw();
  25216. /** Returns the current justification for the text box.
  25217. @see setJustificationType
  25218. */
  25219. const Justification getJustificationType() const throw();
  25220. /** Adds an item to be shown in the drop-down list.
  25221. @param newItemText the text of the item to show in the list
  25222. @param newItemId an associated ID number that can be set or retrieved - see
  25223. getSelectedId() and setSelectedId()
  25224. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25225. */
  25226. void addItem (const String& newItemText,
  25227. const int newItemId) throw();
  25228. /** Adds a separator line to the drop-down list.
  25229. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25230. */
  25231. void addSeparator() throw();
  25232. /** Adds a heading to the drop-down list, so that you can group the items into
  25233. different sections.
  25234. The headings are indented slightly differently to set them apart from the
  25235. items on the list, and obviously can't be selected. You might want to add
  25236. separators between your sections too.
  25237. @see addItem, addSeparator
  25238. */
  25239. void addSectionHeading (const String& headingName) throw();
  25240. /** This allows items in the drop-down list to be selectively disabled.
  25241. When you add an item, it's enabled by default, but you can call this
  25242. method to change its status.
  25243. If you disable an item which is already selected, this won't change the
  25244. current selection - it just stops the user choosing that item from the list.
  25245. */
  25246. void setItemEnabled (const int itemId,
  25247. const bool isEnabled) throw();
  25248. /** Changes the text for an existing item.
  25249. */
  25250. void changeItemText (const int itemId,
  25251. const String& newText) throw();
  25252. /** Removes all the items from the drop-down list.
  25253. If this call causes the content to be cleared, then a change-message
  25254. will be broadcast unless dontSendChangeMessage is true.
  25255. @see addItem, removeItem, getNumItems
  25256. */
  25257. void clear (const bool dontSendChangeMessage = false);
  25258. /** Returns the number of items that have been added to the list.
  25259. Note that this doesn't include headers or separators.
  25260. */
  25261. int getNumItems() const throw();
  25262. /** Returns the text for one of the items in the list.
  25263. Note that this doesn't include headers or separators.
  25264. @param index the item's index from 0 to (getNumItems() - 1)
  25265. */
  25266. const String getItemText (const int index) const throw();
  25267. /** Returns the ID for one of the items in the list.
  25268. Note that this doesn't include headers or separators.
  25269. @param index the item's index from 0 to (getNumItems() - 1)
  25270. */
  25271. int getItemId (const int index) const throw();
  25272. /** Returns the ID of the item that's currently shown in the box.
  25273. If no item is selected, or if the text is editable and the user
  25274. has entered something which isn't one of the items in the list, then
  25275. this will return 0.
  25276. @see setSelectedId, getSelectedItemIndex, getText
  25277. */
  25278. int getSelectedId() const throw();
  25279. /** Sets one of the items to be the current selection.
  25280. This will set the ComboBox's text to that of the item that matches
  25281. this ID.
  25282. @param newItemId the new item to select
  25283. @param dontSendChangeMessage if set to true, this method won't trigger a
  25284. change notification
  25285. @see getSelectedId, setSelectedItemIndex, setText
  25286. */
  25287. void setSelectedId (const int newItemId,
  25288. const bool dontSendChangeMessage = false) throw();
  25289. /** Returns the index of the item that's currently shown in the box.
  25290. If no item is selected, or if the text is editable and the user
  25291. has entered something which isn't one of the items in the list, then
  25292. this will return -1.
  25293. @see setSelectedItemIndex, getSelectedId, getText
  25294. */
  25295. int getSelectedItemIndex() const throw();
  25296. /** Sets one of the items to be the current selection.
  25297. This will set the ComboBox's text to that of the item at the given
  25298. index in the list.
  25299. @param newItemIndex the new item to select
  25300. @param dontSendChangeMessage if set to true, this method won't trigger a
  25301. change notification
  25302. @see getSelectedItemIndex, setSelectedId, setText
  25303. */
  25304. void setSelectedItemIndex (const int newItemIndex,
  25305. const bool dontSendChangeMessage = false) throw();
  25306. /** Returns the text that is currently shown in the combo-box's text field.
  25307. If the ComboBox has editable text, then this text may have been edited
  25308. by the user; otherwise it will be one of the items from the list, or
  25309. possibly an empty string if nothing was selected.
  25310. @see setText, getSelectedId, getSelectedItemIndex
  25311. */
  25312. const String getText() const throw();
  25313. /** Sets the contents of the combo-box's text field.
  25314. The text passed-in will be set as the current text regardless of whether
  25315. it is one of the items in the list. If the current text isn't one of the
  25316. items, then getSelectedId() will return -1, otherwise it wil return
  25317. the approriate ID.
  25318. @param newText the text to select
  25319. @param dontSendChangeMessage if set to true, this method won't trigger a
  25320. change notification
  25321. @see getText
  25322. */
  25323. void setText (const String& newText,
  25324. const bool dontSendChangeMessage = false) throw();
  25325. /** Programmatically opens the text editor to allow the user to edit the current item.
  25326. This is the same effect as when the box is clicked-on.
  25327. @see Label::showEditor();
  25328. */
  25329. void showEditor();
  25330. /** Registers a listener that will be called when the box's content changes. */
  25331. void addListener (ComboBoxListener* const listener) throw();
  25332. /** Deregisters a previously-registered listener. */
  25333. void removeListener (ComboBoxListener* const listener) throw();
  25334. /** Sets a message to display when there is no item currently selected.
  25335. @see getTextWhenNothingSelected
  25336. */
  25337. void setTextWhenNothingSelected (const String& newMessage) throw();
  25338. /** Returns the text that is shown when no item is selected.
  25339. @see setTextWhenNothingSelected
  25340. */
  25341. const String getTextWhenNothingSelected() const throw();
  25342. /** Sets the message to show when there are no items in the list, and the user clicks
  25343. on the drop-down box.
  25344. By default it just says "no choices", but this lets you change it to something more
  25345. meaningful.
  25346. */
  25347. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25348. /** Returns the text shown when no items have been added to the list.
  25349. @see setTextWhenNoChoicesAvailable
  25350. */
  25351. const String getTextWhenNoChoicesAvailable() const throw();
  25352. /** Gives the ComboBox a tooltip. */
  25353. void setTooltip (const String& newTooltip);
  25354. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25355. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25356. methods.
  25357. To change the colours of the menu that pops up
  25358. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25359. */
  25360. enum ColourIds
  25361. {
  25362. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25363. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25364. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25365. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25366. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25367. };
  25368. /** @internal */
  25369. void labelTextChanged (Label*);
  25370. /** @internal */
  25371. void enablementChanged();
  25372. /** @internal */
  25373. void colourChanged();
  25374. /** @internal */
  25375. void focusGained (Component::FocusChangeType cause);
  25376. /** @internal */
  25377. void focusLost (Component::FocusChangeType cause);
  25378. /** @internal */
  25379. void handleAsyncUpdate();
  25380. /** @internal */
  25381. const String getTooltip() { return label->getTooltip(); }
  25382. /** @internal */
  25383. void mouseDown (const MouseEvent&);
  25384. /** @internal */
  25385. void mouseDrag (const MouseEvent&);
  25386. /** @internal */
  25387. void mouseUp (const MouseEvent&);
  25388. /** @internal */
  25389. void lookAndFeelChanged();
  25390. /** @internal */
  25391. void paint (Graphics&);
  25392. /** @internal */
  25393. void resized();
  25394. /** @internal */
  25395. bool keyStateChanged();
  25396. /** @internal */
  25397. bool keyPressed (const KeyPress&);
  25398. juce_UseDebuggingNewOperator
  25399. private:
  25400. struct ItemInfo
  25401. {
  25402. String name;
  25403. int itemId;
  25404. bool isEnabled : 1, isHeading : 1;
  25405. bool isSeparator() const throw();
  25406. bool isRealItem() const throw();
  25407. };
  25408. OwnedArray <ItemInfo> items;
  25409. int currentIndex;
  25410. bool isButtonDown;
  25411. bool separatorPending;
  25412. bool menuActive;
  25413. SortedSet <void*> listeners;
  25414. Label* label;
  25415. String textWhenNothingSelected, noChoicesMessage;
  25416. void showPopup();
  25417. ItemInfo* getItemForId (const int itemId) const throw();
  25418. ItemInfo* getItemForIndex (const int index) const throw();
  25419. ComboBox (const ComboBox&);
  25420. const ComboBox& operator= (const ComboBox&);
  25421. };
  25422. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25423. /********* End of inlined file: juce_ComboBox.h *********/
  25424. /**
  25425. Manages the state of some audio and midi i/o devices.
  25426. This class keeps tracks of a currently-selected audio device, through
  25427. with which it continuously streams data from an audio callback, as well as
  25428. one or more midi inputs.
  25429. The idea is that your application will create one global instance of this object,
  25430. and let it take care of creating and deleting specific types of audio devices
  25431. internally. So when the device is changed, your callbacks will just keep running
  25432. without having to worry about this.
  25433. The manager can save and reload all of its device settings as XML, which
  25434. makes it very easy for you to save and reload the audio setup of your
  25435. application.
  25436. And to make it easy to let the user change its settings, there's a component
  25437. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25438. device selection/sample-rate/latency controls.
  25439. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25440. call setAudioCallback() to register your audio callback with it, and use that to process
  25441. your audio data.
  25442. The manager also acts as a handy hub for incoming midi messages, allowing a
  25443. listener to register for messages from either a specific midi device, or from whatever
  25444. the current default midi input device is. The listener then doesn't have to worry about
  25445. re-registering with different midi devices if they are changed or deleted.
  25446. And yet another neat trick is that amount of CPU time being used is measured and
  25447. available with the getCpuUsage() method.
  25448. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25449. listeners whenever one of its settings is changed.
  25450. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25451. */
  25452. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25453. {
  25454. public:
  25455. /** Creates a default AudioDeviceManager.
  25456. Initially no audio device will be selected. You should call the initialise() method
  25457. and register an audio callback with setAudioCallback() before it'll be able to
  25458. actually make any noise.
  25459. */
  25460. AudioDeviceManager();
  25461. /** Destructor. */
  25462. ~AudioDeviceManager();
  25463. /**
  25464. This structure holds a set of properties describing the current audio setup.
  25465. @see AudioDeviceManager::setAudioDeviceSetup()
  25466. */
  25467. struct JUCE_API AudioDeviceSetup
  25468. {
  25469. AudioDeviceSetup();
  25470. bool operator== (const AudioDeviceSetup& other) const;
  25471. /** The name of the audio device used for output.
  25472. This may be the same as the input device.
  25473. */
  25474. String outputDeviceName;
  25475. /** The name of the audio device used for input.
  25476. This may be the same as the output device.
  25477. */
  25478. String inputDeviceName;
  25479. /** The current sample rate.
  25480. This rate is used for both the input and output devices.
  25481. */
  25482. double sampleRate;
  25483. /** The buffer size, in samples.
  25484. This buffer size is used for both the input and output devices.
  25485. */
  25486. int bufferSize;
  25487. /** The set of active input channels.
  25488. The bits that are set in this array indicate the channels of the
  25489. input device that are active.
  25490. */
  25491. BitArray inputChannels;
  25492. /** If this is true, it indicates that the inputChannels array
  25493. should be ignored, and instead, the device's default channels
  25494. should be used.
  25495. */
  25496. bool useDefaultInputChannels;
  25497. /** The set of active output channels.
  25498. The bits that are set in this array indicate the channels of the
  25499. input device that are active.
  25500. */
  25501. BitArray outputChannels;
  25502. /** If this is true, it indicates that the outputChannels array
  25503. should be ignored, and instead, the device's default channels
  25504. should be used.
  25505. */
  25506. bool useDefaultOutputChannels;
  25507. };
  25508. /** Opens a set of audio devices ready for use.
  25509. This will attempt to open either a default audio device, or one that was
  25510. previously saved as XML.
  25511. @param numInputChannelsNeeded a minimum number of input channels needed
  25512. by your app.
  25513. @param numOutputChannelsNeeded a minimum number of output channels to open
  25514. @param savedState either a previously-saved state that was produced
  25515. by createStateXml(), or 0 if you want the manager
  25516. to choose the best device to open.
  25517. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25518. fails to open, then a default device will be used
  25519. instead. If false, then on failure, no device is
  25520. opened.
  25521. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25522. name, then that will be used as the default device
  25523. (assuming that there wasn't one specified in the XML).
  25524. The string can actually be a simple wildcard, containing "*"
  25525. and "?" characters
  25526. @param preferredSetupOptions if this is non-null, the structure will be used as the
  25527. set of preferred settings when opening the device. If you
  25528. use this parameter, the preferredDefaultDeviceName
  25529. field will be ignored
  25530. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25531. */
  25532. const String initialise (const int numInputChannelsNeeded,
  25533. const int numOutputChannelsNeeded,
  25534. const XmlElement* const savedState,
  25535. const bool selectDefaultDeviceOnFailure,
  25536. const String& preferredDefaultDeviceName = String::empty,
  25537. const AudioDeviceSetup* preferredSetupOptions = 0);
  25538. /** Returns some XML representing the current state of the manager.
  25539. This stores the current device, its samplerate, block size, etc, and
  25540. can be restored later with initialise().
  25541. */
  25542. XmlElement* createStateXml() const;
  25543. /** Returns the current device properties that are in use.
  25544. @see setAudioDeviceSetup
  25545. */
  25546. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25547. /** Changes the current device or its settings.
  25548. If you want to change a device property, like the current sample rate or
  25549. block size, you can call getAudioDeviceSetup() to retrieve the current
  25550. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  25551. and pass it back into this method to apply the new settings.
  25552. @param newSetup the settings that you'd like to use
  25553. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25554. settings will be taken as having been explicitly chosen by the
  25555. user, and the next time createStateXml() is called, these settings
  25556. will be returned. If it's false, then the device is treated as a
  25557. temporary or default device, and a call to createStateXml() will
  25558. return either the last settings that were made with treatAsChosenDevice
  25559. as true, or the last XML settings that were passed into initialise().
  25560. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25561. @see getAudioDeviceSetup
  25562. */
  25563. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25564. const bool treatAsChosenDevice);
  25565. /** Returns the currently-active audio device. */
  25566. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25567. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25568. void setCurrentAudioDeviceType (const String& type,
  25569. const bool treatAsChosenDevice);
  25570. /** Closes the currently-open device.
  25571. You can call restartLastAudioDevice() later to reopen it in the same state
  25572. that it was just in.
  25573. */
  25574. void closeAudioDevice();
  25575. /** Tries to reload the last audio device that was running.
  25576. Note that this only reloads the last device that was running before
  25577. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25578. and can only be called after a device has been opened with SetAudioDevice().
  25579. If a device is already open, this call will do nothing.
  25580. */
  25581. void restartLastAudioDevice();
  25582. /** Gives the manager an audio callback to use.
  25583. The manager will redirect callbacks from whatever audio device is currently
  25584. in use to this callback object.
  25585. You can pass 0 in here to stop callbacks being made.
  25586. */
  25587. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25588. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25589. Returns a value between 0 and 1.0
  25590. */
  25591. double getCpuUsage() const;
  25592. /** Enables or disables a midi input device.
  25593. The list of devices can be obtained with the MidiInput::getDevices() method.
  25594. Any incoming messages from enabled input devices will be forwarded on to all the
  25595. listeners that have been registered with the addMidiInputCallback() method. They
  25596. can either register for messages from a particular device, or from just the
  25597. "default" midi input.
  25598. Routing the midi input via an AudioDeviceManager means that when a listener
  25599. registers for the default midi input, this default device can be changed by the
  25600. manager without the listeners having to know about it or re-register.
  25601. It also means that a listener can stay registered for a midi input that is disabled
  25602. or not present, so that when the input is re-enabled, the listener will start
  25603. receiving messages again.
  25604. @see addMidiInputCallback, isMidiInputEnabled
  25605. */
  25606. void setMidiInputEnabled (const String& midiInputDeviceName,
  25607. const bool enabled);
  25608. /** Returns true if a given midi input device is being used.
  25609. @see setMidiInputEnabled
  25610. */
  25611. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25612. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25613. The device name can be empty to indicate that it wants events from whatever the
  25614. current "default" device is. Or it can be the name of one of the midi input devices
  25615. (see MidiInput::getDevices() for the names).
  25616. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25617. events forwarded on to listeners.
  25618. */
  25619. void addMidiInputCallback (const String& midiInputDeviceName,
  25620. MidiInputCallback* callback);
  25621. /** Removes a listener that was previously registered with addMidiInputCallback().
  25622. */
  25623. void removeMidiInputCallback (const String& midiInputDeviceName,
  25624. MidiInputCallback* callback);
  25625. /** Sets a midi output device to use as the default.
  25626. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25627. The specified device will be opened automatically and can be retrieved with the
  25628. getDefaultMidiOutput() method.
  25629. Pass in an empty string to deselect all devices. For the default device, you
  25630. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25631. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25632. */
  25633. void setDefaultMidiOutput (const String& deviceName);
  25634. /** Returns the name of the default midi output.
  25635. @see setDefaultMidiOutput, getDefaultMidiOutput
  25636. */
  25637. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25638. /** Returns the current default midi output device.
  25639. If no device has been selected, or the device can't be opened, this will
  25640. return 0.
  25641. @see getDefaultMidiOutputName
  25642. */
  25643. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25644. /**
  25645. */
  25646. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25647. /** Creates a list of available types.
  25648. This will add a set of new AudioIODeviceType objects to the specified list, to
  25649. represent each available types of device.
  25650. You can override this if your app needs to do something specific, like avoid
  25651. using DirectSound devices, etc.
  25652. */
  25653. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25654. /** Plays a beep through the current audio device.
  25655. This is here to allow the audio setup UI panels to easily include a "test"
  25656. button so that the user can check where the audio is coming from.
  25657. */
  25658. void playTestSound();
  25659. /** Turns on level-measuring.
  25660. When enabled, the device manager will measure the peak input level
  25661. across all channels, and you can get this level by calling getCurrentInputLevel().
  25662. This is mainly intended for audio setup UI panels to use to create a mic
  25663. level display, so that the user can check that they've selected the right
  25664. device.
  25665. A simple filter is used to make the level decay smoothly, but this is
  25666. only intended for giving rough feedback, and not for any kind of accurate
  25667. measurement.
  25668. */
  25669. void enableInputLevelMeasurement (const bool enableMeasurement);
  25670. /** Returns the current input level.
  25671. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25672. See enableInputLevelMeasurement() for more info.
  25673. */
  25674. double getCurrentInputLevel() const;
  25675. juce_UseDebuggingNewOperator
  25676. private:
  25677. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25678. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25679. AudioDeviceSetup currentSetup;
  25680. AudioIODevice* currentAudioDevice;
  25681. AudioIODeviceCallback* currentCallback;
  25682. int numInputChansNeeded, numOutputChansNeeded;
  25683. String currentDeviceType;
  25684. BitArray inputChannels, outputChannels;
  25685. XmlElement* lastExplicitSettings;
  25686. mutable bool listNeedsScanning;
  25687. bool useInputNames, inputLevelMeasurementEnabled;
  25688. double inputLevel;
  25689. AudioSampleBuffer* testSound;
  25690. int testSoundPosition;
  25691. StringArray midiInsFromXml;
  25692. OwnedArray <MidiInput> enabledMidiInputs;
  25693. Array <MidiInputCallback*> midiCallbacks;
  25694. Array <MidiInput*> midiCallbackDevices;
  25695. String defaultMidiOutputName;
  25696. MidiOutput* defaultMidiOutput;
  25697. CriticalSection audioCallbackLock, midiCallbackLock;
  25698. double cpuUsageMs, timeToCpuScale;
  25699. class CallbackHandler : public AudioIODeviceCallback,
  25700. public MidiInputCallback
  25701. {
  25702. public:
  25703. AudioDeviceManager* owner;
  25704. void audioDeviceIOCallback (const float** inputChannelData,
  25705. int totalNumInputChannels,
  25706. float** outputChannelData,
  25707. int totalNumOutputChannels,
  25708. int numSamples);
  25709. void audioDeviceAboutToStart (AudioIODevice*);
  25710. void audioDeviceStopped();
  25711. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25712. };
  25713. CallbackHandler callbackHandler;
  25714. friend class CallbackHandler;
  25715. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25716. int totalNumInputChannels,
  25717. float** outputChannelData,
  25718. int totalNumOutputChannels,
  25719. int numSamples);
  25720. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25721. void audioDeviceStoppedInt();
  25722. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25723. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25724. const BitArray& ins, const BitArray& outs);
  25725. void stopDevice();
  25726. void updateXml();
  25727. void createDeviceTypesIfNeeded();
  25728. void scanDevicesIfNeeded();
  25729. void deleteCurrentDevice();
  25730. double chooseBestSampleRate (double preferred) const;
  25731. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25732. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25733. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25734. AudioDeviceManager (const AudioDeviceManager&);
  25735. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25736. };
  25737. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25738. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25739. #endif
  25740. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25741. #endif
  25742. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25743. #endif
  25744. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25745. #endif
  25746. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25747. /********* Start of inlined file: juce_Sampler.h *********/
  25748. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25749. #define __JUCE_SAMPLER_JUCEHEADER__
  25750. /********* Start of inlined file: juce_Synthesiser.h *********/
  25751. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25752. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25753. /**
  25754. Describes one of the sounds that a Synthesiser can play.
  25755. A synthesiser can contain one or more sounds, and a sound can choose which
  25756. midi notes and channels can trigger it.
  25757. The SynthesiserSound is a passive class that just describes what the sound is -
  25758. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25759. more than one SynthesiserVoice to play the same sound at the same time.
  25760. @see Synthesiser, SynthesiserVoice
  25761. */
  25762. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25763. {
  25764. protected:
  25765. SynthesiserSound();
  25766. public:
  25767. /** Destructor. */
  25768. virtual ~SynthesiserSound();
  25769. /** Returns true if this sound should be played when a given midi note is pressed.
  25770. The Synthesiser will use this information when deciding which sounds to trigger
  25771. for a given note.
  25772. */
  25773. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25774. /** Returns true if the sound should be triggered by midi events on a given channel.
  25775. The Synthesiser will use this information when deciding which sounds to trigger
  25776. for a given note.
  25777. */
  25778. virtual bool appliesToChannel (const int midiChannel) = 0;
  25779. /**
  25780. */
  25781. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25782. juce_UseDebuggingNewOperator
  25783. };
  25784. /**
  25785. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25786. A voice plays a single sound at a time, and a synthesiser holds an array of
  25787. voices so that it can play polyphonically.
  25788. @see Synthesiser, SynthesiserSound
  25789. */
  25790. class JUCE_API SynthesiserVoice
  25791. {
  25792. public:
  25793. /** Creates a voice. */
  25794. SynthesiserVoice();
  25795. /** Destructor. */
  25796. virtual ~SynthesiserVoice();
  25797. /** Returns the midi note that this voice is currently playing.
  25798. Returns a value less than 0 if no note is playing.
  25799. */
  25800. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25801. /** Returns the sound that this voice is currently playing.
  25802. Returns 0 if it's not playing.
  25803. */
  25804. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25805. /** Must return true if this voice object is capable of playing the given sound.
  25806. If there are different classes of sound, and different classes of voice, a voice can
  25807. choose which ones it wants to take on.
  25808. A typical implementation of this method may just return true if there's only one type
  25809. of voice and sound, or it might check the type of the sound object passed-in and
  25810. see if it's one that it understands.
  25811. */
  25812. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25813. /** Called to start a new note.
  25814. This will be called during the rendering callback, so must be fast and thread-safe.
  25815. */
  25816. virtual void startNote (const int midiNoteNumber,
  25817. const float velocity,
  25818. SynthesiserSound* sound,
  25819. const int currentPitchWheelPosition) = 0;
  25820. /** Called to stop a note.
  25821. This will be called during the rendering callback, so must be fast and thread-safe.
  25822. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25823. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25824. and allow the synth to reassign it another sound.
  25825. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25826. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25827. finishes playing (during the rendering callback), it must make sure that it calls
  25828. clearCurrentNote().
  25829. */
  25830. virtual void stopNote (const bool allowTailOff) = 0;
  25831. /** Called to let the voice know that the pitch wheel has been moved.
  25832. This will be called during the rendering callback, so must be fast and thread-safe.
  25833. */
  25834. virtual void pitchWheelMoved (const int newValue) = 0;
  25835. /** Called to let the voice know that a midi controller has been moved.
  25836. This will be called during the rendering callback, so must be fast and thread-safe.
  25837. */
  25838. virtual void controllerMoved (const int controllerNumber,
  25839. const int newValue) = 0;
  25840. /** Renders the next block of data for this voice.
  25841. The output audio data must be added to the current contents of the buffer provided.
  25842. Only the region of the buffer between startSample and (startSample + numSamples)
  25843. should be altered by this method.
  25844. If the voice is currently silent, it should just return without doing anything.
  25845. If the sound that the voice is playing finishes during the course of this rendered
  25846. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25847. The size of the blocks that are rendered can change each time it is called, and may
  25848. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25849. the voice's methods will be called to tell it about note and controller events.
  25850. */
  25851. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25852. int startSample,
  25853. int numSamples) = 0;
  25854. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25855. midi channel.
  25856. If it's not currently playing, this will return false.
  25857. */
  25858. bool isPlayingChannel (const int midiChannel) const;
  25859. /** Changes the voice's reference sample rate.
  25860. The rate is set so that subclasses know the output rate and can set their pitch
  25861. accordingly.
  25862. This method is called by the synth, and subclasses can access the current rate with
  25863. the currentSampleRate member.
  25864. */
  25865. void setCurrentPlaybackSampleRate (const double newRate);
  25866. juce_UseDebuggingNewOperator
  25867. protected:
  25868. /** Returns the current target sample rate at which rendering is being done.
  25869. This is available for subclasses so they can pitch things correctly.
  25870. */
  25871. double getSampleRate() const throw() { return currentSampleRate; }
  25872. /** Resets the state of this voice after a sound has finished playing.
  25873. The subclass must call this when it finishes playing a note and becomes available
  25874. to play new ones.
  25875. It must either call it in the stopNote() method, or if the voice is tailing off,
  25876. then it should call it later during the renderNextBlock method, as soon as it
  25877. finishes its tail-off.
  25878. It can also be called at any time during the render callback if the sound happens
  25879. to have finished, e.g. if it's playing a sample and the sample finishes.
  25880. */
  25881. void clearCurrentNote();
  25882. private:
  25883. friend class Synthesiser;
  25884. double currentSampleRate;
  25885. int currentlyPlayingNote;
  25886. uint32 noteOnTime;
  25887. SynthesiserSound::Ptr currentlyPlayingSound;
  25888. };
  25889. /**
  25890. Base class for a musical device that can play sounds.
  25891. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25892. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25893. which can play back one of these sounds.
  25894. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25895. set of sounds, and a set of voices it can use to play them. If you only give it
  25896. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25897. have available.
  25898. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25899. events that go in will be scanned for note on/off messages, and these are used to
  25900. start and stop the voices playing the appropriate sounds.
  25901. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25902. noteOff() and other controller methods.
  25903. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25904. what the target playback rate is. This value is passed on to the voices so that
  25905. they can pitch their output correctly.
  25906. */
  25907. class JUCE_API Synthesiser
  25908. {
  25909. public:
  25910. /** Creates a new synthesiser.
  25911. You'll need to add some sounds and voices before it'll make any sound..
  25912. */
  25913. Synthesiser();
  25914. /** Destructor. */
  25915. virtual ~Synthesiser();
  25916. /** Deletes all voices. */
  25917. void clearVoices();
  25918. /** Returns the number of voices that have been added. */
  25919. int getNumVoices() const throw() { return voices.size(); }
  25920. /** Returns one of the voices that have been added. */
  25921. SynthesiserVoice* getVoice (const int index) const throw();
  25922. /** Adds a new voice to the synth.
  25923. All the voices should be the same class of object and are treated equally.
  25924. The object passed in will be managed by the synthesiser, which will delete
  25925. it later on when no longer needed. The caller should not retain a pointer to the
  25926. voice.
  25927. */
  25928. void addVoice (SynthesiserVoice* const newVoice);
  25929. /** Deletes one of the voices. */
  25930. void removeVoice (const int index);
  25931. /** Deletes all sounds. */
  25932. void clearSounds();
  25933. /** Returns the number of sounds that have been added to the synth. */
  25934. int getNumSounds() const throw() { return sounds.size(); }
  25935. /** Returns one of the sounds. */
  25936. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25937. /** Adds a new sound to the synthesiser.
  25938. The object passed in is reference counted, so will be deleted when it is removed
  25939. from the synthesiser, and when no voices are still using it.
  25940. */
  25941. void addSound (const SynthesiserSound::Ptr& newSound);
  25942. /** Removes and deletes one of the sounds. */
  25943. void removeSound (const int index);
  25944. /** If set to true, then the synth will try to take over an existing voice if
  25945. it runs out and needs to play another note.
  25946. The value of this boolean is passed into findFreeVoice(), so the result will
  25947. depend on the implementation of this method.
  25948. */
  25949. void setNoteStealingEnabled (const bool shouldStealNotes);
  25950. /** Returns true if note-stealing is enabled.
  25951. @see setNoteStealingEnabled
  25952. */
  25953. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25954. /** Triggers a note-on event.
  25955. The default method here will find all the sounds that want to be triggered by
  25956. this note/channel. For each sound, it'll try to find a free voice, and use the
  25957. voice to start playing the sound.
  25958. Subclasses might want to override this if they need a more complex algorithm.
  25959. This method will be called automatically according to the midi data passed into
  25960. renderNextBlock(), but may be called explicitly too.
  25961. */
  25962. virtual void noteOn (const int midiChannel,
  25963. const int midiNoteNumber,
  25964. const float velocity);
  25965. /** Triggers a note-off event.
  25966. This will turn off any voices that are playing a sound for the given note/channel.
  25967. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25968. (if they can do). If this is false, the notes will all be cut off immediately.
  25969. This method will be called automatically according to the midi data passed into
  25970. renderNextBlock(), but may be called explicitly too.
  25971. */
  25972. virtual void noteOff (const int midiChannel,
  25973. const int midiNoteNumber,
  25974. const bool allowTailOff);
  25975. /** Turns off all notes.
  25976. This will turn off any voices that are playing a sound on the given midi channel.
  25977. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25978. which channel they're playing.
  25979. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25980. (if they can do). If this is false, the notes will all be cut off immediately.
  25981. This method will be called automatically according to the midi data passed into
  25982. renderNextBlock(), but may be called explicitly too.
  25983. */
  25984. virtual void allNotesOff (const int midiChannel,
  25985. const bool allowTailOff);
  25986. /** Sends a pitch-wheel message.
  25987. This will send a pitch-wheel message to any voices that are playing sounds on
  25988. the given midi channel.
  25989. This method will be called automatically according to the midi data passed into
  25990. renderNextBlock(), but may be called explicitly too.
  25991. @param midiChannel the midi channel for the event
  25992. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25993. */
  25994. virtual void handlePitchWheel (const int midiChannel,
  25995. const int wheelValue);
  25996. /** Sends a midi controller message.
  25997. This will send a midi controller message to any voices that are playing sounds on
  25998. the given midi channel.
  25999. This method will be called automatically according to the midi data passed into
  26000. renderNextBlock(), but may be called explicitly too.
  26001. @param midiChannel the midi channel for the event
  26002. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  26003. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  26004. */
  26005. virtual void handleController (const int midiChannel,
  26006. const int controllerNumber,
  26007. const int controllerValue);
  26008. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  26009. render.
  26010. This value is propagated to the voices so that they can use it to render the correct
  26011. pitches.
  26012. */
  26013. void setCurrentPlaybackSampleRate (const double sampleRate);
  26014. /** Creates the next block of audio output.
  26015. This will process the next numSamples of data from all the voices, and add that output
  26016. to the audio block supplied, starting from the offset specified. Note that the
  26017. data will be added to the current contents of the buffer, so you should clear it
  26018. before calling this method if necessary.
  26019. The midi events in the inputMidi buffer are parsed for note and controller events,
  26020. and these are used to trigger the voices. Note that the startSample offset applies
  26021. both to the audio output buffer and the midi input buffer, so any midi events
  26022. with timestamps outside the specified region will be ignored.
  26023. */
  26024. void renderNextBlock (AudioSampleBuffer& outputAudio,
  26025. const MidiBuffer& inputMidi,
  26026. int startSample,
  26027. int numSamples);
  26028. juce_UseDebuggingNewOperator
  26029. protected:
  26030. /** This is used to control access to the rendering callback and the note trigger methods. */
  26031. CriticalSection lock;
  26032. OwnedArray <SynthesiserVoice> voices;
  26033. ReferenceCountedArray <SynthesiserSound> sounds;
  26034. /** The last pitch-wheel values for each midi channel. */
  26035. int lastPitchWheelValues [16];
  26036. /** Searches through the voices to find one that's not currently playing, and which
  26037. can play the given sound.
  26038. Returns 0 if all voices are busy and stealing isn't enabled.
  26039. This can be overridden to implement custom voice-stealing algorithms.
  26040. */
  26041. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  26042. const bool stealIfNoneAvailable) const;
  26043. /** Starts a specified voice playing a particular sound.
  26044. You'll probably never need to call this, it's used internally by noteOn(), but
  26045. may be needed by subclasses for custom behaviours.
  26046. */
  26047. void startVoice (SynthesiserVoice* const voice,
  26048. SynthesiserSound* const sound,
  26049. const int midiChannel,
  26050. const int midiNoteNumber,
  26051. const float velocity);
  26052. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  26053. int findFreeVoice (const bool) const { return 0; }
  26054. private:
  26055. double sampleRate;
  26056. uint32 lastNoteOnCounter;
  26057. bool shouldStealNotes;
  26058. Synthesiser (const Synthesiser&);
  26059. const Synthesiser& operator= (const Synthesiser&);
  26060. };
  26061. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  26062. /********* End of inlined file: juce_Synthesiser.h *********/
  26063. /**
  26064. A subclass of SynthesiserSound that represents a sampled audio clip.
  26065. This is a pretty basic sampler, and just attempts to load the whole audio stream
  26066. into memory.
  26067. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26068. give it some SampledSound objects to play.
  26069. @see SamplerVoice, Synthesiser, SynthesiserSound
  26070. */
  26071. class JUCE_API SamplerSound : public SynthesiserSound
  26072. {
  26073. public:
  26074. /** Creates a sampled sound from an audio reader.
  26075. This will attempt to load the audio from the source into memory and store
  26076. it in this object.
  26077. @param name a name for the sample
  26078. @param source the audio to load. This object can be safely deleted by the
  26079. caller after this constructor returns
  26080. @param midiNotes the set of midi keys that this sound should be played on. This
  26081. is used by the SynthesiserSound::appliesToNote() method
  26082. @param midiNoteForNormalPitch the midi note at which the sample should be played
  26083. with its natural rate. All other notes will be pitched
  26084. up or down relative to this one
  26085. @param attackTimeSecs the attack (fade-in) time, in seconds
  26086. @param releaseTimeSecs the decay (fade-out) time, in seconds
  26087. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  26088. source, in seconds
  26089. */
  26090. SamplerSound (const String& name,
  26091. AudioFormatReader& source,
  26092. const BitArray& midiNotes,
  26093. const int midiNoteForNormalPitch,
  26094. const double attackTimeSecs,
  26095. const double releaseTimeSecs,
  26096. const double maxSampleLengthSeconds);
  26097. /** Destructor. */
  26098. ~SamplerSound();
  26099. /** Returns the sample's name */
  26100. const String& getName() const throw() { return name; }
  26101. /** Returns the audio sample data.
  26102. This could be 0 if there was a problem loading it.
  26103. */
  26104. AudioSampleBuffer* getAudioData() const throw() { return data; }
  26105. bool appliesToNote (const int midiNoteNumber);
  26106. bool appliesToChannel (const int midiChannel);
  26107. juce_UseDebuggingNewOperator
  26108. private:
  26109. friend class SamplerVoice;
  26110. String name;
  26111. AudioSampleBuffer* data;
  26112. double sourceSampleRate;
  26113. BitArray midiNotes;
  26114. int length, attackSamples, releaseSamples;
  26115. int midiRootNote;
  26116. };
  26117. /**
  26118. A subclass of SynthesiserVoice that can play a SamplerSound.
  26119. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26120. give it some SampledSound objects to play.
  26121. @see SamplerSound, Synthesiser, SynthesiserVoice
  26122. */
  26123. class JUCE_API SamplerVoice : public SynthesiserVoice
  26124. {
  26125. public:
  26126. /** Creates a SamplerVoice.
  26127. */
  26128. SamplerVoice();
  26129. /** Destructor. */
  26130. ~SamplerVoice();
  26131. bool canPlaySound (SynthesiserSound* sound);
  26132. void startNote (const int midiNoteNumber,
  26133. const float velocity,
  26134. SynthesiserSound* sound,
  26135. const int currentPitchWheelPosition);
  26136. void stopNote (const bool allowTailOff);
  26137. void pitchWheelMoved (const int newValue);
  26138. void controllerMoved (const int controllerNumber,
  26139. const int newValue);
  26140. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  26141. juce_UseDebuggingNewOperator
  26142. private:
  26143. double pitchRatio;
  26144. double sourceSamplePosition;
  26145. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  26146. bool isInAttack, isInRelease;
  26147. };
  26148. #endif // __JUCE_SAMPLER_JUCEHEADER__
  26149. /********* End of inlined file: juce_Sampler.h *********/
  26150. #endif
  26151. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26152. #endif
  26153. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26154. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  26155. #ifdef __aeffect__
  26156. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26157. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26158. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26159. events to the list.
  26160. This is used by both the VST hosting code and the plugin wrapper.
  26161. */
  26162. class VSTMidiEventList
  26163. {
  26164. public:
  26165. VSTMidiEventList()
  26166. : events (0), numEventsUsed (0), numEventsAllocated (0)
  26167. {
  26168. }
  26169. ~VSTMidiEventList()
  26170. {
  26171. freeEvents();
  26172. }
  26173. void clear()
  26174. {
  26175. numEventsUsed = 0;
  26176. if (events != 0)
  26177. events->numEvents = 0;
  26178. }
  26179. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26180. {
  26181. ensureSize (numEventsUsed + 1);
  26182. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26183. events->numEvents = ++numEventsUsed;
  26184. if (numBytes <= 4)
  26185. {
  26186. if (e->type == kVstSysExType)
  26187. {
  26188. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26189. e->type = kVstMidiType;
  26190. e->byteSize = sizeof (VstMidiEvent);
  26191. e->noteLength = 0;
  26192. e->noteOffset = 0;
  26193. e->detune = 0;
  26194. e->noteOffVelocity = 0;
  26195. }
  26196. e->deltaFrames = frameOffset;
  26197. memcpy (e->midiData, midiData, numBytes);
  26198. }
  26199. else
  26200. {
  26201. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26202. if (se->type == kVstSysExType)
  26203. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26204. else
  26205. se->sysexDump = (char*) juce_malloc (numBytes);
  26206. memcpy (se->sysexDump, midiData, numBytes);
  26207. se->type = kVstSysExType;
  26208. se->byteSize = sizeof (VstMidiSysexEvent);
  26209. se->deltaFrames = frameOffset;
  26210. se->flags = 0;
  26211. se->dumpBytes = numBytes;
  26212. se->resvd1 = 0;
  26213. se->resvd2 = 0;
  26214. }
  26215. }
  26216. // Handy method to pull the events out of an event buffer supplied by the host
  26217. // or plugin.
  26218. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26219. {
  26220. for (int i = 0; i < events->numEvents; ++i)
  26221. {
  26222. const VstEvent* const e = events->events[i];
  26223. if (e != 0)
  26224. {
  26225. if (e->type == kVstMidiType)
  26226. {
  26227. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26228. 4, e->deltaFrames);
  26229. }
  26230. else if (e->type == kVstSysExType)
  26231. {
  26232. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26233. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26234. e->deltaFrames);
  26235. }
  26236. }
  26237. }
  26238. }
  26239. void ensureSize (int numEventsNeeded)
  26240. {
  26241. if (numEventsNeeded > numEventsAllocated)
  26242. {
  26243. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26244. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26245. if (events == 0)
  26246. events = (VstEvents*) juce_calloc (size);
  26247. else
  26248. events = (VstEvents*) juce_realloc (events, size);
  26249. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26250. {
  26251. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26252. (int) sizeof (VstMidiSysexEvent)));
  26253. e->type = kVstMidiType;
  26254. e->byteSize = sizeof (VstMidiEvent);
  26255. events->events[i] = (VstEvent*) e;
  26256. }
  26257. numEventsAllocated = numEventsNeeded;
  26258. }
  26259. }
  26260. void freeEvents()
  26261. {
  26262. if (events != 0)
  26263. {
  26264. for (int i = numEventsAllocated; --i >= 0;)
  26265. {
  26266. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26267. if (e->type == kVstSysExType)
  26268. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26269. juce_free (e);
  26270. }
  26271. juce_free (events);
  26272. events = 0;
  26273. numEventsUsed = 0;
  26274. numEventsAllocated = 0;
  26275. }
  26276. }
  26277. VstEvents* events;
  26278. private:
  26279. int numEventsUsed, numEventsAllocated;
  26280. };
  26281. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26282. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26283. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  26284. #endif
  26285. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26286. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26287. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26288. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26289. #if JUCE_PLUGINHOST_VST
  26290. /**
  26291. Implements a plugin format manager for VSTs.
  26292. */
  26293. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26294. {
  26295. public:
  26296. VSTPluginFormat();
  26297. ~VSTPluginFormat();
  26298. const String getName() const { return "VST"; }
  26299. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26300. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26301. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26302. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26303. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26304. bool doesPluginStillExist (const PluginDescription& desc);
  26305. const FileSearchPath getDefaultLocationsToSearch();
  26306. juce_UseDebuggingNewOperator
  26307. private:
  26308. VSTPluginFormat (const VSTPluginFormat&);
  26309. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26310. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26311. };
  26312. #endif
  26313. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26314. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26315. #endif
  26316. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26317. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26318. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26319. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26320. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  26321. /**
  26322. Implements a plugin format manager for AudioUnits.
  26323. */
  26324. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  26325. {
  26326. public:
  26327. AudioUnitPluginFormat();
  26328. ~AudioUnitPluginFormat();
  26329. const String getName() const { return "AudioUnit"; }
  26330. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26331. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26332. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26333. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26334. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26335. bool doesPluginStillExist (const PluginDescription& desc);
  26336. const FileSearchPath getDefaultLocationsToSearch();
  26337. juce_UseDebuggingNewOperator
  26338. private:
  26339. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  26340. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  26341. };
  26342. #endif
  26343. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26344. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  26345. #endif
  26346. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26347. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  26348. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26349. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26350. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  26351. // Sorry, this file is just a placeholder at the moment!...
  26352. /**
  26353. Implements a plugin format manager for DirectX plugins.
  26354. */
  26355. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  26356. {
  26357. public:
  26358. DirectXPluginFormat();
  26359. ~DirectXPluginFormat();
  26360. const String getName() const { return "DirectX"; }
  26361. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26362. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26363. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26364. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26365. const FileSearchPath getDefaultLocationsToSearch();
  26366. juce_UseDebuggingNewOperator
  26367. private:
  26368. DirectXPluginFormat (const DirectXPluginFormat&);
  26369. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  26370. };
  26371. #endif
  26372. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26373. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  26374. #endif
  26375. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26376. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  26377. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26378. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26379. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  26380. // Sorry, this file is just a placeholder at the moment!...
  26381. /**
  26382. Implements a plugin format manager for DirectX plugins.
  26383. */
  26384. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26385. {
  26386. public:
  26387. LADSPAPluginFormat();
  26388. ~LADSPAPluginFormat();
  26389. const String getName() const { return "LADSPA"; }
  26390. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26391. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26392. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26393. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26394. const FileSearchPath getDefaultLocationsToSearch();
  26395. juce_UseDebuggingNewOperator
  26396. private:
  26397. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26398. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26399. };
  26400. #endif
  26401. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26402. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26403. #endif
  26404. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26405. #endif
  26406. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26407. #endif
  26408. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26409. #endif
  26410. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26411. #endif
  26412. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26413. #endif
  26414. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26415. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26416. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26417. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26418. /**
  26419. Scans a directory for plugins, and adds them to a KnownPluginList.
  26420. To use one of these, create it and call scanNextFile() repeatedly, until
  26421. it returns false.
  26422. */
  26423. class JUCE_API PluginDirectoryScanner
  26424. {
  26425. public:
  26426. /**
  26427. Creates a scanner.
  26428. @param listToAddResultsTo this will get the new types added to it.
  26429. @param formatToLookFor this is the type of format that you want to look for
  26430. @param directoriesToSearch the path to search
  26431. @param searchRecursively true to search recursively
  26432. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26433. be used as a file to store the names of any plugins
  26434. that crash during initialisation. If there are
  26435. any plugins listed in it, then these will always
  26436. be scanned after all other possible files have
  26437. been tried - in this way, even if there's a few
  26438. dodgy plugins in your path, then a couple of rescans
  26439. will still manage to find all the proper plugins.
  26440. It's probably best to choose a file in the user's
  26441. application data directory (alongside your app's
  26442. settings file) for this. The file format it uses
  26443. is just a list of filenames of the modules that
  26444. failed.
  26445. */
  26446. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26447. AudioPluginFormat& formatToLookFor,
  26448. FileSearchPath directoriesToSearch,
  26449. const bool searchRecursively,
  26450. const File& deadMansPedalFile);
  26451. /** Destructor. */
  26452. ~PluginDirectoryScanner();
  26453. /** Tries the next likely-looking file.
  26454. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26455. re-tested if it's not already in the list, or if the file's modification
  26456. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26457. false, the file will always be reloaded and tested.
  26458. Returns false when there are no more files to try.
  26459. */
  26460. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26461. /** Returns the description of the plugin that will be scanned during the next
  26462. call to scanNextFile().
  26463. This is handy if you want to show the user which file is currently getting
  26464. scanned.
  26465. */
  26466. const String getNextPluginFileThatWillBeScanned() const throw();
  26467. /** Returns the estimated progress, between 0 and 1.
  26468. */
  26469. float getProgress() const { return progress; }
  26470. /** This returns a list of all the filenames of things that looked like being
  26471. a plugin file, but which failed to open for some reason.
  26472. */
  26473. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26474. juce_UseDebuggingNewOperator
  26475. private:
  26476. KnownPluginList& list;
  26477. AudioPluginFormat& format;
  26478. StringArray filesOrIdentifiersToScan;
  26479. File deadMansPedalFile;
  26480. StringArray failedFiles;
  26481. int nextIndex;
  26482. float progress;
  26483. const StringArray getDeadMansPedalFile() throw();
  26484. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26485. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26486. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26487. };
  26488. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26489. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26490. #endif
  26491. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26492. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26493. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26494. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26495. /********* Start of inlined file: juce_ListBox.h *********/
  26496. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26497. #define __JUCE_LISTBOX_JUCEHEADER__
  26498. class ListViewport;
  26499. /**
  26500. A subclass of this is used to drive a ListBox.
  26501. @see ListBox
  26502. */
  26503. class JUCE_API ListBoxModel
  26504. {
  26505. public:
  26506. /** Destructor. */
  26507. virtual ~ListBoxModel() {}
  26508. /** This has to return the number of items in the list.
  26509. @see ListBox::getNumRows()
  26510. */
  26511. virtual int getNumRows() = 0;
  26512. /** This method must be implemented to draw a row of the list.
  26513. */
  26514. virtual void paintListBoxItem (int rowNumber,
  26515. Graphics& g,
  26516. int width, int height,
  26517. bool rowIsSelected) = 0;
  26518. /** This is used to create or update a custom component to go in a row of the list.
  26519. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26520. and handle mouse clicks with listBoxItemClicked().
  26521. This method will be called whenever a custom component might need to be updated - e.g.
  26522. when the table is changed, or TableListBox::updateContent() is called.
  26523. If you don't need a custom component for the specified row, then return 0.
  26524. If you do want a custom component, and the existingComponentToUpdate is null, then
  26525. this method must create a suitable new component and return it.
  26526. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26527. by this method. In this case, the method must either update it to make sure it's correctly representing
  26528. the given row (which may be different from the one that the component was created for), or it can
  26529. delete this component and return a new one.
  26530. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26531. */
  26532. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26533. Component* existingComponentToUpdate);
  26534. /** This can be overridden to react to the user clicking on a row.
  26535. @see listBoxItemDoubleClicked
  26536. */
  26537. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26538. /** This can be overridden to react to the user double-clicking on a row.
  26539. @see listBoxItemClicked
  26540. */
  26541. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26542. /** This can be overridden to react to the user double-clicking on a part of the list where
  26543. there are no rows.
  26544. @see listBoxItemClicked
  26545. */
  26546. virtual void backgroundClicked();
  26547. /** Override this to be informed when rows are selected or deselected.
  26548. This will be called whenever a row is selected or deselected. If a range of
  26549. rows is selected all at once, this will just be called once for that event.
  26550. @param lastRowSelected the last row that the user selected. If no
  26551. rows are currently selected, this may be -1.
  26552. */
  26553. virtual void selectedRowsChanged (int lastRowSelected);
  26554. /** Override this to be informed when the delete key is pressed.
  26555. If no rows are selected when they press the key, this won't be called.
  26556. @param lastRowSelected the last row that had been selected when they pressed the
  26557. key - if there are multiple selections, this might not be
  26558. very useful
  26559. */
  26560. virtual void deleteKeyPressed (int lastRowSelected);
  26561. /** Override this to be informed when the return key is pressed.
  26562. If no rows are selected when they press the key, this won't be called.
  26563. @param lastRowSelected the last row that had been selected when they pressed the
  26564. key - if there are multiple selections, this might not be
  26565. very useful
  26566. */
  26567. virtual void returnKeyPressed (int lastRowSelected);
  26568. /** Override this to be informed when the list is scrolled.
  26569. This might be caused by the user moving the scrollbar, or by programmatic changes
  26570. to the list position.
  26571. */
  26572. virtual void listWasScrolled();
  26573. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26574. If this returns a non-empty name then when the user drags a row, the listbox will
  26575. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26576. a drag-and-drop operation, using this string as the source description, with the listbox
  26577. itself as the source component.
  26578. @see DragAndDropContainer::startDragging
  26579. */
  26580. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26581. };
  26582. /**
  26583. A list of items that can be scrolled vertically.
  26584. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26585. either paint each row of the list and respond to events via callbacks, or for
  26586. more specialised tasks, it can supply a custom component to fill each row.
  26587. @see ComboBox, TableListBox
  26588. */
  26589. class JUCE_API ListBox : public Component,
  26590. public SettableTooltipClient
  26591. {
  26592. public:
  26593. /** Creates a ListBox.
  26594. The model pointer passed-in can be null, in which case you can set it later
  26595. with setModel().
  26596. */
  26597. ListBox (const String& componentName,
  26598. ListBoxModel* const model);
  26599. /** Destructor. */
  26600. ~ListBox();
  26601. /** Changes the current data model to display. */
  26602. void setModel (ListBoxModel* const newModel);
  26603. /** Returns the current list model. */
  26604. ListBoxModel* getModel() const throw() { return model; }
  26605. /** Causes the list to refresh its content.
  26606. Call this when the number of rows in the list changes, or if you want it
  26607. to call refreshComponentForRow() on all the row components.
  26608. Be careful not to call it from a different thread, though, as it's not
  26609. thread-safe.
  26610. */
  26611. void updateContent();
  26612. /** Turns on multiple-selection of rows.
  26613. By default this is disabled.
  26614. When your row component gets clicked you'll need to call the
  26615. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26616. clicked and to get it to do the appropriate selection based on whether
  26617. the ctrl/shift keys are held down.
  26618. */
  26619. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26620. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26621. This function is here primarily for the ComboBox class to use, but might be
  26622. useful for some other purpose too.
  26623. */
  26624. void setMouseMoveSelectsRows (bool shouldSelect);
  26625. /** Selects a row.
  26626. If the row is already selected, this won't do anything.
  26627. @param rowNumber the row to select
  26628. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26629. the selected row is off-screen, it'll scroll to make
  26630. sure that row is on-screen
  26631. @param deselectOthersFirst if true and there are multiple selections, these will
  26632. first be deselected before this item is selected
  26633. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26634. deselectAllRows, selectRangeOfRows
  26635. */
  26636. void selectRow (const int rowNumber,
  26637. bool dontScrollToShowThisRow = false,
  26638. bool deselectOthersFirst = true);
  26639. /** Selects a set of rows.
  26640. This will add these rows to the current selection, so you might need to
  26641. clear the current selection first with deselectAllRows()
  26642. @param firstRow the first row to select (inclusive)
  26643. @param lastRow the last row to select (inclusive)
  26644. */
  26645. void selectRangeOfRows (int firstRow,
  26646. int lastRow);
  26647. /** Deselects a row.
  26648. If it's not currently selected, this will do nothing.
  26649. @see selectRow, deselectAllRows
  26650. */
  26651. void deselectRow (const int rowNumber);
  26652. /** Deselects any currently selected rows.
  26653. @see deselectRow
  26654. */
  26655. void deselectAllRows();
  26656. /** Selects or deselects a row.
  26657. If the row's currently selected, this deselects it, and vice-versa.
  26658. */
  26659. void flipRowSelection (const int rowNumber);
  26660. /** Returns a sparse set indicating the rows that are currently selected.
  26661. @see setSelectedRows
  26662. */
  26663. const SparseSet<int> getSelectedRows() const;
  26664. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26665. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26666. method will be called. If it's false, no notification will be sent to the model.
  26667. @see getSelectedRows
  26668. */
  26669. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26670. const bool sendNotificationEventToModel = true);
  26671. /** Checks whether a row is selected.
  26672. */
  26673. bool isRowSelected (const int rowNumber) const;
  26674. /** Returns the number of rows that are currently selected.
  26675. @see getSelectedRow, isRowSelected, getLastRowSelected
  26676. */
  26677. int getNumSelectedRows() const;
  26678. /** Returns the row number of a selected row.
  26679. This will return the row number of the Nth selected row. The row numbers returned will
  26680. be sorted in order from low to high.
  26681. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26682. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26683. selected
  26684. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26685. */
  26686. int getSelectedRow (const int index = 0) const;
  26687. /** Returns the last row that the user selected.
  26688. This isn't the same as the highest row number that is currently selected - if the user
  26689. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26690. If nothing is selected, it will return -1.
  26691. */
  26692. int getLastRowSelected() const;
  26693. /** Multiply-selects rows based on the modifier keys.
  26694. If no modifier keys are down, this will select the given row and
  26695. deselect any others.
  26696. If the ctrl (or command on the Mac) key is down, it'll flip the
  26697. state of the selected row.
  26698. If the shift key is down, it'll select up to the given row from the
  26699. last row selected.
  26700. @see selectRow
  26701. */
  26702. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26703. const ModifierKeys& modifiers);
  26704. /** Scrolls the list to a particular position.
  26705. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26706. 1.0 scrolls to the bottom.
  26707. If the total number of rows all fit onto the screen at once, then this
  26708. method won't do anything.
  26709. @see getVerticalPosition
  26710. */
  26711. void setVerticalPosition (const double newProportion);
  26712. /** Returns the current vertical position as a proportion of the total.
  26713. This can be used in conjunction with setVerticalPosition() to save and restore
  26714. the list's position. It returns a value in the range 0 to 1.
  26715. @see setVerticalPosition
  26716. */
  26717. double getVerticalPosition() const;
  26718. /** Scrolls if necessary to make sure that a particular row is visible.
  26719. */
  26720. void scrollToEnsureRowIsOnscreen (const int row);
  26721. /** Returns a pointer to the scrollbar.
  26722. (Unlikely to be useful for most people).
  26723. */
  26724. ScrollBar* getVerticalScrollBar() const throw();
  26725. /** Returns a pointer to the scrollbar.
  26726. (Unlikely to be useful for most people).
  26727. */
  26728. ScrollBar* getHorizontalScrollBar() const throw();
  26729. /** Finds the row index that contains a given x,y position.
  26730. The position is relative to the ListBox's top-left.
  26731. If no row exists at this position, the method will return -1.
  26732. @see getComponentForRowNumber
  26733. */
  26734. int getRowContainingPosition (const int x, const int y) const throw();
  26735. /** Finds a row index that would be the most suitable place to insert a new
  26736. item for a given position.
  26737. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26738. because it lets you easily choose the best position to insert the item that
  26739. they drop, based on where they drop it.
  26740. If the position is out of range, this will return -1. If the position is
  26741. beyond the end of the list, it will return getNumRows() to indicate the end
  26742. of the list.
  26743. @see getComponentForRowNumber
  26744. */
  26745. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26746. /** Returns the position of one of the rows, relative to the top-left of
  26747. the listbox.
  26748. This may be off-screen, and the range of the row number that is passed-in is
  26749. not checked to see if it's a valid row.
  26750. */
  26751. const Rectangle getRowPosition (const int rowNumber,
  26752. const bool relativeToComponentTopLeft) const throw();
  26753. /** Finds the row component for a given row in the list.
  26754. The component returned will have been created using createRowComponent().
  26755. If the component for this row is off-screen or if the row is out-of-range,
  26756. this will return 0.
  26757. @see getRowContainingPosition
  26758. */
  26759. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26760. /** Returns the row number that the given component represents.
  26761. If the component isn't one of the list's rows, this will return -1.
  26762. */
  26763. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26764. /** Returns the width of a row (which may be less than the width of this component
  26765. if there's a scrollbar).
  26766. */
  26767. int getVisibleRowWidth() const throw();
  26768. /** Sets the height of each row in the list.
  26769. The default height is 22 pixels.
  26770. @see getRowHeight
  26771. */
  26772. void setRowHeight (const int newHeight);
  26773. /** Returns the height of a row in the list.
  26774. @see setRowHeight
  26775. */
  26776. int getRowHeight() const throw() { return rowHeight; }
  26777. /** Returns the number of rows actually visible.
  26778. This is the number of whole rows which will fit on-screen, so the value might
  26779. be more than the actual number of rows in the list.
  26780. */
  26781. int getNumRowsOnScreen() const throw();
  26782. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26783. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26784. methods.
  26785. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26786. */
  26787. enum ColourIds
  26788. {
  26789. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26790. Make this transparent if you don't want the background to be filled. */
  26791. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26792. Make this transparent to not have an outline. */
  26793. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26794. };
  26795. /** Sets the thickness of a border that will be drawn around the box.
  26796. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26797. @see outlineColourId
  26798. */
  26799. void setOutlineThickness (const int outlineThickness);
  26800. /** Returns the thickness of outline that will be drawn around the listbox.
  26801. @see setOutlineColour
  26802. */
  26803. int getOutlineThickness() const throw() { return outlineThickness; }
  26804. /** Sets a component that the list should use as a header.
  26805. This will position the given component at the top of the list, maintaining the
  26806. height of the component passed-in, but rescaling it horizontally to match the
  26807. width of the items in the listbox.
  26808. The component will be deleted when setHeaderComponent() is called with a
  26809. different component, or when the listbox is deleted.
  26810. */
  26811. void setHeaderComponent (Component* const newHeaderComponent);
  26812. /** Changes the width of the rows in the list.
  26813. This can be used to make the list's row components wider than the list itself - the
  26814. width of the rows will be either the width of the list or this value, whichever is
  26815. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26816. appear.
  26817. The default value for this is 0, which means that the rows will always
  26818. be the same width as the list.
  26819. */
  26820. void setMinimumContentWidth (const int newMinimumWidth);
  26821. /** Returns the space currently available for the row items, taking into account
  26822. borders, scrollbars, etc.
  26823. */
  26824. int getVisibleContentWidth() const throw();
  26825. /** Repaints one of the rows.
  26826. This is a lightweight alternative to calling updateContent, and just causes a
  26827. repaint of the row's area.
  26828. */
  26829. void repaintRow (const int rowNumber) throw();
  26830. /** This fairly obscure method creates an image that just shows the currently
  26831. selected row components.
  26832. It's a handy method for doing drag-and-drop, as it can be passed to the
  26833. DragAndDropContainer for use as the drag image.
  26834. Note that it will make the row components temporarily invisible, so if you're
  26835. using custom components this could affect them if they're sensitive to that
  26836. sort of thing.
  26837. @see Component::createComponentSnapshot
  26838. */
  26839. Image* createSnapshotOfSelectedRows();
  26840. /** Returns the viewport that this ListBox uses.
  26841. You may need to use this to change parameters such as whether scrollbars
  26842. are shown, etc.
  26843. */
  26844. Viewport* getViewport() const throw();
  26845. /** @internal */
  26846. bool keyPressed (const KeyPress& key);
  26847. /** @internal */
  26848. bool keyStateChanged();
  26849. /** @internal */
  26850. void paint (Graphics& g);
  26851. /** @internal */
  26852. void paintOverChildren (Graphics& g);
  26853. /** @internal */
  26854. void resized();
  26855. /** @internal */
  26856. void visibilityChanged();
  26857. /** @internal */
  26858. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26859. /** @internal */
  26860. void mouseMove (const MouseEvent&);
  26861. /** @internal */
  26862. void mouseExit (const MouseEvent&);
  26863. /** @internal */
  26864. void mouseUp (const MouseEvent&);
  26865. /** @internal */
  26866. void colourChanged();
  26867. juce_UseDebuggingNewOperator
  26868. private:
  26869. friend class ListViewport;
  26870. friend class TableListBox;
  26871. ListBoxModel* model;
  26872. ListViewport* viewport;
  26873. Component* headerComponent;
  26874. int totalItems, rowHeight, minimumRowWidth;
  26875. int outlineThickness;
  26876. int lastMouseX, lastMouseY, lastRowSelected;
  26877. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26878. SparseSet <int> selected;
  26879. void selectRowInternal (const int rowNumber,
  26880. bool dontScrollToShowThisRow,
  26881. bool deselectOthersFirst,
  26882. bool isMouseClick);
  26883. ListBox (const ListBox&);
  26884. const ListBox& operator= (const ListBox&);
  26885. };
  26886. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26887. /********* End of inlined file: juce_ListBox.h *********/
  26888. /********* Start of inlined file: juce_TextButton.h *********/
  26889. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26890. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26891. /**
  26892. A button that uses the standard lozenge-shaped background with a line of
  26893. text on it.
  26894. @see Button, DrawableButton
  26895. */
  26896. class JUCE_API TextButton : public Button
  26897. {
  26898. public:
  26899. /** Creates a TextButton.
  26900. @param buttonName the text to put in the button (the component's name is also
  26901. initially set to this string, but these can be changed later
  26902. using the setName() and setButtonText() methods)
  26903. @param toolTip an optional string to use as a toolip
  26904. @see Button
  26905. */
  26906. TextButton (const String& buttonName,
  26907. const String& toolTip = String::empty);
  26908. /** Destructor. */
  26909. ~TextButton();
  26910. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26911. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26912. methods.
  26913. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26914. */
  26915. enum ColourIds
  26916. {
  26917. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26918. 'off'). The look-and-feel class might re-interpret this to add
  26919. effects, etc. */
  26920. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26921. 'on'). The look-and-feel class might re-interpret this to add
  26922. effects, etc. */
  26923. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26924. };
  26925. /** Resizes the button to fit neatly around its current text.
  26926. If newHeight is >= 0, the button's height will be changed to this
  26927. value. If it's less than zero, its height will be unaffected.
  26928. */
  26929. void changeWidthToFitText (const int newHeight = -1);
  26930. /** This can be overridden to use different fonts than the default one.
  26931. Note that you'll need to set the font's size appropriately, too.
  26932. */
  26933. virtual const Font getFont();
  26934. juce_UseDebuggingNewOperator
  26935. protected:
  26936. /** @internal */
  26937. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26938. /** @internal */
  26939. void colourChanged();
  26940. private:
  26941. TextButton (const TextButton&);
  26942. const TextButton& operator= (const TextButton&);
  26943. };
  26944. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26945. /********* End of inlined file: juce_TextButton.h *********/
  26946. /**
  26947. A component displaying a list of plugins, with options to scan for them,
  26948. add, remove and sort them.
  26949. */
  26950. class JUCE_API PluginListComponent : public Component,
  26951. public ListBoxModel,
  26952. public ChangeListener,
  26953. public ButtonListener,
  26954. public Timer
  26955. {
  26956. public:
  26957. /**
  26958. Creates the list component.
  26959. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26960. The properties file, if supplied, is used to store the user's last search paths.
  26961. */
  26962. PluginListComponent (KnownPluginList& listToRepresent,
  26963. const File& deadMansPedalFile,
  26964. PropertiesFile* const propertiesToUse);
  26965. /** Destructor. */
  26966. ~PluginListComponent();
  26967. /** @internal */
  26968. void resized();
  26969. /** @internal */
  26970. bool isInterestedInFileDrag (const StringArray& files);
  26971. /** @internal */
  26972. void filesDropped (const StringArray& files, int, int);
  26973. /** @internal */
  26974. int getNumRows();
  26975. /** @internal */
  26976. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26977. /** @internal */
  26978. void deleteKeyPressed (int lastRowSelected);
  26979. /** @internal */
  26980. void buttonClicked (Button* b);
  26981. /** @internal */
  26982. void changeListenerCallback (void*);
  26983. /** @internal */
  26984. void timerCallback();
  26985. juce_UseDebuggingNewOperator
  26986. private:
  26987. KnownPluginList& list;
  26988. File deadMansPedalFile;
  26989. ListBox* listBox;
  26990. TextButton* optionsButton;
  26991. PropertiesFile* propertiesToUse;
  26992. int typeToScan;
  26993. void scanFor (AudioPluginFormat* format);
  26994. PluginListComponent (const PluginListComponent&);
  26995. const PluginListComponent& operator= (const PluginListComponent&);
  26996. };
  26997. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26998. /********* End of inlined file: juce_PluginListComponent.h *********/
  26999. #endif
  27000. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27001. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27002. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27003. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27004. /********* Start of inlined file: juce_AudioFormat.h *********/
  27005. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27006. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  27007. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  27008. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27009. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27010. /**
  27011. Writes samples to an audio file stream.
  27012. A subclass that writes a specific type of audio format will be created by
  27013. an AudioFormat object.
  27014. After creating one of these with the AudioFormat::createWriterFor() method
  27015. you can call its write() method to store the samples, and then delete it.
  27016. @see AudioFormat, AudioFormatReader
  27017. */
  27018. class JUCE_API AudioFormatWriter
  27019. {
  27020. protected:
  27021. /** Creates an AudioFormatWriter object.
  27022. @param destStream the stream to write to - this will be deleted
  27023. by this object when it is no longer needed
  27024. @param formatName the description that will be returned by the getFormatName()
  27025. method
  27026. @param sampleRate the sample rate to use - the base class just stores
  27027. this value, it doesn't do anything with it
  27028. @param numberOfChannels the number of channels to write - the base class just stores
  27029. this value, it doesn't do anything with it
  27030. @param bitsPerSample the bit depth of the stream - the base class just stores
  27031. this value, it doesn't do anything with it
  27032. */
  27033. AudioFormatWriter (OutputStream* const destStream,
  27034. const String& formatName,
  27035. const double sampleRate,
  27036. const unsigned int numberOfChannels,
  27037. const unsigned int bitsPerSample);
  27038. public:
  27039. /** Destructor. */
  27040. virtual ~AudioFormatWriter();
  27041. /** Returns a description of what type of format this is.
  27042. E.g. "AIFF file"
  27043. */
  27044. const String getFormatName() const throw() { return formatName; }
  27045. /** Writes a set of samples to the audio stream.
  27046. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27047. can use AudioSampleBuffer::writeToAudioWriter().
  27048. @param samplesToWrite an array of arrays containing the sample data for
  27049. each channel to write. This is a zero-terminated
  27050. array of arrays, and can contain a different number
  27051. of channels than the actual stream uses, and the
  27052. writer should do its best to cope with this.
  27053. If the format is fixed-point, each channel will be formatted
  27054. as an array of signed integers using the full 32-bit
  27055. range -0x80000000 to 0x7fffffff, regardless of the source's
  27056. bit-depth. If it is a floating-point format, you should treat
  27057. the arrays as arrays of floats, and just cast it to an (int**)
  27058. to pass it into the method.
  27059. @param numSamples the number of samples to write
  27060. */
  27061. virtual bool write (const int** samplesToWrite,
  27062. int numSamples) = 0;
  27063. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27064. the output.
  27065. This will take care of any floating-point conversion that's required to convert
  27066. between the two formats. It won't deal with sample-rate conversion, though.
  27067. If numSamplesToRead < 0, it will write the entire length of the reader.
  27068. @returns false if it can't read or write properly during the operation
  27069. */
  27070. bool writeFromAudioReader (AudioFormatReader& reader,
  27071. int64 startSample,
  27072. int64 numSamplesToRead);
  27073. /** Reads some samples from an AudioSource, and writes these to the output.
  27074. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27075. @param source the source to read from
  27076. @param numSamplesToRead total number of samples to read and write
  27077. @param samplesPerBlock the maximum number of samples to fetch from the source
  27078. @returns false if it can't read or write properly during the operation
  27079. */
  27080. bool writeFromAudioSource (AudioSource& source,
  27081. int numSamplesToRead,
  27082. const int samplesPerBlock = 2048);
  27083. /** Returns the sample rate being used. */
  27084. double getSampleRate() const throw() { return sampleRate; }
  27085. /** Returns the number of channels being written. */
  27086. int getNumChannels() const throw() { return numChannels; }
  27087. /** Returns the bit-depth of the data being written. */
  27088. int getBitsPerSample() const throw() { return bitsPerSample; }
  27089. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27090. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27091. juce_UseDebuggingNewOperator
  27092. protected:
  27093. /** The sample rate of the stream. */
  27094. double sampleRate;
  27095. /** The number of channels being written to the stream. */
  27096. unsigned int numChannels;
  27097. /** The bit depth of the file. */
  27098. unsigned int bitsPerSample;
  27099. /** True if it's a floating-point format, false if it's fixed-point. */
  27100. bool usesFloatingPointData;
  27101. /** The output stream for Use by subclasses. */
  27102. OutputStream* output;
  27103. private:
  27104. String formatName;
  27105. };
  27106. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27107. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  27108. /**
  27109. Subclasses of AudioFormat are used to read and write different audio
  27110. file formats.
  27111. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27112. */
  27113. class JUCE_API AudioFormat
  27114. {
  27115. public:
  27116. /** Destructor. */
  27117. virtual ~AudioFormat();
  27118. /** Returns the name of this format.
  27119. e.g. "WAV file" or "AIFF file"
  27120. */
  27121. const String& getFormatName() const;
  27122. /** Returns all the file extensions that might apply to a file of this format.
  27123. The first item will be the one that's preferred when creating a new file.
  27124. So for a wav file this might just return ".wav"; for an AIFF file it might
  27125. return two items, ".aif" and ".aiff"
  27126. */
  27127. const StringArray& getFileExtensions() const;
  27128. /** Returns true if this the given file can be read by this format.
  27129. Subclasses shouldn't do too much work here, just check the extension or
  27130. file type. The base class implementation just checks the file's extension
  27131. against one of the ones that was registered in the constructor.
  27132. */
  27133. virtual bool canHandleFile (const File& fileToTest);
  27134. /** Returns a set of sample rates that the format can read and write. */
  27135. virtual const Array <int> getPossibleSampleRates() = 0;
  27136. /** Returns a set of bit depths that the format can read and write. */
  27137. virtual const Array <int> getPossibleBitDepths() = 0;
  27138. /** Returns true if the format can do 2-channel audio. */
  27139. virtual bool canDoStereo() = 0;
  27140. /** Returns true if the format can do 1-channel audio. */
  27141. virtual bool canDoMono() = 0;
  27142. /** Returns true if the format uses compressed data. */
  27143. virtual bool isCompressed();
  27144. /** Returns a list of different qualities that can be used when writing.
  27145. Non-compressed formats will just return an empty array, but for something
  27146. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27147. When calling createWriterFor(), an index from this array is passed in to
  27148. tell the format which option is required.
  27149. */
  27150. virtual const StringArray getQualityOptions();
  27151. /** Tries to create an object that can read from a stream containing audio
  27152. data in this format.
  27153. The reader object that is returned can be used to read from the stream, and
  27154. should then be deleted by the caller.
  27155. @param sourceStream the stream to read from - the AudioFormatReader object
  27156. that is returned will delete this stream when it no longer
  27157. needs it.
  27158. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27159. should delete the stream object that was passed-in. (If a valid
  27160. reader is returned, it will always be in charge of deleting the
  27161. stream, so this parameter is ignored)
  27162. @see AudioFormatReader
  27163. */
  27164. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27165. const bool deleteStreamIfOpeningFails) = 0;
  27166. /** Tries to create an object that can write to a stream with this audio format.
  27167. The writer object that is returned can be used to write to the stream, and
  27168. should then be deleted by the caller.
  27169. If the stream can't be created for some reason (e.g. the parameters passed in
  27170. here aren't suitable), this will return 0.
  27171. @param streamToWriteTo the stream that the data will go to - this will be
  27172. deleted by the AudioFormatWriter object when it's no longer
  27173. needed. If no AudioFormatWriter can be created by this method,
  27174. the stream will NOT be deleted, so that the caller can re-use it
  27175. to try to open a different format, etc
  27176. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27177. returned by getPossibleSampleRates()
  27178. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27179. the choice will depend on the results of canDoMono() and
  27180. canDoStereo()
  27181. @param bitsPerSample the bits per sample to use - this must be one of the values
  27182. returned by getPossibleBitDepths()
  27183. @param metadataValues a set of metadata values that the writer should try to write
  27184. to the stream. Exactly what these are depends on the format,
  27185. and the subclass doesn't actually have to do anything with
  27186. them if it doesn't want to. Have a look at the specific format
  27187. implementation classes to see possible values that can be
  27188. used
  27189. @param qualityOptionIndex the index of one of compression qualities returned by the
  27190. getQualityOptions() method. If there aren't any quality options
  27191. for this format, just pass 0 in this parameter, as it'll be
  27192. ignored
  27193. @see AudioFormatWriter
  27194. */
  27195. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27196. double sampleRateToUse,
  27197. unsigned int numberOfChannels,
  27198. int bitsPerSample,
  27199. const StringPairArray& metadataValues,
  27200. int qualityOptionIndex) = 0;
  27201. protected:
  27202. /** Creates an AudioFormat object.
  27203. @param formatName this sets the value that will be returned by getFormatName()
  27204. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27205. be returned by getFileExtension()
  27206. */
  27207. AudioFormat (const String& formatName,
  27208. const tchar** const fileExtensions);
  27209. private:
  27210. String formatName;
  27211. StringArray fileExtensions;
  27212. };
  27213. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27214. /********* End of inlined file: juce_AudioFormat.h *********/
  27215. /**
  27216. Reads and Writes WAV format audio files.
  27217. @see AudioFormat
  27218. */
  27219. class JUCE_API WavAudioFormat : public AudioFormat
  27220. {
  27221. public:
  27222. /** Creates a format object. */
  27223. WavAudioFormat();
  27224. /** Destructor. */
  27225. ~WavAudioFormat();
  27226. /** Metadata property name used by wav readers and writers for adding
  27227. a BWAV chunk to the file.
  27228. @see AudioFormatReader::metadataValues, createWriterFor
  27229. */
  27230. static const tchar* const bwavDescription;
  27231. /** Metadata property name used by wav readers and writers for adding
  27232. a BWAV chunk to the file.
  27233. @see AudioFormatReader::metadataValues, createWriterFor
  27234. */
  27235. static const tchar* const bwavOriginator;
  27236. /** Metadata property name used by wav readers and writers for adding
  27237. a BWAV chunk to the file.
  27238. @see AudioFormatReader::metadataValues, createWriterFor
  27239. */
  27240. static const tchar* const bwavOriginatorRef;
  27241. /** Metadata property name used by wav readers and writers for adding
  27242. a BWAV chunk to the file.
  27243. Date format is: yyyy-mm-dd
  27244. @see AudioFormatReader::metadataValues, createWriterFor
  27245. */
  27246. static const tchar* const bwavOriginationDate;
  27247. /** Metadata property name used by wav readers and writers for adding
  27248. a BWAV chunk to the file.
  27249. Time format is: hh-mm-ss
  27250. @see AudioFormatReader::metadataValues, createWriterFor
  27251. */
  27252. static const tchar* const bwavOriginationTime;
  27253. /** Metadata property name used by wav readers and writers for adding
  27254. a BWAV chunk to the file.
  27255. This is the number of samples from the start of an edit that the
  27256. file is supposed to begin at. Seems like an obvious mistake to
  27257. only allow a file to occur in an edit once, but that's the way
  27258. it is..
  27259. @see AudioFormatReader::metadataValues, createWriterFor
  27260. */
  27261. static const tchar* const bwavTimeReference;
  27262. /** Metadata property name used by wav readers and writers for adding
  27263. a BWAV chunk to the file.
  27264. This is a
  27265. @see AudioFormatReader::metadataValues, createWriterFor
  27266. */
  27267. static const tchar* const bwavCodingHistory;
  27268. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27269. This just makes it easier than using the property names directly, and it
  27270. fills out the time and date in the right format.
  27271. */
  27272. static const StringPairArray createBWAVMetadata (const String& description,
  27273. const String& originator,
  27274. const String& originatorRef,
  27275. const Time& dateAndTime,
  27276. const int64 timeReferenceSamples,
  27277. const String& codingHistory);
  27278. const Array <int> getPossibleSampleRates();
  27279. const Array <int> getPossibleBitDepths();
  27280. bool canDoStereo();
  27281. bool canDoMono();
  27282. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27283. const bool deleteStreamIfOpeningFails);
  27284. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27285. double sampleRateToUse,
  27286. unsigned int numberOfChannels,
  27287. int bitsPerSample,
  27288. const StringPairArray& metadataValues,
  27289. int qualityOptionIndex);
  27290. /** Utility function to replace the metadata in a wav file with a new set of values.
  27291. If possible, this cheats by overwriting just the metadata region of the file, rather
  27292. than by copying the whole file again.
  27293. */
  27294. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  27295. juce_UseDebuggingNewOperator
  27296. };
  27297. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27298. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27299. #endif
  27300. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27301. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  27302. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27303. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27304. /**
  27305. Reads and Writes AIFF format audio files.
  27306. @see AudioFormat
  27307. */
  27308. class JUCE_API AiffAudioFormat : public AudioFormat
  27309. {
  27310. public:
  27311. /** Creates an format object. */
  27312. AiffAudioFormat();
  27313. /** Destructor. */
  27314. ~AiffAudioFormat();
  27315. const Array <int> getPossibleSampleRates();
  27316. const Array <int> getPossibleBitDepths();
  27317. bool canDoStereo();
  27318. bool canDoMono();
  27319. #if JUCE_MAC
  27320. bool canHandleFile (const File& fileToTest);
  27321. #endif
  27322. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27323. const bool deleteStreamIfOpeningFails);
  27324. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27325. double sampleRateToUse,
  27326. unsigned int numberOfChannels,
  27327. int bitsPerSample,
  27328. const StringPairArray& metadataValues,
  27329. int qualityOptionIndex);
  27330. juce_UseDebuggingNewOperator
  27331. };
  27332. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27333. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  27334. #endif
  27335. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27336. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27337. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27338. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27339. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27340. /**
  27341. Reads and writes the Ogg-Vorbis audio format.
  27342. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27343. and make sure your include search path and library search path are set up to find
  27344. the Vorbis and Ogg header files and static libraries.
  27345. @see AudioFormat,
  27346. */
  27347. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27348. {
  27349. public:
  27350. OggVorbisAudioFormat();
  27351. ~OggVorbisAudioFormat();
  27352. const Array <int> getPossibleSampleRates();
  27353. const Array <int> getPossibleBitDepths();
  27354. bool canDoStereo();
  27355. bool canDoMono();
  27356. bool isCompressed();
  27357. const StringArray getQualityOptions();
  27358. /** Tries to estimate the quality level of an ogg file based on its size.
  27359. If it can't read the file for some reason, this will just return 1 (medium quality),
  27360. otherwise it will return the approximate quality setting that would have been used
  27361. to create the file.
  27362. @see getQualityOptions
  27363. */
  27364. int estimateOggFileQuality (const File& source);
  27365. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27366. const bool deleteStreamIfOpeningFails);
  27367. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27368. double sampleRateToUse,
  27369. unsigned int numberOfChannels,
  27370. int bitsPerSample,
  27371. const StringPairArray& metadataValues,
  27372. int qualityOptionIndex);
  27373. juce_UseDebuggingNewOperator
  27374. };
  27375. #endif
  27376. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27377. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27378. #endif
  27379. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27380. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27381. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27382. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27383. #if JUCE_QUICKTIME
  27384. /**
  27385. Uses QuickTime to read the audio track a movie or media file.
  27386. As well as QuickTime movies, this should also manage to open other audio
  27387. files that quicktime can understand, like mp3, m4a, etc.
  27388. @see AudioFormat
  27389. */
  27390. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27391. {
  27392. public:
  27393. /** Creates a format object. */
  27394. QuickTimeAudioFormat();
  27395. /** Destructor. */
  27396. ~QuickTimeAudioFormat();
  27397. const Array <int> getPossibleSampleRates();
  27398. const Array <int> getPossibleBitDepths();
  27399. bool canDoStereo();
  27400. bool canDoMono();
  27401. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27402. const bool deleteStreamIfOpeningFails);
  27403. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27404. double sampleRateToUse,
  27405. unsigned int numberOfChannels,
  27406. int bitsPerSample,
  27407. const StringPairArray& metadataValues,
  27408. int qualityOptionIndex);
  27409. juce_UseDebuggingNewOperator
  27410. };
  27411. #endif
  27412. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27413. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27414. #endif
  27415. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27416. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  27417. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27418. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27419. /**
  27420. */
  27421. class AudioCDBurner
  27422. {
  27423. public:
  27424. /** Returns a list of available optical drives.
  27425. Use openDevice() to open one of the items from this list.
  27426. */
  27427. static const StringArray findAvailableDevices();
  27428. /** Tries to open one of the optical drives.
  27429. The deviceIndex is an index into the array returned by findAvailableDevices().
  27430. */
  27431. static AudioCDBurner* openDevice (const int deviceIndex);
  27432. /** Destructor. */
  27433. ~AudioCDBurner();
  27434. /** Returns true if there's a writable disk in the drive.
  27435. */
  27436. bool isDiskPresent() const;
  27437. /** Returns the number of free blocks on the disk.
  27438. There are 75 blocks per second, at 44100Hz.
  27439. */
  27440. int getNumAvailableAudioBlocks() const;
  27441. /** Adds a track to be written.
  27442. The source passed-in here will be kept by this object, and it will
  27443. be used and deleted at some point in the future, either during the
  27444. burn() method or when this AudioCDBurner object is deleted. Your caller
  27445. method shouldn't keep a reference to it or use it again after passing
  27446. it in here.
  27447. */
  27448. bool addAudioTrack (AudioSource* source, int numSamples);
  27449. /**
  27450. Return true to cancel the current burn operation
  27451. */
  27452. class BurnProgressListener
  27453. {
  27454. public:
  27455. BurnProgressListener() throw() {}
  27456. virtual ~BurnProgressListener() {}
  27457. /** Called at intervals to report on the progress of the AudioCDBurner.
  27458. To cancel the burn, return true from this.
  27459. */
  27460. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27461. };
  27462. const String burn (BurnProgressListener* listener,
  27463. const bool ejectDiscAfterwards,
  27464. const bool peformFakeBurnForTesting);
  27465. juce_UseDebuggingNewOperator
  27466. private:
  27467. AudioCDBurner (const int deviceIndex);
  27468. void* internal;
  27469. };
  27470. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27471. /********* End of inlined file: juce_AudioCDBurner.h *********/
  27472. #endif
  27473. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27474. /********* Start of inlined file: juce_AudioCDReader.h *********/
  27475. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27476. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27477. #if JUCE_MAC
  27478. #endif
  27479. /**
  27480. A type of AudioFormatReader that reads from an audio CD.
  27481. One of these can be used to read a CD as if it's one big audio stream. Use the
  27482. getPositionOfTrackStart() method to find where the individual tracks are
  27483. within the stream.
  27484. @see AudioFormatReader
  27485. */
  27486. class JUCE_API AudioCDReader : public AudioFormatReader
  27487. {
  27488. public:
  27489. /** Returns a list of names of Audio CDs currently available for reading.
  27490. If there's a CD drive but no CD in it, this might return an empty list, or
  27491. possibly a device that can be opened but which has no tracks, depending
  27492. on the platform.
  27493. @see createReaderForCD
  27494. */
  27495. static const StringArray getAvailableCDNames();
  27496. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27497. @param index the index of one of the available CDs - use getAvailableCDNames()
  27498. to find out how many there are.
  27499. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27500. caller will be responsible for deleting the object returned.
  27501. */
  27502. static AudioCDReader* createReaderForCD (const int index);
  27503. /** Destructor. */
  27504. ~AudioCDReader();
  27505. /** Implementation of the AudioFormatReader method. */
  27506. bool read (int** destSamples,
  27507. int64 startSampleInFile,
  27508. int numSamples);
  27509. /** Checks whether the CD has been removed from the drive.
  27510. */
  27511. bool isCDStillPresent() const;
  27512. /** Returns the total number of tracks (audio + data).
  27513. */
  27514. int getNumTracks() const;
  27515. /** Finds the sample offset of the start of a track.
  27516. @param trackNum the track number, where 0 is the first track.
  27517. */
  27518. int getPositionOfTrackStart (int trackNum) const;
  27519. /** Returns true if a given track is an audio track.
  27520. @param trackNum the track number, where 0 is the first track.
  27521. */
  27522. bool isTrackAudio (int trackNum) const;
  27523. /** Refreshes the object's table of contents.
  27524. If the disc has been ejected and a different one put in since this
  27525. object was created, this will cause it to update its idea of how many tracks
  27526. there are, etc.
  27527. */
  27528. void refreshTrackLengths();
  27529. /** Enables scanning for indexes within tracks.
  27530. @see getLastIndex
  27531. */
  27532. void enableIndexScanning (bool enabled);
  27533. /** Returns the index number found during the last read() call.
  27534. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27535. Then when the read() method is called, if it comes across an index within that
  27536. block, the index number is stored and returned by this method.
  27537. Some devices might not support indexes, of course.
  27538. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27539. @see enableIndexScanning
  27540. */
  27541. int getLastIndex() const;
  27542. /** Scans a track to find the position of any indexes within it.
  27543. @param trackNumber the track to look in, where 0 is the first track on the disc
  27544. @returns an array of sample positions of any index points found (not including
  27545. the index that marks the start of the track)
  27546. */
  27547. const Array <int> findIndexesInTrack (const int trackNumber);
  27548. /** Returns the CDDB id number for the CD.
  27549. It's not a great way of identifying a disc, but it's traditional.
  27550. */
  27551. int getCDDBId();
  27552. /** Tries to eject the disk.
  27553. Of course this might not be possible, if some other process is using it.
  27554. */
  27555. void ejectDisk();
  27556. juce_UseDebuggingNewOperator
  27557. private:
  27558. #if JUCE_MAC
  27559. File volumeDir;
  27560. OwnedArray<File> tracks;
  27561. Array <int> trackStartSamples;
  27562. int currentReaderTrack;
  27563. AudioFormatReader* reader;
  27564. AudioCDReader (const File& volume);
  27565. public:
  27566. static int compareElements (const File* const, const File* const) throw();
  27567. private:
  27568. #elif JUCE_WIN32
  27569. int numTracks;
  27570. int trackStarts[100];
  27571. bool audioTracks [100];
  27572. void* handle;
  27573. bool indexingEnabled;
  27574. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27575. MemoryBlock buffer;
  27576. AudioCDReader (void* handle);
  27577. int getIndexAt (int samplePos);
  27578. #elif JUCE_LINUX
  27579. AudioCDReader();
  27580. #endif
  27581. AudioCDReader (const AudioCDReader&);
  27582. const AudioCDReader& operator= (const AudioCDReader&);
  27583. };
  27584. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27585. /********* End of inlined file: juce_AudioCDReader.h *********/
  27586. #endif
  27587. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27588. #endif
  27589. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27590. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27591. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27592. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27593. /**
  27594. A class for keeping a list of available audio formats, and for deciding which
  27595. one to use to open a given file.
  27596. You can either use this class as a singleton object, or create instances of it
  27597. yourself. Once created, use its registerFormat() method to tell it which
  27598. formats it should use.
  27599. @see AudioFormat
  27600. */
  27601. class JUCE_API AudioFormatManager
  27602. {
  27603. public:
  27604. /** Creates an empty format manager.
  27605. Before it'll be any use, you'll need to call registerFormat() with all the
  27606. formats you want it to be able to recognise.
  27607. */
  27608. AudioFormatManager();
  27609. /** Destructor. */
  27610. ~AudioFormatManager();
  27611. juce_DeclareSingleton (AudioFormatManager, false);
  27612. /** Adds a format to the manager's list of available file types.
  27613. The object passed-in will be deleted by this object, so don't keep a pointer
  27614. to it!
  27615. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27616. return this one when called.
  27617. */
  27618. void registerFormat (AudioFormat* newFormat,
  27619. const bool makeThisTheDefaultFormat);
  27620. /** Handy method to make it easy to register the formats that come with Juce.
  27621. Currently, this will add WAV and AIFF to the list.
  27622. */
  27623. void registerBasicFormats();
  27624. /** Clears the list of known formats. */
  27625. void clearFormats();
  27626. /** Returns the number of currently registered file formats. */
  27627. int getNumKnownFormats() const;
  27628. /** Returns one of the registered file formats. */
  27629. AudioFormat* getKnownFormat (const int index) const;
  27630. /** Looks for which of the known formats is listed as being for a given file
  27631. extension.
  27632. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27633. */
  27634. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27635. /** Returns the format which has been set as the default one.
  27636. You can set a format as being the default when it is registered. It's useful
  27637. when you want to write to a file, because the best format may change between
  27638. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27639. If none has been set as the default, this method will just return the first
  27640. one in the list.
  27641. */
  27642. AudioFormat* getDefaultFormat() const;
  27643. /** Returns a set of wildcards for file-matching that contains the extensions for
  27644. all known formats.
  27645. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27646. */
  27647. const String getWildcardForAllFormats() const;
  27648. /** Searches through the known formats to try to create a suitable reader for
  27649. this file.
  27650. If none of the registered formats can open the file, it'll return 0. If it
  27651. returns a reader, it's the caller's responsibility to delete the reader.
  27652. */
  27653. AudioFormatReader* createReaderFor (const File& audioFile);
  27654. /** Searches through the known formats to try to create a suitable reader for
  27655. this stream.
  27656. The stream object that is passed-in will be deleted by this method or by the
  27657. reader that is returned, so the caller should not keep any references to it.
  27658. The stream that is passed-in must be capable of being repositioned so
  27659. that all the formats can have a go at opening it.
  27660. If none of the registered formats can open the stream, it'll return 0. If it
  27661. returns a reader, it's the caller's responsibility to delete the reader.
  27662. */
  27663. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27664. juce_UseDebuggingNewOperator
  27665. private:
  27666. VoidArray knownFormats;
  27667. int defaultFormatIndex;
  27668. };
  27669. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27670. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27671. #endif
  27672. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27673. #endif
  27674. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27675. #endif
  27676. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27677. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27678. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27679. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27680. /**
  27681. This class is used to wrap an AudioFormatReader and only read from a
  27682. subsection of the file.
  27683. So if you have a reader which can read a 1000 sample file, you could wrap it
  27684. in one of these to only access, e.g. samples 100 to 200, and any samples
  27685. outside that will come back as 0. Accessing sample 0 from this reader will
  27686. actually read the first sample from the other's subsection, which might
  27687. be at a non-zero position.
  27688. @see AudioFormatReader
  27689. */
  27690. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27691. {
  27692. public:
  27693. /** Creates a AudioSubsectionReader for a given data source.
  27694. @param sourceReader the source reader from which we'll be taking data
  27695. @param subsectionStartSample the sample within the source reader which will be
  27696. mapped onto sample 0 for this reader.
  27697. @param subsectionLength the number of samples from the source that will
  27698. make up the subsection. If this reader is asked for
  27699. any samples beyond this region, it will return zero.
  27700. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27701. this object is deleted.
  27702. */
  27703. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27704. const int64 subsectionStartSample,
  27705. const int64 subsectionLength,
  27706. const bool deleteSourceWhenDeleted);
  27707. /** Destructor. */
  27708. ~AudioSubsectionReader();
  27709. bool read (int** destSamples,
  27710. int64 startSample,
  27711. int numSamples);
  27712. void readMaxLevels (int64 startSample,
  27713. int64 numSamples,
  27714. float& lowestLeft,
  27715. float& highestLeft,
  27716. float& lowestRight,
  27717. float& highestRight);
  27718. juce_UseDebuggingNewOperator
  27719. private:
  27720. AudioFormatReader* const source;
  27721. int64 startSample, length;
  27722. const bool deleteSourceWhenDeleted;
  27723. AudioSubsectionReader (const AudioSubsectionReader&);
  27724. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27725. };
  27726. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27727. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27728. #endif
  27729. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27730. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27731. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27732. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27733. class AudioThumbnailCache;
  27734. /**
  27735. Makes it easy to quickly draw scaled views of the waveform shape of an
  27736. audio file.
  27737. To use this class, just create an AudioThumbNail class for the file you want
  27738. to draw, call setSource to tell it which file or resource to use, then call
  27739. drawChannel() to draw it.
  27740. The class will asynchronously scan the wavefile to create its scaled-down view,
  27741. so you should make your UI repaint itself as this data comes in. To do this, the
  27742. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27743. listeners should repaint themselves.
  27744. The thumbnail stores an internal low-res version of the wave data, and this can
  27745. be loaded and saved to avoid having to scan the file again.
  27746. @see AudioThumbnailCache
  27747. */
  27748. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27749. public TimeSliceClient,
  27750. private Timer
  27751. {
  27752. public:
  27753. /** Creates an audio thumbnail.
  27754. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27755. of the audio data, this is the scale at which it should be done
  27756. @param formatManagerToUse the audio format manager that is used to open the file
  27757. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27758. thread and storage that is used to by the thumbnail, and the cache
  27759. object can be shared between multiple thumbnails
  27760. */
  27761. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27762. AudioFormatManager& formatManagerToUse,
  27763. AudioThumbnailCache& cacheToUse);
  27764. /** Destructor. */
  27765. ~AudioThumbnail();
  27766. /** Specifies the file or stream that contains the audio file.
  27767. For a file, just call
  27768. @code
  27769. setSource (new FileInputSource (file))
  27770. @endcode
  27771. You can pass a zero in here to clear the thumbnail.
  27772. The source that is passed in will be deleted by this object when it is no
  27773. longer needed
  27774. */
  27775. void setSource (InputSource* const newSource);
  27776. /** Reloads the low res thumbnail data from an input stream.
  27777. The thumb will automatically attempt to reload itself from its
  27778. AudioThumbnailCache.
  27779. */
  27780. void loadFrom (InputStream& input);
  27781. /** Saves the low res thumbnail data to an output stream.
  27782. The thumb will automatically attempt to save itself to its
  27783. AudioThumbnailCache after it finishes scanning the wave file.
  27784. */
  27785. void saveTo (OutputStream& output) const;
  27786. /** Returns the number of channels in the file.
  27787. */
  27788. int getNumChannels() const throw();
  27789. /** Returns the length of the audio file.
  27790. */
  27791. double getTotalLength() const throw();
  27792. /** Renders the waveform shape for a channel.
  27793. The waveform will be drawn within the specified rectangle, where startTime
  27794. and endTime specify the times within the audio file that should be positioned
  27795. at the left and right edges of the rectangle.
  27796. The waveform will be scaled vertically so that a full-volume sample will fill
  27797. the rectangle vertically, but you can also specify an extra vertical scale factor
  27798. with the verticalZoomFactor parameter.
  27799. */
  27800. void drawChannel (Graphics& g,
  27801. int x, int y, int w, int h,
  27802. double startTime,
  27803. double endTime,
  27804. int channelNum,
  27805. const float verticalZoomFactor);
  27806. /** Returns true if the low res preview is fully generated.
  27807. */
  27808. bool isFullyLoaded() const throw();
  27809. /** @internal */
  27810. bool useTimeSlice();
  27811. /** @internal */
  27812. void timerCallback();
  27813. juce_UseDebuggingNewOperator
  27814. private:
  27815. AudioFormatManager& formatManagerToUse;
  27816. AudioThumbnailCache& cache;
  27817. InputSource* source;
  27818. CriticalSection readerLock;
  27819. AudioFormatReader* reader;
  27820. MemoryBlock data, cachedLevels;
  27821. int orginalSamplesPerThumbnailSample;
  27822. int numChannelsCached, numSamplesCached;
  27823. double cachedStart, cachedTimePerPixel;
  27824. bool cacheNeedsRefilling;
  27825. void clear();
  27826. AudioFormatReader* createReader() const;
  27827. void generateSection (AudioFormatReader& reader,
  27828. int64 startSample,
  27829. int numSamples);
  27830. char* getChannelData (int channel) const;
  27831. void refillCache (const int numSamples,
  27832. double startTime,
  27833. const double timePerPixel);
  27834. friend class AudioThumbnailCache;
  27835. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27836. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27837. // returns true if more needs to be read
  27838. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27839. };
  27840. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27841. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27842. #endif
  27843. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27844. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27845. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27846. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27847. struct ThumbnailCacheEntry;
  27848. /**
  27849. An instance of this class is used to manage multiple AudioThumbnail objects.
  27850. The cache runs a single background thread that is shared by all the thumbnails
  27851. that need it, and it maintains a set of low-res previews in memory, to avoid
  27852. having to re-scan audio files too often.
  27853. @see AudioThumbnail
  27854. */
  27855. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27856. {
  27857. public:
  27858. /** Creates a cache object.
  27859. The maxNumThumbsToStore parameter lets you specify how many previews should
  27860. be kept in memory at once.
  27861. */
  27862. AudioThumbnailCache (const int maxNumThumbsToStore);
  27863. /** Destructor. */
  27864. ~AudioThumbnailCache();
  27865. /** Clears out any stored thumbnails.
  27866. */
  27867. void clear();
  27868. /** Reloads the specified thumb if this cache contains the appropriate stored
  27869. data.
  27870. This is called automatically by the AudioThumbnail class, so you shouldn't
  27871. normally need to call it directly.
  27872. */
  27873. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27874. /** Stores the cachable data from the specified thumb in this cache.
  27875. This is called automatically by the AudioThumbnail class, so you shouldn't
  27876. normally need to call it directly.
  27877. */
  27878. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27879. juce_UseDebuggingNewOperator
  27880. private:
  27881. OwnedArray <ThumbnailCacheEntry> thumbs;
  27882. int maxNumThumbsToStore;
  27883. friend class AudioThumbnail;
  27884. void addThumbnail (AudioThumbnail* const thumb);
  27885. void removeThumbnail (AudioThumbnail* const thumb);
  27886. };
  27887. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27888. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27889. #endif
  27890. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27891. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27892. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27893. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27894. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27895. /**
  27896. Reads and writes the lossless-compression FLAC audio format.
  27897. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27898. and make sure your include search path and library search path are set up to find
  27899. the FLAC header files and static libraries.
  27900. @see AudioFormat
  27901. */
  27902. class JUCE_API FlacAudioFormat : public AudioFormat
  27903. {
  27904. public:
  27905. FlacAudioFormat();
  27906. ~FlacAudioFormat();
  27907. const Array <int> getPossibleSampleRates();
  27908. const Array <int> getPossibleBitDepths();
  27909. bool canDoStereo();
  27910. bool canDoMono();
  27911. bool isCompressed();
  27912. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27913. const bool deleteStreamIfOpeningFails);
  27914. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27915. double sampleRateToUse,
  27916. unsigned int numberOfChannels,
  27917. int bitsPerSample,
  27918. const StringPairArray& metadataValues,
  27919. int qualityOptionIndex);
  27920. juce_UseDebuggingNewOperator
  27921. };
  27922. #endif
  27923. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27924. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27925. #endif
  27926. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27927. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  27928. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27929. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  27930. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  27931. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27932. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27933. class InterprocessConnectionServer;
  27934. /**
  27935. Manages a simple two-way messaging connection to another process, using either
  27936. a socket or a named pipe as the transport medium.
  27937. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  27938. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27939. and incoming messages will result in a callback via the messageReceived()
  27940. method.
  27941. To open a pipe and wait for another client to connect to it, use the createPipe()
  27942. method.
  27943. To act as a socket server and create connections for one or more client, see the
  27944. InterprocessConnectionServer class.
  27945. @see InterprocessConnectionServer, Socket, NamedPipe
  27946. */
  27947. class JUCE_API InterprocessConnection : public Thread,
  27948. private MessageListener
  27949. {
  27950. public:
  27951. /** Creates a connection.
  27952. Connections are created manually, connecting them with the connectToSocket()
  27953. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  27954. when a client wants to connect.
  27955. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  27956. connectionLost() and messageReceived() methods will
  27957. always be made using the message thread; if false,
  27958. these will be called immediately on the connection's
  27959. own thread.
  27960. @param magicMessageHeaderNumber a magic number to use in the header to check the
  27961. validity of the data blocks being sent and received. This
  27962. can be any number, but the sender and receiver must obviously
  27963. use matching values or they won't recognise each other.
  27964. */
  27965. InterprocessConnection (const bool callbacksOnMessageThread = true,
  27966. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  27967. /** Destructor. */
  27968. ~InterprocessConnection();
  27969. /** Tries to connect this object to a socket.
  27970. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  27971. object waiting to receive client connections on this port number.
  27972. @param hostName the host computer, either a network address or name
  27973. @param portNumber the socket port number to try to connect to
  27974. @param timeOutMillisecs how long to keep trying before giving up
  27975. @returns true if the connection is established successfully
  27976. @see Socket
  27977. */
  27978. bool connectToSocket (const String& hostName,
  27979. const int portNumber,
  27980. const int timeOutMillisecs);
  27981. /** Tries to connect the object to an existing named pipe.
  27982. For this to work, another process on the same computer must already have opened
  27983. an InterprocessConnection object and used createPipe() to create a pipe for this
  27984. to connect to.
  27985. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27986. @returns true if it connects successfully.
  27987. @see createPipe, NamedPipe
  27988. */
  27989. bool connectToPipe (const String& pipeName,
  27990. const int pipeReceiveMessageTimeoutMs = -1);
  27991. /** Tries to create a new pipe for other processes to connect to.
  27992. This creates a pipe with the given name, so that other processes can use
  27993. connectToPipe() to connect to the other end.
  27994. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27995. If another process is already using this pipe, this will fail and return false.
  27996. */
  27997. bool createPipe (const String& pipeName,
  27998. const int pipeReceiveMessageTimeoutMs = -1);
  27999. /** Disconnects and closes any currently-open sockets or pipes. */
  28000. void disconnect();
  28001. /** True if a socket or pipe is currently active. */
  28002. bool isConnected() const;
  28003. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  28004. StreamingSocket* getSocket() const throw() { return socket; }
  28005. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  28006. NamedPipe* getPipe() const throw() { return pipe; }
  28007. /** Returns the name of the machine at the other end of this connection.
  28008. This will return an empty string if the other machine isn't known for
  28009. some reason.
  28010. */
  28011. const String getConnectedHostName() const;
  28012. /** Tries to send a message to the other end of this connection.
  28013. This will fail if it's not connected, or if there's some kind of write error. If
  28014. it succeeds, the connection object at the other end will receive the message by
  28015. a callback to its messageReceived() method.
  28016. @see messageReceived
  28017. */
  28018. bool sendMessage (const MemoryBlock& message);
  28019. /** Called when the connection is first connected.
  28020. If the connection was created with the callbacksOnMessageThread flag set, then
  28021. this will be called on the message thread; otherwise it will be called on a server
  28022. thread.
  28023. */
  28024. virtual void connectionMade() = 0;
  28025. /** Called when the connection is broken.
  28026. If the connection was created with the callbacksOnMessageThread flag set, then
  28027. this will be called on the message thread; otherwise it will be called on a server
  28028. thread.
  28029. */
  28030. virtual void connectionLost() = 0;
  28031. /** Called when a message arrives.
  28032. When the object at the other end of this connection sends us a message with sendMessage(),
  28033. this callback is used to deliver it to us.
  28034. If the connection was created with the callbacksOnMessageThread flag set, then
  28035. this will be called on the message thread; otherwise it will be called on a server
  28036. thread.
  28037. @see sendMessage
  28038. */
  28039. virtual void messageReceived (const MemoryBlock& message) = 0;
  28040. juce_UseDebuggingNewOperator
  28041. private:
  28042. CriticalSection pipeAndSocketLock;
  28043. StreamingSocket* socket;
  28044. NamedPipe* pipe;
  28045. bool callbackConnectionState;
  28046. const bool useMessageThread;
  28047. const uint32 magicMessageHeader;
  28048. int pipeReceiveMessageTimeout;
  28049. friend class InterprocessConnectionServer;
  28050. void initialiseWithSocket (StreamingSocket* const socket_);
  28051. void initialiseWithPipe (NamedPipe* const pipe_);
  28052. void handleMessage (const Message& message);
  28053. void connectionMadeInt();
  28054. void connectionLostInt();
  28055. void deliverDataInt (const MemoryBlock& data);
  28056. bool readNextMessageInt();
  28057. void run();
  28058. InterprocessConnection (const InterprocessConnection&);
  28059. const InterprocessConnection& operator= (const InterprocessConnection&);
  28060. };
  28061. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28062. /********* End of inlined file: juce_InterprocessConnection.h *********/
  28063. /**
  28064. An object that waits for client sockets to connect to a port on this host, and
  28065. creates InterprocessConnection objects for each one.
  28066. To use this, create a class derived from it which implements the createConnectionObject()
  28067. method, so that it creates suitable connection objects for each client that tries
  28068. to connect.
  28069. @see InterprocessConnection
  28070. */
  28071. class JUCE_API InterprocessConnectionServer : private Thread
  28072. {
  28073. public:
  28074. /** Creates an uninitialised server object.
  28075. */
  28076. InterprocessConnectionServer();
  28077. /** Destructor. */
  28078. ~InterprocessConnectionServer();
  28079. /** Starts an internal thread which listens on the given port number.
  28080. While this is running, in another process tries to connect with the
  28081. InterprocessConnection::connectToSocket() method, this object will call
  28082. createConnectionObject() to create a connection to that client.
  28083. Use stop() to stop the thread running.
  28084. @see createConnectionObject, stop
  28085. */
  28086. bool beginWaitingForSocket (const int portNumber);
  28087. /** Terminates the listener thread, if it's active.
  28088. @see beginWaitingForSocket
  28089. */
  28090. void stop();
  28091. protected:
  28092. /** Creates a suitable connection object for a client process that wants to
  28093. connect to this one.
  28094. This will be called by the listener thread when a client process tries
  28095. to connect, and must return a new InterprocessConnection object that will
  28096. then run as this end of the connection.
  28097. @see InterprocessConnection
  28098. */
  28099. virtual InterprocessConnection* createConnectionObject() = 0;
  28100. public:
  28101. juce_UseDebuggingNewOperator
  28102. private:
  28103. StreamingSocket* volatile socket;
  28104. void run();
  28105. InterprocessConnectionServer (const InterprocessConnectionServer&);
  28106. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  28107. };
  28108. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28109. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  28110. #endif
  28111. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  28112. #endif
  28113. #ifndef __JUCE_TIMER_JUCEHEADER__
  28114. #endif
  28115. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  28116. #endif
  28117. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28118. /********* Start of inlined file: juce_MultiTimer.h *********/
  28119. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28120. #define __JUCE_MULTITIMER_JUCEHEADER__
  28121. /**
  28122. A type of timer class that can run multiple timers with different frequencies,
  28123. all of which share a single callback.
  28124. This class is very similar to the Timer class, but allows you run multiple
  28125. separate timers, where each one has a unique ID number. The methods in this
  28126. class are exactly equivalent to those in Timer, but with the addition of
  28127. this ID number.
  28128. To use it, you need to create a subclass of MultiTimer, implementing the
  28129. timerCallback() method. Then you can start timers with startTimer(), and
  28130. each time the callback is triggered, it passes in the ID of the timer that
  28131. caused it.
  28132. @see Timer
  28133. */
  28134. class JUCE_API MultiTimer
  28135. {
  28136. protected:
  28137. /** Creates a MultiTimer.
  28138. When created, no timers are running, so use startTimer() to start things off.
  28139. */
  28140. MultiTimer() throw();
  28141. /** Creates a copy of another timer.
  28142. Note that this timer will not contain any running timers, even if the one you're
  28143. copying from was running.
  28144. */
  28145. MultiTimer (const MultiTimer& other) throw();
  28146. public:
  28147. /** Destructor. */
  28148. virtual ~MultiTimer();
  28149. /** The user-defined callback routine that actually gets called by each of the
  28150. timers that are running.
  28151. It's perfectly ok to call startTimer() or stopTimer() from within this
  28152. callback to change the subsequent intervals.
  28153. */
  28154. virtual void timerCallback (const int timerId) = 0;
  28155. /** Starts a timer and sets the length of interval required.
  28156. If the timer is already started, this will reset it, so the
  28157. time between calling this method and the next timer callback
  28158. will not be less than the interval length passed in.
  28159. @param timerId a unique Id number that identifies the timer to
  28160. start. This is the id that will be passed back
  28161. to the timerCallback() method when this timer is
  28162. triggered
  28163. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28164. rounded up to 1)
  28165. */
  28166. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28167. /** Stops a timer.
  28168. If a timer has been started with the given ID number, it will be cancelled.
  28169. No more callbacks will be made for the specified timer after this method returns.
  28170. If this is called from a different thread, any callbacks that may
  28171. be currently executing may be allowed to finish before the method
  28172. returns.
  28173. */
  28174. void stopTimer (const int timerId) throw();
  28175. /** Checks whether a timer has been started for a specified ID.
  28176. @returns true if a timer with the given ID is running.
  28177. */
  28178. bool isTimerRunning (const int timerId) const throw();
  28179. /** Returns the interval for a specified timer ID.
  28180. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28181. is running for the ID number specified.
  28182. */
  28183. int getTimerInterval (const int timerId) const throw();
  28184. private:
  28185. CriticalSection timerListLock;
  28186. VoidArray timers;
  28187. const MultiTimer& operator= (const MultiTimer&);
  28188. };
  28189. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28190. /********* End of inlined file: juce_MultiTimer.h *********/
  28191. #endif
  28192. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28193. /********* Start of inlined file: juce_MessageManager.h *********/
  28194. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28195. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28196. /********* Start of inlined file: juce_ActionListenerList.h *********/
  28197. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28198. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28199. /**
  28200. A set of ActionListeners.
  28201. Listeners can be added and removed from the list, and messages can be
  28202. broadcast to all the listeners.
  28203. @see ActionListener, ActionBroadcaster
  28204. */
  28205. class JUCE_API ActionListenerList : public MessageListener
  28206. {
  28207. public:
  28208. /** Creates an empty list. */
  28209. ActionListenerList() throw();
  28210. /** Destructor. */
  28211. ~ActionListenerList() throw();
  28212. /** Adds a listener to the list.
  28213. (Trying to add a listener that's already on the list will have no effect).
  28214. */
  28215. void addActionListener (ActionListener* const listener) throw();
  28216. /** Removes a listener from the list.
  28217. If the listener isn't on the list, this won't have any effect.
  28218. */
  28219. void removeActionListener (ActionListener* const listener) throw();
  28220. /** Removes all listeners from the list. */
  28221. void removeAllActionListeners() throw();
  28222. /** Broadcasts a message to all the registered listeners.
  28223. This sends the message asynchronously.
  28224. If a listener is on the list when this method is called but is removed from
  28225. the list before the message arrives, it won't receive the message. Similarly
  28226. listeners that are added to the list after the message is sent but before it
  28227. arrives won't get the message either.
  28228. */
  28229. void sendActionMessage (const String& message) const;
  28230. /** @internal */
  28231. void handleMessage (const Message&);
  28232. juce_UseDebuggingNewOperator
  28233. private:
  28234. SortedSet <void*> actionListeners_;
  28235. CriticalSection actionListenerLock_;
  28236. ActionListenerList (const ActionListenerList&);
  28237. const ActionListenerList& operator= (const ActionListenerList&);
  28238. };
  28239. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28240. /********* End of inlined file: juce_ActionListenerList.h *********/
  28241. /********* Start of inlined file: juce_CallbackMessage.h *********/
  28242. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28243. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28244. /**
  28245. A message that calls a custom function when it gets delivered.
  28246. You can use this class to fire off actions that you want to be performed later
  28247. on the message thread.
  28248. Unlike other Message objects, these don't get sent to a MessageListener, you
  28249. just call the post() method to send them, and when they arrive, your
  28250. messageCallback() method will automatically be invoked.
  28251. @see MessageListener, MessageManager, ActionListener, ChangeListener
  28252. */
  28253. class JUCE_API CallbackMessage : public Message
  28254. {
  28255. public:
  28256. CallbackMessage() throw();
  28257. /** Destructor. */
  28258. ~CallbackMessage() throw();
  28259. /** Called when the message is delivered.
  28260. You should implement this method and make it do whatever action you want
  28261. to perform.
  28262. Note that like all other messages, this object will be deleted immediately
  28263. after this method has been invoked.
  28264. */
  28265. virtual void messageCallback() = 0;
  28266. /** Instead of sending this message to a MessageListener, just call this method
  28267. to post it to the event queue.
  28268. After you've called this, this object will belong to the MessageManager,
  28269. which will delete it later. So make sure you don't delete the object yourself,
  28270. call post() more than once, or call post() on a stack-based obect!
  28271. */
  28272. void post();
  28273. juce_UseDebuggingNewOperator
  28274. private:
  28275. CallbackMessage (const CallbackMessage&);
  28276. const CallbackMessage& operator= (const CallbackMessage&);
  28277. };
  28278. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28279. /********* End of inlined file: juce_CallbackMessage.h *********/
  28280. class Component;
  28281. class MessageManagerLock;
  28282. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  28283. */
  28284. typedef void* (MessageCallbackFunction) (void* userData);
  28285. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  28286. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  28287. */
  28288. class JUCE_API MessageManager
  28289. {
  28290. public:
  28291. /** Returns the global instance of the MessageManager. */
  28292. static MessageManager* getInstance() throw();
  28293. /** Runs the event dispatch loop until a stop message is posted.
  28294. This method is only intended to be run by the application's startup routine,
  28295. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  28296. @see stopDispatchLoop
  28297. */
  28298. void runDispatchLoop();
  28299. /** Sends a signal that the dispatch loop should terminate.
  28300. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  28301. will be interrupted and will return.
  28302. @see runDispatchLoop
  28303. */
  28304. void stopDispatchLoop();
  28305. /** Returns true if the stopDispatchLoop() method has been called.
  28306. */
  28307. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  28308. /** Synchronously dispatches messages until a given time has elapsed.
  28309. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  28310. otherwise returns true.
  28311. */
  28312. bool runDispatchLoopUntil (int millisecondsToRunFor);
  28313. /** Calls a function using the message-thread.
  28314. This can be used by any thread to cause this function to be called-back
  28315. by the message thread. If it's the message-thread that's calling this method,
  28316. then the function will just be called; if another thread is calling, a message
  28317. will be posted to the queue, and this method will block until that message
  28318. is delivered, the function is called, and the result is returned.
  28319. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  28320. thread has a critical section locked, which an unrelated message callback then tries to lock
  28321. before the message thread gets round to processing this callback.
  28322. @param callback the function to call - its signature must be @code
  28323. void* myCallbackFunction (void*) @endcode
  28324. @param userData a user-defined pointer that will be passed to the function that gets called
  28325. @returns the value that the callback function returns.
  28326. @see MessageManagerLock
  28327. */
  28328. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  28329. void* userData);
  28330. /** Returns true if the caller-thread is the message thread. */
  28331. bool isThisTheMessageThread() const throw();
  28332. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  28333. (Best to ignore this method unless you really know what you're doing..)
  28334. @see getCurrentMessageThread
  28335. */
  28336. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  28337. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  28338. (Best to ignore this method unless you really know what you're doing..)
  28339. @see setCurrentMessageThread
  28340. */
  28341. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  28342. /** Returns true if the caller thread has currenltly got the message manager locked.
  28343. see the MessageManagerLock class for more info about this.
  28344. This will be true if the caller is the message thread, because that automatically
  28345. gains a lock while a message is being dispatched.
  28346. */
  28347. bool currentThreadHasLockedMessageManager() const throw();
  28348. /** Sends a message to all other JUCE applications that are running.
  28349. @param messageText the string that will be passed to the actionListenerCallback()
  28350. method of the broadcast listeners in the other app.
  28351. @see registerBroadcastListener, ActionListener
  28352. */
  28353. static void broadcastMessage (const String& messageText) throw();
  28354. /** Registers a listener to get told about broadcast messages.
  28355. The actionListenerCallback() callback's string parameter
  28356. is the message passed into broadcastMessage().
  28357. @see broadcastMessage
  28358. */
  28359. void registerBroadcastListener (ActionListener* listener) throw();
  28360. /** Deregisters a broadcast listener. */
  28361. void deregisterBroadcastListener (ActionListener* listener) throw();
  28362. /** @internal */
  28363. void deliverMessage (void*);
  28364. /** @internal */
  28365. void deliverBroadcastMessage (const String&);
  28366. /** @internal */
  28367. ~MessageManager() throw();
  28368. juce_UseDebuggingNewOperator
  28369. private:
  28370. MessageManager() throw();
  28371. friend class MessageListener;
  28372. friend class ChangeBroadcaster;
  28373. friend class ActionBroadcaster;
  28374. friend class CallbackMessage;
  28375. static MessageManager* instance;
  28376. SortedSet<const MessageListener*> messageListeners;
  28377. ActionListenerList* broadcastListeners;
  28378. friend class JUCEApplication;
  28379. bool quitMessagePosted, quitMessageReceived;
  28380. Thread::ThreadID messageThreadId;
  28381. VoidArray modalComponents;
  28382. static void* exitModalLoopCallback (void*);
  28383. void postMessageToQueue (Message* const message);
  28384. void postCallbackMessage (Message* const message);
  28385. static void doPlatformSpecificInitialisation();
  28386. static void doPlatformSpecificShutdown();
  28387. friend class MessageManagerLock;
  28388. Thread::ThreadID volatile threadWithLock;
  28389. CriticalSection lockingLock;
  28390. MessageManager (const MessageManager&);
  28391. const MessageManager& operator= (const MessageManager&);
  28392. };
  28393. /** Used to make sure that the calling thread has exclusive access to the message loop.
  28394. Because it's not thread-safe to call any of the Component or other UI classes
  28395. from threads other than the message thread, one of these objects can be used to
  28396. lock the message loop and allow this to be done. The message thread will be
  28397. suspended for the lifetime of the MessageManagerLock object, so create one on
  28398. the stack like this: @code
  28399. void MyThread::run()
  28400. {
  28401. someData = 1234;
  28402. const MessageManagerLock mmLock;
  28403. // the event loop will now be locked so it's safe to make a few calls..
  28404. myComponent->setBounds (newBounds);
  28405. myComponent->repaint();
  28406. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  28407. }
  28408. @endcode
  28409. Obviously be careful not to create one of these and leave it lying around, or
  28410. your app will grind to a halt!
  28411. Another caveat is that using this in conjunction with other CriticalSections
  28412. can create lots of interesting ways of producing a deadlock! In particular, if
  28413. your message thread calls stopThread() for a thread that uses these locks,
  28414. you'll get an (occasional) deadlock..
  28415. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  28416. */
  28417. class JUCE_API MessageManagerLock
  28418. {
  28419. public:
  28420. /** Tries to acquire a lock on the message manager.
  28421. The constructor attempts to gain a lock on the message loop, and the lock will be
  28422. kept for the lifetime of this object.
  28423. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  28424. this method will keep checking whether the thread has been given the
  28425. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  28426. without gaining the lock. If you pass a thread, you must check whether the lock was
  28427. successful by calling lockWasGained(). If this is false, your thread is being told to
  28428. die, so you should take evasive action.
  28429. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  28430. careful when doing this, because it's very easy to deadlock if your message thread
  28431. attempts to call stopThread() on a thread just as that thread attempts to get the
  28432. message lock.
  28433. If the calling thread already has the lock, nothing will be done, so it's safe and
  28434. quick to use these locks recursively.
  28435. E.g.
  28436. @code
  28437. void run()
  28438. {
  28439. ...
  28440. while (! threadShouldExit())
  28441. {
  28442. MessageManagerLock mml (Thread::getCurrentThread());
  28443. if (! mml.lockWasGained())
  28444. return; // another thread is trying to kill us!
  28445. ..do some locked stuff here..
  28446. }
  28447. ..and now the MM is now unlocked..
  28448. }
  28449. @endcode
  28450. */
  28451. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  28452. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  28453. instead of a thread.
  28454. See the MessageManagerLock (Thread*) constructor for details on how this works.
  28455. */
  28456. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  28457. /** Releases the current thread's lock on the message manager.
  28458. Make sure this object is created and deleted by the same thread,
  28459. otherwise there are no guarantees what will happen!
  28460. */
  28461. ~MessageManagerLock() throw();
  28462. /** Returns true if the lock was successfully acquired.
  28463. (See the constructor that takes a Thread for more info).
  28464. */
  28465. bool lockWasGained() const throw() { return locked; }
  28466. private:
  28467. bool locked, needsUnlocking;
  28468. void* sharedEvents;
  28469. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  28470. };
  28471. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28472. /********* End of inlined file: juce_MessageManager.h *********/
  28473. #endif
  28474. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28475. #endif
  28476. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28477. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  28478. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28479. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28480. /** Manages a list of ActionListeners, and can send them messages.
  28481. To quickly add methods to your class that can add/remove action
  28482. listeners and broadcast to them, you can derive from this.
  28483. @see ActionListenerList, ActionListener
  28484. */
  28485. class JUCE_API ActionBroadcaster
  28486. {
  28487. public:
  28488. /** Creates an ActionBroadcaster. */
  28489. ActionBroadcaster() throw();
  28490. /** Destructor. */
  28491. virtual ~ActionBroadcaster();
  28492. /** Adds a listener to the list.
  28493. (Trying to add a listener that's already on the list will have no effect).
  28494. */
  28495. void addActionListener (ActionListener* const listener);
  28496. /** Removes a listener from the list.
  28497. If the listener isn't on the list, this won't have any effect.
  28498. */
  28499. void removeActionListener (ActionListener* const listener);
  28500. /** Removes all listeners from the list. */
  28501. void removeAllActionListeners();
  28502. /** Broadcasts a message to all the registered listeners.
  28503. @see ActionListenerList::sendActionMessage
  28504. */
  28505. void sendActionMessage (const String& message) const;
  28506. private:
  28507. ActionListenerList actionListenerList;
  28508. ActionBroadcaster (const ActionBroadcaster&);
  28509. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  28510. };
  28511. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28512. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  28513. #endif
  28514. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  28515. #endif
  28516. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28517. #endif
  28518. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  28519. #endif
  28520. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  28521. #endif
  28522. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  28523. #endif
  28524. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  28525. #endif
  28526. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28527. #endif
  28528. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28529. #endif
  28530. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28531. /********* Start of inlined file: juce_GradientBrush.h *********/
  28532. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28533. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28534. /********* Start of inlined file: juce_ColourGradient.h *********/
  28535. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28536. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28537. /**
  28538. Structure used to define a colour gradient for painting areas.
  28539. @see GradientBrush
  28540. */
  28541. class JUCE_API ColourGradient
  28542. {
  28543. public:
  28544. /** Creates a gradient object.
  28545. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28546. colour2 should be. In between them there's a gradient.
  28547. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28548. its centre.
  28549. The alpha transparencies of the colours are used, so note that
  28550. if you blend from transparent to a solid colour, the RGB of the transparent
  28551. colour will become visible in parts of the gradient. e.g. blending
  28552. from Colour::transparentBlack to Colours::white will produce a
  28553. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28554. will be white all the way across.
  28555. @see ColourGradient
  28556. */
  28557. ColourGradient (const Colour& colour1,
  28558. const float x1,
  28559. const float y1,
  28560. const Colour& colour2,
  28561. const float x2,
  28562. const float y2,
  28563. const bool isRadial) throw();
  28564. /** Creates an uninitialised gradient.
  28565. If you use this constructor instead of the other one, be sure to set all the
  28566. object's public member variables before using it!
  28567. */
  28568. ColourGradient() throw();
  28569. /** Destructor */
  28570. ~ColourGradient() throw();
  28571. /** Removes any colours that have been added.
  28572. This will also remove any start and end colours, so the gradient won't work. You'll
  28573. need to add more colours with addColour().
  28574. */
  28575. void clearColours() throw();
  28576. /** Adds a colour at a point along the length of the gradient.
  28577. This allows the gradient to go through a spectrum of colours, instead of just a
  28578. start and end colour.
  28579. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28580. of the distance along the line between the two points
  28581. at which the colour should occur.
  28582. @param colour the colour that should be used at this point
  28583. */
  28584. void addColour (const double proportionAlongGradient,
  28585. const Colour& colour) throw();
  28586. /** Multiplies the alpha value of all the colours by the given scale factor */
  28587. void multiplyOpacity (const float multiplier) throw();
  28588. /** Returns the number of colour-stops that have been added. */
  28589. int getNumColours() const throw();
  28590. /** Returns the position along the length of the gradient of the colour with this index.
  28591. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28592. */
  28593. double getColourPosition (const int index) const throw();
  28594. /** Returns the colour that was added with a given index.
  28595. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28596. */
  28597. const Colour getColour (const int index) const throw();
  28598. /** Creates a set of interpolated premultiplied ARGB values.
  28599. The caller must delete the array that is returned using juce_free().
  28600. */
  28601. PixelARGB* createLookupTable (int& numEntries) const throw();
  28602. /** Returns true if all colours are opaque. */
  28603. bool isOpaque() const throw();
  28604. /** Returns true if all colours are completely transparent. */
  28605. bool isInvisible() const throw();
  28606. float x1;
  28607. float y1;
  28608. float x2;
  28609. float y2;
  28610. /** If true, the gradient should be filled circularly, centred around
  28611. (x1, y1), with (x2, y2) defining a point on the circumference.
  28612. If false, the gradient is linear between the two points.
  28613. */
  28614. bool isRadial;
  28615. /** A transform to apply to the resultant gradient shape */
  28616. AffineTransform transform;
  28617. juce_UseDebuggingNewOperator
  28618. private:
  28619. Array <uint32> colours;
  28620. };
  28621. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28622. /********* End of inlined file: juce_ColourGradient.h *********/
  28623. /**
  28624. A Brush that fills areas with a colour gradient.
  28625. The gradient can either be linear or circular.
  28626. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28627. */
  28628. class JUCE_API GradientBrush : public Brush
  28629. {
  28630. public:
  28631. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28632. (x1, y1) is the location relative to the origin of the Graphics context,
  28633. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28634. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28635. its centre.
  28636. The alpha transparencies of the colours are used, so the brush
  28637. need not be completely opaque. Note that this means that if you
  28638. blend from transparent to a solid colour, the RGB of the transparent
  28639. colour will become visible in parts of the gradient. e.g. blending
  28640. from Colour::transparentBlack to Colours::white will produce a
  28641. grey colour, but Colour::transparentWhite to Colours::white will be
  28642. white all the way across.
  28643. @see ColourGradient
  28644. */
  28645. GradientBrush (const Colour& colour1,
  28646. const float x1,
  28647. const float y1,
  28648. const Colour& colour2,
  28649. const float x2,
  28650. const float y2,
  28651. const bool isRadial) throw();
  28652. /** Creates a gradient brush from a ColourGradient object.
  28653. */
  28654. GradientBrush (const ColourGradient& gradient) throw();
  28655. /** Destructor. */
  28656. ~GradientBrush() throw();
  28657. Brush* createCopy() const throw();
  28658. void applyTransform (const AffineTransform& transform) throw();
  28659. void multiplyOpacity (const float multiple) throw();
  28660. bool isInvisible() const throw();
  28661. void paintPath (LowLevelGraphicsContext& context,
  28662. const Path& path, const AffineTransform& transform) throw();
  28663. void paintRectangle (LowLevelGraphicsContext& context,
  28664. int x, int y, int w, int h) throw();
  28665. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28666. const Image& alphaChannelImage, int imageX, int imageY,
  28667. int x, int y, int w, int h) throw();
  28668. juce_UseDebuggingNewOperator
  28669. protected:
  28670. ColourGradient gradient;
  28671. private:
  28672. GradientBrush (const GradientBrush&);
  28673. const GradientBrush& operator= (const GradientBrush&);
  28674. };
  28675. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28676. /********* End of inlined file: juce_GradientBrush.h *********/
  28677. #endif
  28678. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28679. /********* Start of inlined file: juce_ImageBrush.h *********/
  28680. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28681. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28682. /********* Start of inlined file: juce_Image.h *********/
  28683. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28684. #define __JUCE_IMAGE_JUCEHEADER__
  28685. /**
  28686. Holds a fixed-size bitmap.
  28687. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28688. To draw into an image, create a Graphics object for it.
  28689. e.g. @code
  28690. // create a transparent 500x500 image..
  28691. Image myImage (Image::RGB, 500, 500, true);
  28692. Graphics g (myImage);
  28693. g.setColour (Colours::red);
  28694. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28695. @endcode
  28696. Other useful ways to create an image are with the ImageCache class, or the
  28697. ImageFileFormat, which provides a way to load common image files.
  28698. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28699. */
  28700. class JUCE_API Image
  28701. {
  28702. public:
  28703. enum PixelFormat
  28704. {
  28705. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28706. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28707. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28708. };
  28709. /** Creates an in-memory image with a specified size and format.
  28710. @param format the number of colour channels in the image
  28711. @param imageWidth the desired width of the image, in pixels - this value must be
  28712. greater than zero (otherwise a width of 1 will be used)
  28713. @param imageHeight the desired width of the image, in pixels - this value must be
  28714. greater than zero (otherwise a height of 1 will be used)
  28715. @param clearImage if true, the image will initially be cleared to black or transparent
  28716. black. If false, the image may contain random data, and the
  28717. user will have to deal with this
  28718. */
  28719. Image (const PixelFormat format,
  28720. const int imageWidth,
  28721. const int imageHeight,
  28722. const bool clearImage);
  28723. /** Creates a copy of another image.
  28724. @see createCopy
  28725. */
  28726. Image (const Image& other);
  28727. /** Destructor. */
  28728. virtual ~Image();
  28729. /** Returns the image's width (in pixels). */
  28730. int getWidth() const throw() { return imageWidth; }
  28731. /** Returns the image's height (in pixels). */
  28732. int getHeight() const throw() { return imageHeight; }
  28733. /** Returns the image's pixel format. */
  28734. PixelFormat getFormat() const throw() { return format; }
  28735. /** True if the image's format is ARGB. */
  28736. bool isARGB() const throw() { return format == ARGB; }
  28737. /** True if the image's format is RGB. */
  28738. bool isRGB() const throw() { return format == RGB; }
  28739. /** True if the image contains an alpha-channel. */
  28740. bool hasAlphaChannel() const throw() { return format != RGB; }
  28741. /** Clears a section of the image with a given colour.
  28742. This won't do any alpha-blending - it just sets all pixels in the image to
  28743. the given colour (which may be non-opaque if the image has an alpha channel).
  28744. */
  28745. virtual void clear (int x, int y, int w, int h,
  28746. const Colour& colourToClearTo = Colour (0x00000000));
  28747. /** Returns a new image that's a copy of this one.
  28748. A new size for the copied image can be specified, or values less than
  28749. zero can be passed-in to use the image's existing dimensions.
  28750. It's up to the caller to delete the image when no longer needed.
  28751. */
  28752. virtual Image* createCopy (int newWidth = -1,
  28753. int newHeight = -1,
  28754. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28755. /** Returns the colour of one of the pixels in the image.
  28756. If the co-ordinates given are beyond the image's boundaries, this will
  28757. return Colours::transparentBlack.
  28758. (0, 0) is the image's top-left corner.
  28759. @see getAlphaAt, setPixelAt, blendPixelAt
  28760. */
  28761. virtual const Colour getPixelAt (const int x, const int y) const;
  28762. /** Sets the colour of one of the image's pixels.
  28763. If the co-ordinates are beyond the image's boundaries, then nothing will
  28764. happen.
  28765. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28766. just replace the existing pixel with the given one. The colour's opacity
  28767. will be ignored if this image doesn't have an alpha-channel.
  28768. (0, 0) is the image's top-left corner.
  28769. @see blendPixelAt
  28770. */
  28771. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28772. /** Changes the opacity of a pixel.
  28773. This only has an effect if the image has an alpha channel and if the
  28774. given co-ordinates are inside the image's boundary.
  28775. The multiplier must be in the range 0 to 1.0, and the current alpha
  28776. at the given co-ordinates will be multiplied by this value.
  28777. @see getAlphaAt, setPixelAt
  28778. */
  28779. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28780. /** Changes the overall opacity of the image.
  28781. This will multiply the alpha value of each pixel in the image by the given
  28782. amount (limiting the resulting alpha values between 0 and 255). This allows
  28783. you to make an image more or less transparent.
  28784. If the image doesn't have an alpha channel, this won't have any effect.
  28785. */
  28786. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28787. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28788. */
  28789. virtual void desaturate();
  28790. /** Locks some of the pixels in the image so they can be read and written to.
  28791. This returns a pointer to some memory containing the pixels in the given
  28792. rectangle. It also returns values for the line and pixel stride used within
  28793. the data. The format of the pixel data is the same as that of this image.
  28794. When you've finished reading and changing the data, you must call
  28795. releasePixelDataReadWrite() to give the pixels back to the image.
  28796. For images that are stored in memory, this method may just return a direct
  28797. pointer to the image's data, but other types of image may be stored elsewhere,
  28798. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28799. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28800. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28801. instead.
  28802. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28803. */
  28804. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28805. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28806. */
  28807. virtual void releasePixelDataReadWrite (void* sourceData);
  28808. /** Locks some of the pixels in the image so they can be read.
  28809. This returns a pointer to some memory containing the pixels in the given
  28810. rectangle. It also returns values for the line and pixel stride used within
  28811. the data. The format of the pixel data is the same as that of this image.
  28812. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28813. to let the image free the memory if necessary.
  28814. For images that are stored in memory, this method may just return a direct
  28815. pointer to the image's data, but other types of image may be stored elsewhere,
  28816. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28817. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28818. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28819. instead.
  28820. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28821. */
  28822. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28823. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28824. */
  28825. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28826. /** Copies some pixel values to a rectangle of the image.
  28827. The format of the pixel data must match that of the image itself, and the
  28828. rectangle supplied must be within the image's bounds.
  28829. */
  28830. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28831. const uint8* sourcePixelData, int sourceLineStride);
  28832. /** Copies a section of the image to somewhere else within itself.
  28833. */
  28834. virtual void moveImageSection (int destX, int destY,
  28835. int sourceX, int sourceY,
  28836. int width, int height);
  28837. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28838. of the image.
  28839. @param result the list that will have the area added to it
  28840. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28841. above this level will be considered opaque
  28842. */
  28843. void createSolidAreaMask (RectangleList& result,
  28844. const float alphaThreshold = 0.5f) const;
  28845. juce_UseDebuggingNewOperator
  28846. /** Creates a context suitable for drawing onto this image.
  28847. Don't call this method directly! It's used internally by the Graphics class.
  28848. */
  28849. virtual LowLevelGraphicsContext* createLowLevelContext();
  28850. protected:
  28851. const PixelFormat format;
  28852. const int imageWidth, imageHeight;
  28853. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28854. Image (const PixelFormat format,
  28855. const int imageWidth,
  28856. const int imageHeight);
  28857. int pixelStride, lineStride;
  28858. uint8* imageData;
  28859. private:
  28860. const Image& operator= (const Image&);
  28861. };
  28862. #endif // __JUCE_IMAGE_JUCEHEADER__
  28863. /********* End of inlined file: juce_Image.h *********/
  28864. /**
  28865. A Brush that fills areas with tiled repetitions of an image.
  28866. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28867. */
  28868. class JUCE_API ImageBrush : public Brush
  28869. {
  28870. public:
  28871. /* Creates an image brush, ready for use in Graphics::setBrush().
  28872. (x, y) is an anchor point for the top-left of the image
  28873. A reference to the image passed in will be kept, so don't delete
  28874. it within the lifetime of this object
  28875. */
  28876. ImageBrush (Image* const image,
  28877. const int anchorX,
  28878. const int anchorY,
  28879. const float opacity) throw();
  28880. /** Destructor. */
  28881. ~ImageBrush() throw();
  28882. Brush* createCopy() const throw();
  28883. void applyTransform (const AffineTransform& transform) throw();
  28884. void multiplyOpacity (const float multiple) throw();
  28885. bool isInvisible() const throw();
  28886. void paintPath (LowLevelGraphicsContext& context,
  28887. const Path& path, const AffineTransform& transform) throw();
  28888. void paintRectangle (LowLevelGraphicsContext& context,
  28889. int x, int y, int w, int h) throw();
  28890. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28891. const Image& alphaChannelImage, int imageX, int imageY,
  28892. int x, int y, int w, int h) throw();
  28893. juce_UseDebuggingNewOperator
  28894. protected:
  28895. Image* image;
  28896. int anchorX, anchorY;
  28897. float opacity;
  28898. private:
  28899. ImageBrush (const ImageBrush&);
  28900. const ImageBrush& operator= (const ImageBrush&);
  28901. void getStartXY (int& x, int& y) const throw();
  28902. };
  28903. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28904. /********* End of inlined file: juce_ImageBrush.h *********/
  28905. #endif
  28906. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28907. #endif
  28908. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28909. #endif
  28910. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28911. #endif
  28912. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28913. #endif
  28914. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28915. #endif
  28916. #ifndef __JUCE_FONT_JUCEHEADER__
  28917. #endif
  28918. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28919. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28920. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28921. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28922. /**
  28923. An glyph from a particular font, with a particular size, style,
  28924. typeface and position.
  28925. @see GlyphArrangement, Font
  28926. */
  28927. class JUCE_API PositionedGlyph
  28928. {
  28929. public:
  28930. /** Returns the character the glyph represents. */
  28931. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28932. /** Checks whether the glyph is actually empty. */
  28933. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28934. /** Returns the position of the glyph's left-hand edge. */
  28935. float getLeft() const throw() { return x; }
  28936. /** Returns the position of the glyph's right-hand edge. */
  28937. float getRight() const throw() { return x + w; }
  28938. /** Returns the y position of the glyph's baseline. */
  28939. float getBaselineY() const throw() { return y; }
  28940. /** Returns the y position of the top of the glyph. */
  28941. float getTop() const throw() { return y - fontAscent; }
  28942. /** Returns the y position of the bottom of the glyph. */
  28943. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28944. /** Shifts the glyph's position by a relative amount. */
  28945. void moveBy (const float deltaX,
  28946. const float deltaY) throw();
  28947. /** Draws the glyph into a graphics context. */
  28948. void draw (const Graphics& g) const throw();
  28949. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28950. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28951. /** Returns the path for this glyph.
  28952. @param path the glyph's outline will be appended to this path
  28953. */
  28954. void createPath (Path& path) const throw();
  28955. /** Checks to see if a point lies within this glyph. */
  28956. bool hitTest (float x, float y) const throw();
  28957. juce_UseDebuggingNewOperator
  28958. private:
  28959. friend class GlyphArrangement;
  28960. float x, y, w;
  28961. float fontHeight, fontAscent, fontHorizontalScale;
  28962. bool isUnderlined;
  28963. const TypefaceGlyphInfo* glyphInfo;
  28964. PositionedGlyph() throw();
  28965. };
  28966. /**
  28967. A set of glyphs, each with a position.
  28968. You can create a GlyphArrangement, text to it and then draw it onto a
  28969. graphics context. It's used internally by the text methods in the
  28970. Graphics class, but can be used directly if more control is needed.
  28971. @see Font, PositionedGlyph
  28972. */
  28973. class JUCE_API GlyphArrangement
  28974. {
  28975. public:
  28976. /** Creates an empty arrangement. */
  28977. GlyphArrangement() throw();
  28978. /** Takes a copy of another arrangement. */
  28979. GlyphArrangement (const GlyphArrangement& other) throw();
  28980. /** Copies another arrangement onto this one.
  28981. To add another arrangement without clearing this one, use addGlyphArrangement().
  28982. */
  28983. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28984. /** Destructor. */
  28985. ~GlyphArrangement() throw();
  28986. /** Returns the total number of glyphs in the arrangement. */
  28987. int getNumGlyphs() const throw() { return numGlyphs; }
  28988. /** Returns one of the glyphs from the arrangement.
  28989. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28990. careful not to pass an out-of-range index here, as it
  28991. doesn't do any bounds-checking.
  28992. */
  28993. PositionedGlyph& getGlyph (const int index) const throw();
  28994. /** Clears all text from the arrangement and resets it.
  28995. */
  28996. void clear() throw();
  28997. /** Appends a line of text to the arrangement.
  28998. This will add the text as a single line, where x is the left-hand edge of the
  28999. first character, and y is the position for the text's baseline.
  29000. If the text contains new-lines or carriage-returns, this will ignore them - use
  29001. addJustifiedText() to add multi-line arrangements.
  29002. */
  29003. void addLineOfText (const Font& font,
  29004. const String& text,
  29005. const float x,
  29006. const float y) throw();
  29007. /** Adds a line of text, truncating it if it's wider than a specified size.
  29008. This is the same as addLineOfText(), but if the line's width exceeds the value
  29009. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  29010. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  29011. */
  29012. void addCurtailedLineOfText (const Font& font,
  29013. const String& text,
  29014. float x,
  29015. const float y,
  29016. const float maxWidthPixels,
  29017. const bool useEllipsis) throw();
  29018. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  29019. This will add text to the arrangement, breaking it into new lines either where there
  29020. is a new-line or carriage-return character in the text, or where a line's width
  29021. exceeds the value set in maxLineWidth.
  29022. Each line that is added will be laid out using the flags set in horizontalLayout, so
  29023. the lines can be left- or right-justified, or centred horizontally in the space
  29024. between x and (x + maxLineWidth).
  29025. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  29026. lines will be placed below it, separated by a distance of font.getHeight().
  29027. */
  29028. void addJustifiedText (const Font& font,
  29029. const String& text,
  29030. float x, float y,
  29031. const float maxLineWidth,
  29032. const Justification& horizontalLayout) throw();
  29033. /** Tries to fit some text withing a given space.
  29034. This does its best to make the given text readable within the specified rectangle,
  29035. so it useful for labelling things.
  29036. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  29037. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  29038. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  29039. it's been truncated.
  29040. A Justification parameter lets you specify how the text is laid out within the rectangle,
  29041. both horizontally and vertically.
  29042. @see Graphics::drawFittedText
  29043. */
  29044. void addFittedText (const Font& font,
  29045. const String& text,
  29046. float x, float y,
  29047. float width, float height,
  29048. const Justification& layout,
  29049. int maximumLinesToUse,
  29050. const float minimumHorizontalScale = 0.7f) throw();
  29051. /** Appends another glyph arrangement to this one. */
  29052. void addGlyphArrangement (const GlyphArrangement& other) throw();
  29053. /** Draws this glyph arrangement to a graphics context.
  29054. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  29055. method, which renders the glyphs as filled vectors.
  29056. */
  29057. void draw (const Graphics& g) const throw();
  29058. /** Draws this glyph arrangement to a graphics context.
  29059. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  29060. method for non-transformed arrangements.
  29061. */
  29062. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29063. /** Converts the set of glyphs into a path.
  29064. @param path the glyphs' outlines will be appended to this path
  29065. */
  29066. void createPath (Path& path) const throw();
  29067. /** Looks for a glyph that contains the given co-ordinate.
  29068. @returns the index of the glyph, or -1 if none were found.
  29069. */
  29070. int findGlyphIndexAt (float x, float y) const throw();
  29071. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  29072. @param startIndex the first glyph to test
  29073. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  29074. startIndex will be included
  29075. @param left on return, the leftmost co-ordinate of the rectangle
  29076. @param top on return, the top co-ordinate of the rectangle
  29077. @param right on return, the rightmost co-ordinate of the rectangle
  29078. @param bottom on return, the bottom co-ordinate of the rectangle
  29079. @param includeWhitespace if true, the extent of any whitespace characters will also
  29080. be taken into account
  29081. */
  29082. void getBoundingBox (int startIndex,
  29083. int numGlyphs,
  29084. float& left,
  29085. float& top,
  29086. float& right,
  29087. float& bottom,
  29088. const bool includeWhitespace) const throw();
  29089. /** Shifts a set of glyphs by a given amount.
  29090. @param startIndex the first glyph to transform
  29091. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  29092. startIndex will be used
  29093. @param deltaX the amount to add to their x-positions
  29094. @param deltaY the amount to add to their y-positions
  29095. */
  29096. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  29097. const float deltaX,
  29098. const float deltaY) throw();
  29099. /** Removes a set of glyphs from the arrangement.
  29100. @param startIndex the first glyph to remove
  29101. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  29102. startIndex will be deleted
  29103. */
  29104. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  29105. /** Expands or compresses a set of glyphs horizontally.
  29106. @param startIndex the first glyph to transform
  29107. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  29108. startIndex will be used
  29109. @param horizontalScaleFactor how much to scale their horizontal width by
  29110. */
  29111. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  29112. const float horizontalScaleFactor) throw();
  29113. /** Justifies a set of glyphs within a given space.
  29114. This moves the glyphs as a block so that the whole thing is located within the
  29115. given rectangle with the specified layout.
  29116. If the Justification::horizontallyJustified flag is specified, each line will
  29117. be stretched out to fill the specified width.
  29118. */
  29119. void justifyGlyphs (const int startIndex, const int numGlyphs,
  29120. const float x,
  29121. const float y,
  29122. const float width,
  29123. const float height,
  29124. const Justification& justification) throw();
  29125. juce_UseDebuggingNewOperator
  29126. private:
  29127. int numGlyphs, numAllocated;
  29128. PositionedGlyph* glyphs;
  29129. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  29130. void removeLast() throw();
  29131. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  29132. void incGlyphRefCount (const int index) const throw();
  29133. void decGlyphRefCount (const int index) const throw();
  29134. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  29135. };
  29136. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29137. /********* End of inlined file: juce_GlyphArrangement.h *********/
  29138. #endif
  29139. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29140. /********* Start of inlined file: juce_TextLayout.h *********/
  29141. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29142. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  29143. class Graphics;
  29144. /**
  29145. A laid-out arrangement of text.
  29146. You can add text in different fonts to a TextLayout object, then call its
  29147. layout() method to word-wrap it into lines. The layout can then be drawn
  29148. using a graphics context.
  29149. It's handy if you've got a message to display, because you can format it,
  29150. measure the extent of the layout, and then create a suitably-sized window
  29151. to show it in.
  29152. @see Font, Graphics::drawFittedText, GlyphArrangement
  29153. */
  29154. class JUCE_API TextLayout
  29155. {
  29156. public:
  29157. /** Creates an empty text layout.
  29158. Text can then be appended using the appendText() method.
  29159. */
  29160. TextLayout() throw();
  29161. /** Creates a copy of another layout object. */
  29162. TextLayout (const TextLayout& other) throw();
  29163. /** Creates a text layout from an initial string and font. */
  29164. TextLayout (const String& text, const Font& font) throw();
  29165. /** Destructor. */
  29166. ~TextLayout() throw();
  29167. /** Copies another layout onto this one. */
  29168. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  29169. /** Clears the layout, removing all its text. */
  29170. void clear() throw();
  29171. /** Adds a string to the end of the arrangement.
  29172. The string will be broken onto new lines wherever it contains
  29173. carriage-returns or linefeeds. After adding it, you can call layout()
  29174. to wrap long lines into a paragraph and justify it.
  29175. */
  29176. void appendText (const String& textToAppend,
  29177. const Font& fontToUse) throw();
  29178. /** Replaces all the text with a new string.
  29179. This is equivalent to calling clear() followed by appendText().
  29180. */
  29181. void setText (const String& newText,
  29182. const Font& fontToUse) throw();
  29183. /** Breaks the text up to form a paragraph with the given width.
  29184. @param maximumWidth any text wider than this will be split
  29185. across multiple lines
  29186. @param justification how the lines are to be laid-out horizontally
  29187. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29188. width that keeps all the lines of text at a
  29189. similar length - this is good when you're displaying
  29190. a short message and don't want it to get split
  29191. onto two lines with only a couple of words on
  29192. the second line, which looks untidy.
  29193. */
  29194. void layout (int maximumWidth,
  29195. const Justification& justification,
  29196. const bool attemptToBalanceLineLengths) throw();
  29197. /** Returns the overall width of the entire text layout. */
  29198. int getWidth() const throw();
  29199. /** Returns the overall height of the entire text layout. */
  29200. int getHeight() const throw();
  29201. /** Returns the total number of lines of text. */
  29202. int getNumLines() const throw() { return totalLines; }
  29203. /** Returns the width of a particular line of text.
  29204. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29205. */
  29206. int getLineWidth (const int lineNumber) const throw();
  29207. /** Renders the text at a specified position using a graphics context.
  29208. */
  29209. void draw (Graphics& g,
  29210. const int topLeftX,
  29211. const int topLeftY) const throw();
  29212. /** Renders the text within a specified rectangle using a graphics context.
  29213. The justification flags dictate how the block of text should be positioned
  29214. within the rectangle.
  29215. */
  29216. void drawWithin (Graphics& g,
  29217. int x, int y, int w, int h,
  29218. const Justification& layoutFlags) const throw();
  29219. juce_UseDebuggingNewOperator
  29220. private:
  29221. VoidArray tokens;
  29222. int totalLines;
  29223. };
  29224. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29225. /********* End of inlined file: juce_TextLayout.h *********/
  29226. #endif
  29227. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29228. #endif
  29229. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29230. /********* Start of inlined file: juce_EdgeTable.h *********/
  29231. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29232. #define __JUCE_EDGETABLE_JUCEHEADER__
  29233. class Path;
  29234. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  29235. /**
  29236. A table of horizontal scan-line segments - used for rasterising Paths.
  29237. @see Path, Graphics
  29238. */
  29239. class JUCE_API EdgeTable
  29240. {
  29241. public:
  29242. /** Indicates the quality at which the edge table should be generated.
  29243. Higher values will have better quality anti-aliasing, but will take
  29244. longer to generate the edge table and to render it.
  29245. */
  29246. enum OversamplingLevel
  29247. {
  29248. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  29249. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  29250. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  29251. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  29252. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  29253. normal user-interface use. */
  29254. };
  29255. /** Creates an empty edge table ready to have paths added.
  29256. A table is created with a fixed vertical size, and only sections of paths
  29257. which lie within their range will be added to the table.
  29258. @param topY the lowest y co-ordinate that the table can contain
  29259. @param height the number of horizontal lines it can contain
  29260. @param verticalOversampling the amount of oversampling used for anti-aliasing
  29261. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  29262. worth changing this except for very special purposes
  29263. */
  29264. EdgeTable (const int topY,
  29265. const int height,
  29266. const OversamplingLevel verticalOversampling = Oversampling_4times,
  29267. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  29268. /** Creates a copy of another edge table. */
  29269. EdgeTable (const EdgeTable& other) throw();
  29270. /** Copies from another edge table. */
  29271. const EdgeTable& operator= (const EdgeTable& other) throw();
  29272. /** Destructor. */
  29273. ~EdgeTable() throw();
  29274. /** Adds edges to the table for a path.
  29275. This will add horizontal lines to the edge table for any parts of the path
  29276. which lie within the vertical bounds for which this table was created.
  29277. @param path the path to add
  29278. @param transform an optional transform to apply to the path while it's
  29279. being added
  29280. */
  29281. void addPath (const Path& path,
  29282. const AffineTransform& transform) throw();
  29283. /** Reduces the amount of space the table has allocated.
  29284. This will shrink the table down to use as little memory as possible - useful for
  29285. read-only tables that get stored and re-used for rendering.
  29286. */
  29287. void optimiseTable() throw();
  29288. /** Iterates the lines in the table, for rendering.
  29289. This function will iterate each line in the table, and call a user-defined class
  29290. to render each pixel or continuous line of pixels that the table contains.
  29291. @param iterationCallback this templated class must contain the following methods:
  29292. @code
  29293. inline void setEdgeTableYPos (int y);
  29294. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  29295. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  29296. @endcode
  29297. (these don't necessarily have to be 'const', but it might help it go faster)
  29298. @param clipLeft the left-hand edge of the rectangle which should be iterated
  29299. @param clipTop the top edge of the rectangle which should be iterated
  29300. @param clipRight the right-hand edge of the rectangle which should be iterated
  29301. @param clipBottom the bottom edge of the rectangle which should be iterated
  29302. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  29303. */
  29304. template <class EdgeTableIterationCallback>
  29305. void iterate (EdgeTableIterationCallback& iterationCallback,
  29306. const int clipLeft,
  29307. int clipTop,
  29308. const int clipRight,
  29309. int clipBottom,
  29310. const int subPixelXOffset) const
  29311. {
  29312. if (clipTop < top)
  29313. clipTop = top;
  29314. if (clipBottom > top + height)
  29315. clipBottom = top + height;
  29316. const int* singleLine = table + lineStrideElements
  29317. * ((clipTop - top) << (int) oversampling);
  29318. int mergedLineAllocation = 128;
  29319. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  29320. int* mergedLine = (int*) temp.getData();
  29321. const int timesOverSampling = 1 << (int) oversampling;
  29322. for (int y = clipTop; y < clipBottom; ++y)
  29323. {
  29324. int numMergedPoints = 0;
  29325. // sort all the oversampled lines into a single merged line ready to draw..
  29326. for (int over = timesOverSampling; --over >= 0;)
  29327. {
  29328. const int* l = singleLine;
  29329. singleLine += lineStrideElements;
  29330. int num = *l;
  29331. jassert (num >= 0);
  29332. if (num > 0)
  29333. {
  29334. if (numMergedPoints + num >= mergedLineAllocation)
  29335. {
  29336. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  29337. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  29338. mergedLine = (int*) temp.getData();
  29339. }
  29340. while (--num >= 0)
  29341. {
  29342. const int x = *++l;
  29343. const int winding = *++l;
  29344. int n = numMergedPoints << 1;
  29345. while (n > 0)
  29346. {
  29347. const int cx = mergedLine [n - 2];
  29348. if (cx <= x)
  29349. break;
  29350. mergedLine [n] = cx;
  29351. --n;
  29352. mergedLine [n + 2] = mergedLine [n];
  29353. --n;
  29354. }
  29355. mergedLine [n] = x;
  29356. mergedLine [n + 1] = winding;
  29357. ++numMergedPoints;
  29358. }
  29359. }
  29360. }
  29361. if (--numMergedPoints > 0)
  29362. {
  29363. const int* line = mergedLine;
  29364. int x = subPixelXOffset + *line;
  29365. int level = *++line;
  29366. int levelAccumulator = 0;
  29367. iterationCallback.setEdgeTableYPos (y);
  29368. while (--numMergedPoints >= 0)
  29369. {
  29370. const int endX = subPixelXOffset + *++line;
  29371. jassert (endX >= x);
  29372. const int absLevel = abs (level);
  29373. int endOfRun = (endX >> 8);
  29374. if (endOfRun == (x >> 8))
  29375. {
  29376. // small segment within the same pixel, so just save it for the next
  29377. // time round..
  29378. levelAccumulator += (endX - x) * absLevel;
  29379. }
  29380. else
  29381. {
  29382. // plot the fist pixel of this segment, including any accumulated
  29383. // levels from smaller segments that haven't been drawn yet
  29384. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  29385. levelAccumulator >>= 8;
  29386. if (levelAccumulator > 0xff)
  29387. levelAccumulator = 0xff;
  29388. x >>= 8;
  29389. if (x >= clipRight)
  29390. {
  29391. levelAccumulator = 0;
  29392. break;
  29393. }
  29394. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  29395. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29396. if (++x >= clipRight)
  29397. {
  29398. levelAccumulator = 0;
  29399. break;
  29400. }
  29401. // if there's a segment of solid pixels, do it all in one go..
  29402. if (absLevel > 0 && endOfRun > x)
  29403. {
  29404. if (x < clipLeft)
  29405. x = clipLeft;
  29406. if (endOfRun > clipRight)
  29407. endOfRun = clipRight;
  29408. const int numPix = endOfRun - x;
  29409. if (numPix > 0)
  29410. iterationCallback.handleEdgeTableLine (x, numPix,
  29411. jmin (absLevel, 0xff));
  29412. }
  29413. // save the bit at the end to be drawn next time round the loop.
  29414. levelAccumulator = (endX & 0xff) * absLevel;
  29415. }
  29416. level += *++line;
  29417. x = endX;
  29418. }
  29419. if (levelAccumulator > 0)
  29420. {
  29421. levelAccumulator >>= 8;
  29422. if (levelAccumulator > 0xff)
  29423. levelAccumulator = 0xff;
  29424. x >>= 8;
  29425. if (x >= clipLeft && x < clipRight)
  29426. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29427. }
  29428. }
  29429. }
  29430. }
  29431. juce_UseDebuggingNewOperator
  29432. private:
  29433. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29434. int* table;
  29435. int top, height, maxEdgesPerLine, lineStrideElements;
  29436. OversamplingLevel oversampling;
  29437. // this will assume that the y co-ord is within bounds, and will avoid checking
  29438. // this for speed.
  29439. void addEdgePoint (const int x, const int y, const int winding) throw();
  29440. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29441. };
  29442. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29443. /********* End of inlined file: juce_EdgeTable.h *********/
  29444. #endif
  29445. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29446. #endif
  29447. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29448. #endif
  29449. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29450. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29451. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29452. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29453. /**
  29454. Interface class for graphics context objects, used internally by the Graphics class.
  29455. Users are not supposed to create instances of this class directly - do your drawing
  29456. via the Graphics object instead.
  29457. It's a base class for different types of graphics context, that may perform software-based
  29458. or OS-accelerated rendering.
  29459. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29460. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29461. context.
  29462. */
  29463. class JUCE_API LowLevelGraphicsContext
  29464. {
  29465. protected:
  29466. LowLevelGraphicsContext();
  29467. public:
  29468. virtual ~LowLevelGraphicsContext();
  29469. /** Returns true if this device is vector-based, e.g. a printer. */
  29470. virtual bool isVectorDevice() const = 0;
  29471. /** Moves the origin to a new position.
  29472. The co-ords are relative to the current origin, and indicate the new position
  29473. of (0, 0).
  29474. */
  29475. virtual void setOrigin (int x, int y) = 0;
  29476. /** Cliping co-ords are relative to the origin. */
  29477. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29478. /** Cliping co-ords are relative to the origin. */
  29479. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29480. /** Cliping co-ords are relative to the origin. */
  29481. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29482. virtual void saveState() = 0;
  29483. virtual void restoreState() = 0;
  29484. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29485. virtual const Rectangle getClipBounds() const = 0;
  29486. virtual bool isClipEmpty() const = 0;
  29487. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29488. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29489. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29490. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29491. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29492. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29493. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29494. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29495. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29496. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29497. virtual void blendImage (const Image& sourceImage,
  29498. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29499. float alpha) = 0;
  29500. virtual void blendImageRescaling (const Image& sourceImage,
  29501. int destX, int destY, int destW, int destH,
  29502. int sourceX, int sourceY, int sourceW, int sourceH,
  29503. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29504. virtual void blendImageWarping (const Image& sourceImage,
  29505. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29506. const AffineTransform& transform,
  29507. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29508. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29509. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29510. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29511. };
  29512. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29513. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29514. #endif
  29515. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29516. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29517. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29518. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29519. /**
  29520. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29521. into a PostScript document.
  29522. */
  29523. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29524. {
  29525. public:
  29526. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29527. const String& documentTitle,
  29528. const int totalWidth,
  29529. const int totalHeight);
  29530. ~LowLevelGraphicsPostScriptRenderer();
  29531. bool isVectorDevice() const;
  29532. void setOrigin (int x, int y);
  29533. bool reduceClipRegion (int x, int y, int w, int h);
  29534. bool reduceClipRegion (const RectangleList& clipRegion);
  29535. void excludeClipRegion (int x, int y, int w, int h);
  29536. void saveState();
  29537. void restoreState();
  29538. bool clipRegionIntersects (int x, int y, int w, int h);
  29539. const Rectangle getClipBounds() const;
  29540. bool isClipEmpty() const;
  29541. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29542. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29543. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29544. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29545. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29546. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29547. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29548. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29549. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29550. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29551. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29552. int sourceX, int sourceY, float alpha);
  29553. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29554. int sourceX, int sourceY, int sourceW, int sourceH,
  29555. float alpha, const Graphics::ResamplingQuality quality);
  29556. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29557. const AffineTransform& transform,
  29558. float alpha, const Graphics::ResamplingQuality quality);
  29559. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29560. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29561. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29562. juce_UseDebuggingNewOperator
  29563. protected:
  29564. OutputStream& out;
  29565. RectangleList* clip;
  29566. int totalWidth, totalHeight, xOffset, yOffset;
  29567. bool needToClip;
  29568. Colour lastColour;
  29569. struct SavedState
  29570. {
  29571. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29572. ~SavedState();
  29573. RectangleList* clip;
  29574. const int xOffset, yOffset;
  29575. private:
  29576. SavedState (const SavedState&);
  29577. const SavedState& operator= (const SavedState&);
  29578. };
  29579. OwnedArray <SavedState> stateStack;
  29580. void writeClip();
  29581. void writeColour (const Colour& colour);
  29582. void writePath (const Path& path) const;
  29583. void writeXY (const float x, const float y) const;
  29584. void writeTransform (const AffineTransform& trans) const;
  29585. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29586. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29587. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29588. };
  29589. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29590. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29591. #endif
  29592. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29593. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29594. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29595. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29596. /**
  29597. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29598. its rendering in memory.
  29599. User code is not supposed to create instances of this class directly - do all your
  29600. rendering via the Graphics class instead.
  29601. */
  29602. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29603. {
  29604. public:
  29605. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29606. ~LowLevelGraphicsSoftwareRenderer();
  29607. bool isVectorDevice() const;
  29608. void setOrigin (int x, int y);
  29609. bool reduceClipRegion (int x, int y, int w, int h);
  29610. bool reduceClipRegion (const RectangleList& clipRegion);
  29611. void excludeClipRegion (int x, int y, int w, int h);
  29612. void saveState();
  29613. void restoreState();
  29614. bool clipRegionIntersects (int x, int y, int w, int h);
  29615. const Rectangle getClipBounds() const;
  29616. bool isClipEmpty() const;
  29617. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29618. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29619. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29620. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29621. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29622. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29623. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29624. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29625. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29626. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29627. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29628. int sourceX, int sourceY, float alpha);
  29629. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29630. int sourceX, int sourceY, int sourceW, int sourceH,
  29631. float alpha, const Graphics::ResamplingQuality quality);
  29632. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29633. const AffineTransform& transform,
  29634. float alpha, const Graphics::ResamplingQuality quality);
  29635. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29636. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29637. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29638. RectangleList* getRawClipRegion() throw() { return clip; }
  29639. juce_UseDebuggingNewOperator
  29640. protected:
  29641. Image& image;
  29642. RectangleList* clip;
  29643. int xOffset, yOffset;
  29644. struct SavedState
  29645. {
  29646. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29647. ~SavedState();
  29648. RectangleList* clip;
  29649. const int xOffset, yOffset;
  29650. private:
  29651. SavedState (const SavedState&);
  29652. const SavedState& operator= (const SavedState&);
  29653. };
  29654. OwnedArray <SavedState> stateStack;
  29655. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29656. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29657. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29658. const Path& path, const AffineTransform& transform,
  29659. int& x, int& y, int& w, int& h) const;
  29660. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29661. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29662. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29663. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29664. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29665. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29666. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29667. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29668. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29669. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29670. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29671. float alpha);
  29672. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29673. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29674. const AffineTransform& transform,
  29675. float alpha, const Graphics::ResamplingQuality quality);
  29676. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29677. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29678. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29679. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29680. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29681. };
  29682. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29683. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29684. #endif
  29685. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29686. #endif
  29687. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29688. #endif
  29689. #ifndef __JUCE_LINE_JUCEHEADER__
  29690. #endif
  29691. #ifndef __JUCE_PATH_JUCEHEADER__
  29692. #endif
  29693. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29694. /********* Start of inlined file: juce_PathIterator.h *********/
  29695. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29696. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29697. /**
  29698. Flattens a Path object into a series of straight-line sections.
  29699. Use one of these to iterate through a Path object, and it will convert
  29700. all the curves into line sections so it's easy to render or perform
  29701. geometric operations on.
  29702. @see Path
  29703. */
  29704. class JUCE_API PathFlatteningIterator
  29705. {
  29706. public:
  29707. /** Creates a PathFlatteningIterator.
  29708. After creation, use the next() method to initialise the fields in the
  29709. object with the first line's position.
  29710. @param path the path to iterate along
  29711. @param transform a transform to apply to each point in the path being iterated
  29712. @param tolerence the amount by which the curves are allowed to deviate from the
  29713. lines into which they are being broken down - a higher tolerence
  29714. is a bit faster, but less smooth.
  29715. */
  29716. PathFlatteningIterator (const Path& path,
  29717. const AffineTransform& transform = AffineTransform::identity,
  29718. float tolerence = 9.0f) throw();
  29719. /** Destructor. */
  29720. ~PathFlatteningIterator() throw();
  29721. /** Fetches the next line segment from the path.
  29722. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29723. so that they describe the new line segment.
  29724. @returns false when there are no more lines to fetch.
  29725. */
  29726. bool next() throw();
  29727. /** The x position of the start of the current line segment. */
  29728. float x1;
  29729. /** The y position of the start of the current line segment. */
  29730. float y1;
  29731. /** The x position of the end of the current line segment. */
  29732. float x2;
  29733. /** The y position of the end of the current line segment. */
  29734. float y2;
  29735. /** Indicates whether the current line segment is closing a sub-path.
  29736. If the current line is the one that connects the end of a sub-path
  29737. back to the start again, this will be true.
  29738. */
  29739. bool closesSubPath;
  29740. /** The index of the current line within the current sub-path.
  29741. E.g. you can use this to see whether the line is the first one in the
  29742. subpath by seeing if it's 0.
  29743. */
  29744. int subPathIndex;
  29745. /** Returns true if the current segment is the last in the current sub-path. */
  29746. bool isLastInSubpath() const throw() { return stackPos == stackBase
  29747. && (index >= path.numElements
  29748. || points [index] == Path::moveMarker); }
  29749. juce_UseDebuggingNewOperator
  29750. private:
  29751. const Path& path;
  29752. const AffineTransform transform;
  29753. float* points;
  29754. float tolerence, subPathCloseX, subPathCloseY;
  29755. bool isIdentityTransform;
  29756. float* stackBase;
  29757. float* stackPos;
  29758. int index, stackSize;
  29759. PathFlatteningIterator (const PathFlatteningIterator&);
  29760. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29761. };
  29762. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29763. /********* End of inlined file: juce_PathIterator.h *********/
  29764. #endif
  29765. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29766. #endif
  29767. #ifndef __JUCE_POINT_JUCEHEADER__
  29768. #endif
  29769. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29770. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29771. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29772. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29773. /**
  29774. A rectangle whose co-ordinates can be defined in terms of absolute or
  29775. proportional distances.
  29776. Designed mainly for storing component positions, this gives you a lot of
  29777. control over how each co-ordinate is stored, either as an absolute position,
  29778. or as a proportion of the size of a parent rectangle.
  29779. It also allows you to define the anchor points by which the rectangle is
  29780. positioned, so for example you could specify that the top right of the
  29781. rectangle should be an absolute distance from its parent's bottom-right corner.
  29782. This object can be stored as a string, which takes the form "x y w h", including
  29783. symbols like '%' and letters to indicate the anchor point. See its toString()
  29784. method for more info.
  29785. Example usage:
  29786. @code
  29787. class MyComponent
  29788. {
  29789. void resized()
  29790. {
  29791. // this will set the child component's x to be 20% of our width, its y
  29792. // to be 30, its width to be 150, and its height to be 50% of our
  29793. // height..
  29794. const PositionedRectangle pos1 ("20% 30 150 50%");
  29795. pos1.applyToComponent (*myChildComponent1);
  29796. // this will inset the child component with a gap of 10 pixels
  29797. // around each of its edges..
  29798. const PositionedRectangle pos2 ("10 10 20M 20M");
  29799. pos2.applyToComponent (*myChildComponent2);
  29800. }
  29801. };
  29802. @endcode
  29803. */
  29804. class JUCE_API PositionedRectangle
  29805. {
  29806. public:
  29807. /** Creates an empty rectangle with all co-ordinates set to zero.
  29808. The default anchor point is top-left; the default
  29809. */
  29810. PositionedRectangle() throw();
  29811. /** Initialises a PositionedRectangle from a saved string version.
  29812. The string must be in the format generated by toString().
  29813. */
  29814. PositionedRectangle (const String& stringVersion) throw();
  29815. /** Creates a copy of another PositionedRectangle. */
  29816. PositionedRectangle (const PositionedRectangle& other) throw();
  29817. /** Copies another PositionedRectangle. */
  29818. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29819. /** Destructor. */
  29820. ~PositionedRectangle() throw();
  29821. /** Returns a string version of this position, from which it can later be
  29822. re-generated.
  29823. The format is four co-ordinates, "x y w h".
  29824. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29825. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29826. as a percentage, e.g. "80%".
  29827. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29828. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29829. the parent's right-hand edge.
  29830. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29831. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29832. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29833. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29834. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29835. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29836. has "c" appended to it. So "-50Rc" would mean that this component's
  29837. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29838. this component's centre should be placed 40% across the parent's width.
  29839. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29840. the number has "M" appended to it.
  29841. To reload a stored string, use the constructor that takes a string parameter.
  29842. */
  29843. const String toString() const throw();
  29844. /** Calculates the absolute position, given the size of the space that
  29845. it should go in.
  29846. This will work out any proportional distances and sizes relative to the
  29847. target rectangle, and will return the absolute position.
  29848. @see applyToComponent
  29849. */
  29850. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29851. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29852. */
  29853. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29854. double& x,
  29855. double& y,
  29856. double& width,
  29857. double& height) const throw();
  29858. /** This sets the bounds of the given component to this position.
  29859. This is equivalent to writing:
  29860. @code
  29861. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29862. @endcode
  29863. @see getRectangle, updateFromComponent
  29864. */
  29865. void applyToComponent (Component& comp) const throw();
  29866. /** Updates this object's co-ordinates to match the given rectangle.
  29867. This will set all co-ordinates based on the given rectangle, re-calculating
  29868. any proportional distances, and using the current anchor points.
  29869. So for example if the x co-ordinate mode is currently proportional, this will
  29870. re-calculate x based on the rectangle's relative position within the target
  29871. rectangle's width.
  29872. If the target rectangle's width or height are zero then it may not be possible
  29873. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29874. will not be changed.
  29875. */
  29876. void updateFrom (const Rectangle& newPosition,
  29877. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29878. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29879. */
  29880. void updateFromDouble (const double x, const double y,
  29881. const double width, const double height,
  29882. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29883. /** Updates this object's co-ordinates to match the bounds of this component.
  29884. This is equivalent to calling updateFrom() with the component's bounds and
  29885. it parent size.
  29886. If the component doesn't currently have a parent, then proportional co-ordinates
  29887. might not be updated because it would need to know the parent's size to do the
  29888. maths for this.
  29889. */
  29890. void updateFromComponent (const Component& comp) throw();
  29891. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29892. enum AnchorPoint
  29893. {
  29894. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29895. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29896. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29897. };
  29898. /** Specifies how an x or y co-ordinate should be interpreted. */
  29899. enum PositionMode
  29900. {
  29901. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29902. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29903. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29904. 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. */
  29905. };
  29906. /** Specifies how the width or height should be interpreted. */
  29907. enum SizeMode
  29908. {
  29909. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29910. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29911. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29912. };
  29913. /** Sets all options for all co-ordinates.
  29914. This requires a reference rectangle to be specified, because if you're changing any
  29915. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29916. the co-ordinates, and will need to know the parent size so it can calculate this.
  29917. */
  29918. void setModes (const AnchorPoint xAnchorMode,
  29919. const PositionMode xPositionMode,
  29920. const AnchorPoint yAnchorMode,
  29921. const PositionMode yPositionMode,
  29922. const SizeMode widthMode,
  29923. const SizeMode heightMode,
  29924. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29925. /** Returns the anchoring mode for the x co-ordinate.
  29926. To change any of the modes, use setModes().
  29927. */
  29928. AnchorPoint getAnchorPointX() const throw();
  29929. /** Returns the positioning mode for the x co-ordinate.
  29930. To change any of the modes, use setModes().
  29931. */
  29932. PositionMode getPositionModeX() const throw();
  29933. /** Returns the raw x co-ordinate.
  29934. If the x position mode is absolute, then this will be the absolute value. If it's
  29935. proportional, then this will be a fractional proportion, where 1.0 means the full
  29936. width of the parent space.
  29937. */
  29938. double getX() const throw() { return x; }
  29939. /** Sets the raw value of the x co-ordinate.
  29940. See getX() for the meaning of this value.
  29941. */
  29942. void setX (const double newX) throw() { x = newX; }
  29943. /** Returns the anchoring mode for the y co-ordinate.
  29944. To change any of the modes, use setModes().
  29945. */
  29946. AnchorPoint getAnchorPointY() const throw();
  29947. /** Returns the positioning mode for the y co-ordinate.
  29948. To change any of the modes, use setModes().
  29949. */
  29950. PositionMode getPositionModeY() const throw();
  29951. /** Returns the raw y co-ordinate.
  29952. If the y position mode is absolute, then this will be the absolute value. If it's
  29953. proportional, then this will be a fractional proportion, where 1.0 means the full
  29954. height of the parent space.
  29955. */
  29956. double getY() const throw() { return y; }
  29957. /** Sets the raw value of the y co-ordinate.
  29958. See getY() for the meaning of this value.
  29959. */
  29960. void setY (const double newY) throw() { y = newY; }
  29961. /** Returns the mode used to calculate the width.
  29962. To change any of the modes, use setModes().
  29963. */
  29964. SizeMode getWidthMode() const throw();
  29965. /** Returns the raw width value.
  29966. If the width mode is absolute, then this will be the absolute value. If the mode is
  29967. proportional, then this will be a fractional proportion, where 1.0 means the full
  29968. width of the parent space.
  29969. */
  29970. double getWidth() const throw() { return w; }
  29971. /** Sets the raw width value.
  29972. See getWidth() for the details about what this value means.
  29973. */
  29974. void setWidth (const double newWidth) throw() { w = newWidth; }
  29975. /** Returns the mode used to calculate the height.
  29976. To change any of the modes, use setModes().
  29977. */
  29978. SizeMode getHeightMode() const throw();
  29979. /** Returns the raw height value.
  29980. If the height mode is absolute, then this will be the absolute value. If the mode is
  29981. proportional, then this will be a fractional proportion, where 1.0 means the full
  29982. height of the parent space.
  29983. */
  29984. double getHeight() const throw() { return h; }
  29985. /** Sets the raw height value.
  29986. See getHeight() for the details about what this value means.
  29987. */
  29988. void setHeight (const double newHeight) throw() { h = newHeight; }
  29989. /** If the size and position are constance, and wouldn't be affected by changes
  29990. in the parent's size, then this will return true.
  29991. */
  29992. bool isPositionAbsolute() const throw();
  29993. /** Compares two objects. */
  29994. const bool operator== (const PositionedRectangle& other) const throw();
  29995. /** Compares two objects. */
  29996. const bool operator!= (const PositionedRectangle& other) const throw();
  29997. juce_UseDebuggingNewOperator
  29998. private:
  29999. double x, y, w, h;
  30000. uint8 xMode, yMode, wMode, hMode;
  30001. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  30002. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  30003. void decodePosString (const String& s, uint8& mode, double& value) throw();
  30004. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  30005. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  30006. const uint8 xMode, const uint8 wMode,
  30007. const int parentPos, const int parentSize) const throw();
  30008. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  30009. const uint8 xMode, const uint8 wMode,
  30010. const int parentPos, const int parentSize) const throw();
  30011. };
  30012. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30013. /********* End of inlined file: juce_PositionedRectangle.h *********/
  30014. #endif
  30015. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  30016. #endif
  30017. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  30018. #endif
  30019. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  30020. #endif
  30021. #ifndef __JUCE_IMAGE_JUCEHEADER__
  30022. #endif
  30023. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30024. /********* Start of inlined file: juce_ImageCache.h *********/
  30025. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30026. #define __JUCE_IMAGECACHE_JUCEHEADER__
  30027. /**
  30028. A global cache of images that have been loaded from files or memory.
  30029. If you're loading an image and may need to use the image in more than one
  30030. place, this is used to allow the same image to be shared rather than loading
  30031. multiple copies into memory.
  30032. Another advantage is that after images are released, they will be kept in
  30033. memory for a few seconds before it is actually deleted, so if you're repeatedly
  30034. loading/deleting the same image, it'll reduce the chances of having to reload it
  30035. each time.
  30036. @see Image, ImageFileFormat
  30037. */
  30038. class JUCE_API ImageCache : private DeletedAtShutdown,
  30039. private Timer
  30040. {
  30041. public:
  30042. /** Loads an image from a file, (or just returns the image if it's already cached).
  30043. If the cache already contains an image that was loaded from this file,
  30044. that image will be returned. Otherwise, this method will try to load the
  30045. file, add it to the cache, and return it.
  30046. It's very important not to delete the image that is returned - instead use
  30047. the ImageCache::release() method.
  30048. Also, remember that the image returned is shared, so drawing into it might
  30049. affect other things that are using it!
  30050. @param file the file to try to load
  30051. @returns the image, or null if it there was an error loading it
  30052. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30053. */
  30054. static Image* getFromFile (const File& file);
  30055. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  30056. If the cache already contains an image that was loaded from this block of memory,
  30057. that image will be returned. Otherwise, this method will try to load the
  30058. file, add it to the cache, and return it.
  30059. It's very important not to delete the image that is returned - instead use
  30060. the ImageCache::release() method.
  30061. Also, remember that the image returned is shared, so drawing into it might
  30062. affect other things that are using it!
  30063. @param imageData the block of memory containing the image data
  30064. @param dataSize the data size in bytes
  30065. @returns the image, or null if it there was an error loading it
  30066. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30067. */
  30068. static Image* getFromMemory (const void* imageData,
  30069. const int dataSize);
  30070. /** Releases an image that was previously created by the ImageCache.
  30071. If an image has been returned by the getFromFile() or getFromMemory() methods,
  30072. it mustn't be deleted directly, but should be released with this method
  30073. instead.
  30074. @see getFromFile, getFromMemory
  30075. */
  30076. static void release (Image* const imageToRelease);
  30077. /** Checks whether an image is in the cache or not.
  30078. @returns true if the image is currently in the cache
  30079. */
  30080. static bool isImageInCache (Image* const imageToLookFor);
  30081. /** Increments the reference-count for a cached image.
  30082. If the image isn't in the cache, this method won't do anything.
  30083. */
  30084. static void incReferenceCount (Image* const image);
  30085. /** Checks the cache for an image with a particular hashcode.
  30086. If there's an image in the cache with this hashcode, it will be returned,
  30087. otherwise it will return zero.
  30088. If an image is returned, it must be released with the release() method
  30089. when no longer needed, to maintain the correct reference counts.
  30090. @param hashCode the hash code that would have been associated with the
  30091. image by addImageToCache()
  30092. @see addImageToCache
  30093. */
  30094. static Image* getFromHashCode (const int64 hashCode);
  30095. /** Adds an image to the cache with a user-defined hash-code.
  30096. After calling this, responsibilty for deleting the image will be taken
  30097. by the ImageCache.
  30098. The image will be initially be given a reference count of 1, so call
  30099. the release() method to delete it.
  30100. @param image the image to add
  30101. @param hashCode the hash-code to associate with it
  30102. @see getFromHashCode
  30103. */
  30104. static void addImageToCache (Image* const image,
  30105. const int64 hashCode);
  30106. /** Changes the amount of time before an unused image will be removed from the cache.
  30107. By default this is about 5 seconds.
  30108. */
  30109. static void setCacheTimeout (const int millisecs);
  30110. juce_UseDebuggingNewOperator
  30111. private:
  30112. CriticalSection lock;
  30113. VoidArray images;
  30114. ImageCache() throw();
  30115. ImageCache (const ImageCache&);
  30116. const ImageCache& operator= (const ImageCache&);
  30117. ~ImageCache();
  30118. void timerCallback();
  30119. };
  30120. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  30121. /********* End of inlined file: juce_ImageCache.h *********/
  30122. #endif
  30123. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30124. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  30125. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30126. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30127. /**
  30128. Represents a filter kernel to use in convoluting an image.
  30129. @see Image::applyConvolution
  30130. */
  30131. class JUCE_API ImageConvolutionKernel
  30132. {
  30133. public:
  30134. /** Creates an empty convulution kernel.
  30135. @param size the length of each dimension of the kernel, so e.g. if the size
  30136. is 5, it will create a 5x5 kernel
  30137. */
  30138. ImageConvolutionKernel (const int size) throw();
  30139. /** Destructor. */
  30140. ~ImageConvolutionKernel() throw();
  30141. /** Resets all values in the kernel to zero.
  30142. */
  30143. void clear() throw();
  30144. /** Sets the value of a specific cell in the kernel.
  30145. The x and y parameters must be in the range 0 < x < getKernelSize().
  30146. @see setOverallSum
  30147. */
  30148. void setKernelValue (const int x,
  30149. const int y,
  30150. const float value) throw();
  30151. /** Rescales all values in the kernel to make the total add up to a fixed value.
  30152. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  30153. */
  30154. void setOverallSum (const float desiredTotalSum) throw();
  30155. /** Multiplies all values in the kernel by a value. */
  30156. void rescaleAllValues (const float multiplier) throw();
  30157. /** Intialises the kernel for a gaussian blur.
  30158. @param blurRadius this may be larger or smaller than the kernel's actual
  30159. size but this will obviously be wasteful or clip at the
  30160. edges. Ideally the kernel should be just larger than
  30161. (blurRadius * 2).
  30162. */
  30163. void createGaussianBlur (const float blurRadius) throw();
  30164. /** Returns the size of the kernel.
  30165. E.g. if it's a 3x3 kernel, this returns 3.
  30166. */
  30167. int getKernelSize() const throw() { return size; }
  30168. /** Returns a 2-dimensional array of the kernel's values.
  30169. The size of each dimension of the array will be getKernelSize().
  30170. */
  30171. float** getValues() const throw() { return values; }
  30172. /** Applies the kernel to an image.
  30173. @param destImage the image that will receive the resultant convoluted pixels.
  30174. @param sourceImage an optional source image to read from - if this is 0, then the
  30175. destination image will be used as the source. If an image is
  30176. specified, it must be exactly the same size and type as the destination
  30177. image.
  30178. @param x the region of the image to apply the filter to
  30179. @param y the region of the image to apply the filter to
  30180. @param width the region of the image to apply the filter to
  30181. @param height the region of the image to apply the filter to
  30182. */
  30183. void applyToImage (Image& destImage,
  30184. const Image* sourceImage,
  30185. int x,
  30186. int y,
  30187. int width,
  30188. int height) const;
  30189. juce_UseDebuggingNewOperator
  30190. private:
  30191. float** values;
  30192. int size;
  30193. // no reason not to implement these one day..
  30194. ImageConvolutionKernel (const ImageConvolutionKernel&);
  30195. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  30196. };
  30197. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30198. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  30199. #endif
  30200. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30201. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30202. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30203. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30204. /**
  30205. Base-class for codecs that can read and write image file formats such
  30206. as PNG, JPEG, etc.
  30207. This class also contains static methods to make it easy to load images
  30208. from files, streams or from memory.
  30209. @see Image, ImageCache
  30210. */
  30211. class JUCE_API ImageFileFormat
  30212. {
  30213. protected:
  30214. /** Creates an ImageFormat. */
  30215. ImageFileFormat() throw() {}
  30216. public:
  30217. /** Destructor. */
  30218. virtual ~ImageFileFormat() throw() {}
  30219. /** Returns a description of this file format.
  30220. E.g. "JPEG", "PNG"
  30221. */
  30222. virtual const String getFormatName() = 0;
  30223. /** Returns true if the given stream seems to contain data that this format
  30224. understands.
  30225. The format class should only read the first few bytes of the stream and sniff
  30226. for header bytes that it understands.
  30227. @see decodeImage
  30228. */
  30229. virtual bool canUnderstand (InputStream& input) = 0;
  30230. /** Tries to decode and return an image from the given stream.
  30231. This will be called for an image format after calling its canUnderStand() method
  30232. to see if it can handle the stream.
  30233. @param input the stream to read the data from. The stream will be positioned
  30234. at the start of the image data (but this may not necessarily
  30235. be position 0)
  30236. @returns the image that was decoded, or 0 if it fails. It's the
  30237. caller's responsibility to delete this image when no longer needed.
  30238. @see loadFrom
  30239. */
  30240. virtual Image* decodeImage (InputStream& input) = 0;
  30241. /** Attempts to write an image to a stream.
  30242. To specify extra information like encoding quality, there will be appropriate parameters
  30243. in the subclasses of the specific file types.
  30244. @returns true if it nothing went wrong.
  30245. */
  30246. virtual bool writeImageToStream (const Image& sourceImage,
  30247. OutputStream& destStream) = 0;
  30248. /** Tries the built-in decoders to see if it can find one to read this stream.
  30249. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30250. The object that is returned should not be deleted by the caller.
  30251. @see canUnderstand, decodeImage, loadFrom
  30252. */
  30253. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30254. /** Tries to load an image from a stream.
  30255. This will use the findImageFormatForStream() method to locate a suitable
  30256. codec, and use that to load the image.
  30257. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30258. caller's responsibility to delete this image when no longer needed.
  30259. */
  30260. static Image* loadFrom (InputStream& input);
  30261. /** Tries to load an image from a file.
  30262. This will use the findImageFormatForStream() method to locate a suitable
  30263. codec, and use that to load the image.
  30264. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30265. caller's responsibility to delete this image when no longer needed.
  30266. */
  30267. static Image* loadFrom (const File& file);
  30268. /** Tries to load an image from a block of raw image data.
  30269. This will use the findImageFormatForStream() method to locate a suitable
  30270. codec, and use that to load the image.
  30271. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30272. caller's responsibility to delete this image when no longer needed.
  30273. */
  30274. static Image* loadFrom (const void* rawData,
  30275. const int numBytesOfData);
  30276. };
  30277. /**
  30278. A type of ImageFileFormat for reading and writing PNG files.
  30279. @see ImageFileFormat, JPEGImageFormat
  30280. */
  30281. class PNGImageFormat : public ImageFileFormat
  30282. {
  30283. public:
  30284. PNGImageFormat() throw();
  30285. ~PNGImageFormat() throw();
  30286. const String getFormatName();
  30287. bool canUnderstand (InputStream& input);
  30288. Image* decodeImage (InputStream& input);
  30289. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30290. };
  30291. /**
  30292. A type of ImageFileFormat for reading and writing JPEG files.
  30293. @see ImageFileFormat, PNGImageFormat
  30294. */
  30295. class JPEGImageFormat : public ImageFileFormat
  30296. {
  30297. public:
  30298. JPEGImageFormat() throw();
  30299. ~JPEGImageFormat() throw();
  30300. /** Specifies the quality to be used when writing a JPEG file.
  30301. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30302. any negative value is "default" quality
  30303. */
  30304. void setQuality (const float newQuality);
  30305. const String getFormatName();
  30306. bool canUnderstand (InputStream& input);
  30307. Image* decodeImage (InputStream& input);
  30308. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30309. private:
  30310. float quality;
  30311. };
  30312. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30313. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30314. #endif
  30315. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30316. /********* Start of inlined file: juce_Drawable.h *********/
  30317. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30318. #define __JUCE_DRAWABLE_JUCEHEADER__
  30319. /**
  30320. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30321. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30322. */
  30323. class JUCE_API Drawable
  30324. {
  30325. protected:
  30326. /** The base class can't be instantiated directly.
  30327. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30328. */
  30329. Drawable();
  30330. public:
  30331. /** Destructor. */
  30332. virtual ~Drawable();
  30333. /** Creates a deep copy of this Drawable object.
  30334. Use this to create a new copy of this and any sub-objects in the tree.
  30335. */
  30336. virtual Drawable* createCopy() const = 0;
  30337. /** Renders this Drawable object.
  30338. This is the main rendering method you should call to render a Drawable.
  30339. @see drawWithin
  30340. */
  30341. virtual void draw (Graphics& g,
  30342. const AffineTransform& transform = AffineTransform::identity) const = 0;
  30343. /** Renders the Drawable at a given offset within the Graphics context.
  30344. The co-ordinates passed-in are used to translate the object relative to its own
  30345. origin before drawing it - this is basically a quick way of saying:
  30346. @code
  30347. draw (g, AffineTransform::translation (x, y)).
  30348. @endcode
  30349. */
  30350. void drawAt (Graphics& g,
  30351. const float x,
  30352. const float y) const;
  30353. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30354. changing its aspect-ratio.
  30355. The object can placed arbitrarily within the rectangle based on a Justification type,
  30356. and can either be made as big as possible, or just reduced to fit.
  30357. @param g the graphics context to render onto
  30358. @param destX top-left of the target rectangle to fit it into
  30359. @param destY top-left of the target rectangle to fit it into
  30360. @param destWidth size of the target rectangle to fit the image into
  30361. @param destHeight size of the target rectangle to fit the image into
  30362. @param placement defines the alignment and rescaling to use to fit
  30363. this object within the target rectangle.
  30364. */
  30365. void drawWithin (Graphics& g,
  30366. const int destX,
  30367. const int destY,
  30368. const int destWidth,
  30369. const int destHeight,
  30370. const RectanglePlacement& placement) const;
  30371. /** Returns the smallest rectangle that can contain this Drawable object.
  30372. Co-ordinates are relative to the object's own origin.
  30373. */
  30374. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30375. /** Returns true if the given point is somewhere inside this Drawable.
  30376. Co-ordinates are relative to the object's own origin.
  30377. */
  30378. virtual bool hitTest (float x, float y) const = 0;
  30379. /** Returns the name given to this drawable.
  30380. @see setName
  30381. */
  30382. const String& getName() const throw() { return name; }
  30383. /** Assigns a name to this drawable. */
  30384. void setName (const String& newName) throw() { name = newName; }
  30385. /** Tries to turn some kind of image file into a drawable.
  30386. The data could be an image that the ImageFileFormat class understands, or it
  30387. could be SVG.
  30388. */
  30389. static Drawable* createFromImageData (const void* data, const int numBytes);
  30390. /** Tries to turn a stream containing some kind of image data into a drawable.
  30391. The data could be an image that the ImageFileFormat class understands, or it
  30392. could be SVG.
  30393. */
  30394. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30395. /** Tries to turn a file containing some kind of image data into a drawable.
  30396. The data could be an image that the ImageFileFormat class understands, or it
  30397. could be SVG.
  30398. */
  30399. static Drawable* createFromImageFile (const File& file);
  30400. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30401. into a Drawable tree.
  30402. The object returned must be deleted by the caller. If something goes wrong
  30403. while parsing, it may return 0.
  30404. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30405. implementation, but it can return the basic vector objects.
  30406. */
  30407. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30408. juce_UseDebuggingNewOperator
  30409. private:
  30410. Drawable (const Drawable&);
  30411. const Drawable& operator= (const Drawable&);
  30412. String name;
  30413. };
  30414. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30415. /********* End of inlined file: juce_Drawable.h *********/
  30416. #endif
  30417. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30418. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30419. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30420. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30421. /**
  30422. A drawable object which acts as a container for a set of other Drawables.
  30423. @see Drawable
  30424. */
  30425. class JUCE_API DrawableComposite : public Drawable
  30426. {
  30427. public:
  30428. /** Creates a composite Drawable.
  30429. */
  30430. DrawableComposite();
  30431. /** Destructor. */
  30432. virtual ~DrawableComposite();
  30433. /** Adds a new sub-drawable to this one.
  30434. This passes in a Drawable pointer for this object to look after. To add a copy
  30435. of a drawable, use the form of this method that takes a Drawable reference instead.
  30436. @param drawable the object to add - this will be deleted automatically
  30437. when no longer needed, so the caller mustn't keep any
  30438. pointers to it.
  30439. @param transform the transform to apply to this drawable when it's being
  30440. drawn
  30441. @param index where to insert it in the list of drawables. 0 is the back,
  30442. -1 is the front, or any value from 0 and getNumDrawables()
  30443. can be used
  30444. @see removeDrawable
  30445. */
  30446. void insertDrawable (Drawable* drawable,
  30447. const AffineTransform& transform = AffineTransform::identity,
  30448. const int index = -1);
  30449. /** Adds a new sub-drawable to this one.
  30450. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30451. for this object to look after, use the form of this method that takes a Drawable
  30452. pointer instead.
  30453. @param drawable the object to add - an internal copy will be made of this object
  30454. @param transform the transform to apply to this drawable when it's being
  30455. drawn
  30456. @param index where to insert it in the list of drawables. 0 is the back,
  30457. -1 is the front, or any value from 0 and getNumDrawables()
  30458. can be used
  30459. @see removeDrawable
  30460. */
  30461. void insertDrawable (const Drawable& drawable,
  30462. const AffineTransform& transform = AffineTransform::identity,
  30463. const int index = -1);
  30464. /** Deletes one of the Drawable objects.
  30465. @param index the index of the drawable to delete, between 0
  30466. and (getNumDrawables() - 1).
  30467. @see insertDrawable, getNumDrawables
  30468. */
  30469. void removeDrawable (const int index);
  30470. /** Returns the number of drawables contained inside this one.
  30471. @see getDrawable
  30472. */
  30473. int getNumDrawables() const throw() { return drawables.size(); }
  30474. /** Returns one of the drawables that are contained in this one.
  30475. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30476. to find it.
  30477. The pointer returned is managed by this object and will be deleted when no longer
  30478. needed, so be careful what you do with it.
  30479. @see getNumDrawables
  30480. */
  30481. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30482. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30483. The pointer returned is managed by this object and will be deleted when no longer
  30484. needed, so be careful what you do with it.
  30485. @see getNumDrawables
  30486. */
  30487. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30488. /** Brings one of the Drawables to the front.
  30489. @param index the index of the drawable to move, between 0
  30490. and (getNumDrawables() - 1).
  30491. @see insertDrawable, getNumDrawables
  30492. */
  30493. void bringToFront (const int index);
  30494. /** @internal */
  30495. void draw (Graphics& g, const AffineTransform& transform) const;
  30496. /** @internal */
  30497. void getBounds (float& x, float& y, float& width, float& height) const;
  30498. /** @internal */
  30499. bool hitTest (float x, float y) const;
  30500. /** @internal */
  30501. Drawable* createCopy() const;
  30502. juce_UseDebuggingNewOperator
  30503. private:
  30504. OwnedArray <Drawable> drawables;
  30505. OwnedArray <AffineTransform> transforms;
  30506. DrawableComposite (const DrawableComposite&);
  30507. const DrawableComposite& operator= (const DrawableComposite&);
  30508. };
  30509. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30510. /********* End of inlined file: juce_DrawableComposite.h *********/
  30511. #endif
  30512. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30513. /********* Start of inlined file: juce_DrawableImage.h *********/
  30514. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30515. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30516. /**
  30517. A drawable object which is a bitmap image.
  30518. @see Drawable
  30519. */
  30520. class JUCE_API DrawableImage : public Drawable
  30521. {
  30522. public:
  30523. DrawableImage();
  30524. /** Destructor. */
  30525. virtual ~DrawableImage();
  30526. /** Sets the image that this drawable will render.
  30527. An internal copy is made of the image passed-in. If you want to provide an
  30528. image that this object can take charge of without needing to create a copy,
  30529. use the other setImage() method.
  30530. */
  30531. void setImage (const Image& imageToCopy);
  30532. /** Sets the image that this drawable will render.
  30533. An internal copy of this will not be made, so the caller mustn't delete
  30534. the image while it's still being used by this object.
  30535. A good way to use this is with the ImageCache - if you create an image
  30536. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30537. it'll be released neatly with its reference count being decreased.
  30538. @param imageToUse the image to render
  30539. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30540. then the image will be deleted when this object no longer
  30541. needs it - unless the image was created by the ImageCache,
  30542. in which case it will be released with ImageCache::release().
  30543. */
  30544. void setImage (Image* imageToUse,
  30545. const bool releaseWhenNotNeeded);
  30546. /** Returns the current image. */
  30547. Image* getImage() const throw() { return image; }
  30548. /** Clears (and possibly deletes) the currently set image. */
  30549. void clearImage();
  30550. /** Sets the opacity to use when drawing the image. */
  30551. void setOpacity (const float newOpacity);
  30552. /** Returns the image's opacity. */
  30553. float getOpacity() const throw() { return opacity; }
  30554. /** Sets a colour to draw over the image's alpha channel.
  30555. By default this is transparent so isn't drawn, but if you set a non-transparent
  30556. colour here, then it will be overlaid on the image, using the image's alpha
  30557. channel as a mask.
  30558. This is handy for doing things like darkening or lightening an image by overlaying
  30559. it with semi-transparent black or white.
  30560. */
  30561. void setOverlayColour (const Colour& newOverlayColour);
  30562. /** Returns the overlay colour. */
  30563. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30564. /** @internal */
  30565. void draw (Graphics& g, const AffineTransform& transform) const;
  30566. /** @internal */
  30567. void getBounds (float& x, float& y, float& width, float& height) const;
  30568. /** @internal */
  30569. bool hitTest (float x, float y) const;
  30570. /** @internal */
  30571. Drawable* createCopy() const;
  30572. juce_UseDebuggingNewOperator
  30573. private:
  30574. Image* image;
  30575. bool canDeleteImage;
  30576. float opacity;
  30577. Colour overlayColour;
  30578. DrawableImage (const DrawableImage&);
  30579. const DrawableImage& operator= (const DrawableImage&);
  30580. };
  30581. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30582. /********* End of inlined file: juce_DrawableImage.h *********/
  30583. #endif
  30584. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30585. /********* Start of inlined file: juce_DrawablePath.h *********/
  30586. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30587. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30588. /**
  30589. A drawable object which renders a filled or outlined shape.
  30590. @see Drawable
  30591. */
  30592. class JUCE_API DrawablePath : public Drawable
  30593. {
  30594. public:
  30595. /** Creates a DrawablePath.
  30596. */
  30597. DrawablePath();
  30598. /** Destructor. */
  30599. virtual ~DrawablePath();
  30600. /** Changes the path that will be drawn.
  30601. @see setSolidFill, setOutline
  30602. */
  30603. void setPath (const Path& newPath);
  30604. /** Returns the current path. */
  30605. const Path& getPath() const throw() { return path; }
  30606. /** Sets a colour to fill the path with.
  30607. This colour is used to fill the path - if you don't want the path to be
  30608. filled (e.g. if you're just drawing an outline), set this colour to be
  30609. transparent.
  30610. @see setPath, setOutline
  30611. */
  30612. void setSolidFill (const Colour& newColour);
  30613. /** Sets a custom brush to use to fill the path.
  30614. @see setSolidFill
  30615. */
  30616. void setFillBrush (const Brush& newBrush);
  30617. /** Returns the brush currently being used to fill the shape. */
  30618. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30619. /** Changes the properties of the outline that will be drawn around the path.
  30620. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30621. colour passed-in here will be used for it.
  30622. @see setPath, setSolidFill
  30623. */
  30624. void setOutline (const float thickness,
  30625. const Colour& outlineColour);
  30626. /** Changes the properties of the outline that will be drawn around the path.
  30627. If the stroke type has 0 thickness, no outline will be drawn.
  30628. @see setPath, setSolidFill
  30629. */
  30630. void setOutline (const PathStrokeType& strokeType,
  30631. const Brush& strokeBrush);
  30632. /** Returns the current outline style. */
  30633. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30634. /** Returns the brush currently being used to draw the outline. */
  30635. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30636. /** @internal */
  30637. void draw (Graphics& g, const AffineTransform& transform) const;
  30638. /** @internal */
  30639. void getBounds (float& x, float& y, float& width, float& height) const;
  30640. /** @internal */
  30641. bool hitTest (float x, float y) const;
  30642. /** @internal */
  30643. Drawable* createCopy() const;
  30644. juce_UseDebuggingNewOperator
  30645. private:
  30646. Path path, outline;
  30647. Brush* fillBrush;
  30648. Brush* strokeBrush;
  30649. PathStrokeType strokeType;
  30650. void updateOutline();
  30651. DrawablePath (const DrawablePath&);
  30652. const DrawablePath& operator= (const DrawablePath&);
  30653. };
  30654. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30655. /********* End of inlined file: juce_DrawablePath.h *********/
  30656. #endif
  30657. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30658. /********* Start of inlined file: juce_DrawableText.h *********/
  30659. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30660. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30661. /**
  30662. A drawable object which renders a line of text.
  30663. @see Drawable
  30664. */
  30665. class JUCE_API DrawableText : public Drawable
  30666. {
  30667. public:
  30668. /** Creates a DrawableText object. */
  30669. DrawableText();
  30670. /** Destructor. */
  30671. virtual ~DrawableText();
  30672. /** Sets the block of text to render */
  30673. void setText (const GlyphArrangement& newText);
  30674. /** Sets a single line of text to render.
  30675. This is a convenient method of adding a single line - for
  30676. more complex text, use the setText() that takes a
  30677. GlyphArrangement instead.
  30678. */
  30679. void setText (const String& newText, const Font& fontToUse);
  30680. /** Returns the text arrangement that was set with setText(). */
  30681. const GlyphArrangement& getText() const throw() { return text; }
  30682. /** Sets the colour of the text. */
  30683. void setColour (const Colour& newColour);
  30684. /** Returns the current text colour. */
  30685. const Colour& getColour() const throw() { return colour; }
  30686. /** @internal */
  30687. void draw (Graphics& g, const AffineTransform& transform) const;
  30688. /** @internal */
  30689. void getBounds (float& x, float& y, float& width, float& height) const;
  30690. /** @internal */
  30691. bool hitTest (float x, float y) const;
  30692. /** @internal */
  30693. Drawable* createCopy() const;
  30694. juce_UseDebuggingNewOperator
  30695. private:
  30696. GlyphArrangement text;
  30697. Colour colour;
  30698. DrawableText (const DrawableText&);
  30699. const DrawableText& operator= (const DrawableText&);
  30700. };
  30701. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30702. /********* End of inlined file: juce_DrawableText.h *********/
  30703. #endif
  30704. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30705. #endif
  30706. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30707. #endif
  30708. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30709. #endif
  30710. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30711. #endif
  30712. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30713. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30714. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30715. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30716. /**
  30717. A button showing an underlined weblink, that will launch the link
  30718. when it's clicked.
  30719. @see Button
  30720. */
  30721. class JUCE_API HyperlinkButton : public Button
  30722. {
  30723. public:
  30724. /** Creates a HyperlinkButton.
  30725. @param linkText the text that will be displayed in the button - this is
  30726. also set as the Component's name, but the text can be
  30727. changed later with the Button::getButtonText() method
  30728. @param linkURL the URL to launch when the user clicks the button
  30729. */
  30730. HyperlinkButton (const String& linkText,
  30731. const URL& linkURL);
  30732. /** Destructor. */
  30733. ~HyperlinkButton();
  30734. /** Changes the font to use for the text.
  30735. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30736. to match the size of the component.
  30737. */
  30738. void setFont (const Font& newFont,
  30739. const bool resizeToMatchComponentHeight,
  30740. const Justification& justificationType = Justification::horizontallyCentred);
  30741. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30742. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30743. methods.
  30744. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30745. */
  30746. enum ColourIds
  30747. {
  30748. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30749. };
  30750. /** Changes the URL that the button will trigger. */
  30751. void setURL (const URL& newURL) throw();
  30752. /** Returns the URL that the button will trigger. */
  30753. const URL& getURL() const throw() { return url; }
  30754. /** Resizes the button horizontally to fit snugly around the text.
  30755. This won't affect the button's height.
  30756. */
  30757. void changeWidthToFitText();
  30758. juce_UseDebuggingNewOperator
  30759. protected:
  30760. /** @internal */
  30761. void clicked();
  30762. /** @internal */
  30763. void colourChanged();
  30764. /** @internal */
  30765. void paintButton (Graphics& g,
  30766. bool isMouseOverButton,
  30767. bool isButtonDown);
  30768. private:
  30769. URL url;
  30770. Font font;
  30771. bool resizeFont;
  30772. Justification justification;
  30773. const Font getFontToUse() const;
  30774. HyperlinkButton (const HyperlinkButton&);
  30775. const HyperlinkButton& operator= (const HyperlinkButton&);
  30776. };
  30777. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30778. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30779. #endif
  30780. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30781. /********* Start of inlined file: juce_ImageButton.h *********/
  30782. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30783. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30784. /**
  30785. As the title suggests, this is a button containing an image.
  30786. The colour and transparency of the image can be set to vary when the
  30787. button state changes.
  30788. @see Button, ShapeButton, TextButton
  30789. */
  30790. class JUCE_API ImageButton : public Button
  30791. {
  30792. public:
  30793. /** Creates an ImageButton.
  30794. Use setImage() to specify the image to use. The colours and opacities that
  30795. are specified here can be changed later using setDrawingOptions().
  30796. @param name the name to give the component
  30797. */
  30798. ImageButton (const String& name);
  30799. /** Destructor. */
  30800. ~ImageButton();
  30801. /** Sets up the images to draw in various states.
  30802. Important! Bear in mind that if you pass the same image in for more than one of
  30803. these parameters, this button will delete it (or release from the ImageCache)
  30804. multiple times!
  30805. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30806. resized to the same dimensions as the normal image
  30807. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30808. button when the button's size changes
  30809. @param preserveImageProportions if true then any rescaling of the image to fit
  30810. the button will keep the image's x and y proportions
  30811. correct - i.e. it won't distort its shape, although
  30812. this might create gaps around the edges
  30813. @param normalImage the image to use when the button is in its normal state. The
  30814. image passed in will be deleted (or released if it
  30815. was created by the ImageCache class) when the
  30816. button no longer needs it.
  30817. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30818. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30819. normal image - if this colour is transparent, no overlay
  30820. will be drawn. The overlay will be drawn over the top of the
  30821. image, so you can basically add a solid or semi-transparent
  30822. colour to the image to brighten or darken it
  30823. @param overImage the image to use when the mouse is over the button. If
  30824. you want to use the same image as was set in the normalImage
  30825. parameter, this value can be 0. As for normalImage, it
  30826. will be deleted or released by the button when no longer
  30827. needed
  30828. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30829. is over the button
  30830. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30831. image when the mouse is over - if this colour is transparent,
  30832. no overlay will be drawn
  30833. @param downImage an image to use when the button is pressed down. If set
  30834. to zero, the 'over' image will be drawn instead (or the
  30835. normal image if there isn't an 'over' image either). This
  30836. image will be deleted or released by the button when no
  30837. longer needed
  30838. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30839. is pressed
  30840. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30841. image when the button is pressed down - if this colour is
  30842. transparent, no overlay will be drawn
  30843. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30844. whenever it's inside the button's bounding rectangle. If
  30845. set to values higher than 0, the mouse will only be
  30846. considered to be over the image when the value of the
  30847. image's alpha channel at that position is greater than
  30848. this level.
  30849. */
  30850. void setImages (const bool resizeButtonNowToFitThisImage,
  30851. const bool rescaleImagesWhenButtonSizeChanges,
  30852. const bool preserveImageProportions,
  30853. Image* const normalImage,
  30854. const float imageOpacityWhenNormal,
  30855. const Colour& overlayColourWhenNormal,
  30856. Image* const overImage,
  30857. const float imageOpacityWhenOver,
  30858. const Colour& overlayColourWhenOver,
  30859. Image* const downImage,
  30860. const float imageOpacityWhenDown,
  30861. const Colour& overlayColourWhenDown,
  30862. const float hitTestAlphaThreshold = 0.0f);
  30863. /** Returns the currently set 'normal' image. */
  30864. Image* getNormalImage() const throw();
  30865. /** Returns the image that's drawn when the mouse is over the button.
  30866. If an 'over' image has been set, this will return it; otherwise it'll
  30867. just return the normal image.
  30868. */
  30869. Image* getOverImage() const throw();
  30870. /** Returns the image that's drawn when the button is held down.
  30871. If a 'down' image has been set, this will return it; otherwise it'll
  30872. return the 'over' image or normal image, depending on what's available.
  30873. */
  30874. Image* getDownImage() const throw();
  30875. juce_UseDebuggingNewOperator
  30876. protected:
  30877. /** @internal */
  30878. bool hitTest (int x, int y);
  30879. /** @internal */
  30880. void paintButton (Graphics& g,
  30881. bool isMouseOverButton,
  30882. bool isButtonDown);
  30883. private:
  30884. bool scaleImageToFit, preserveProportions;
  30885. unsigned char alphaThreshold;
  30886. int imageX, imageY, imageW, imageH;
  30887. Image* normalImage;
  30888. Image* overImage;
  30889. Image* downImage;
  30890. float normalOpacity, overOpacity, downOpacity;
  30891. Colour normalOverlay, overOverlay, downOverlay;
  30892. Image* getCurrentImage() const;
  30893. void deleteImages();
  30894. ImageButton (const ImageButton&);
  30895. const ImageButton& operator= (const ImageButton&);
  30896. };
  30897. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30898. /********* End of inlined file: juce_ImageButton.h *********/
  30899. #endif
  30900. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30901. /********* Start of inlined file: juce_ShapeButton.h *********/
  30902. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30903. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30904. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30905. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30906. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30907. /**
  30908. An effect filter that adds a drop-shadow behind the image's content.
  30909. (This will only work on images/components that aren't opaque, of course).
  30910. When added to a component, this effect will draw a soft-edged
  30911. shadow based on what gets drawn inside it. The shadow will also
  30912. be applied to the component's children.
  30913. For speed, this doesn't use a proper gaussian blur, but cheats by
  30914. using a simple bilinear filter. If you need a really high-quality
  30915. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30916. @see Component::setComponentEffect
  30917. */
  30918. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30919. {
  30920. public:
  30921. /** Creates a default drop-shadow effect.
  30922. To customise the shadow's appearance, use the setShadowProperties()
  30923. method.
  30924. */
  30925. DropShadowEffect();
  30926. /** Destructor. */
  30927. ~DropShadowEffect();
  30928. /** Sets up parameters affecting the shadow's appearance.
  30929. @param newRadius the (approximate) radius of the blur used
  30930. @param newOpacity the opacity with which the shadow is rendered
  30931. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30932. component's contents
  30933. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30934. component's contents
  30935. */
  30936. void setShadowProperties (const float newRadius,
  30937. const float newOpacity,
  30938. const int newShadowOffsetX,
  30939. const int newShadowOffsetY);
  30940. /** @internal */
  30941. void applyEffect (Image& sourceImage, Graphics& destContext);
  30942. juce_UseDebuggingNewOperator
  30943. private:
  30944. int offsetX, offsetY;
  30945. float radius, opacity;
  30946. };
  30947. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30948. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30949. /**
  30950. A button that contains a filled shape.
  30951. @see Button, ImageButton, TextButton, ArrowButton
  30952. */
  30953. class JUCE_API ShapeButton : public Button
  30954. {
  30955. public:
  30956. /** Creates a ShapeButton.
  30957. @param name a name to give the component - see Component::setName()
  30958. @param normalColour the colour to fill the shape with when the mouse isn't over
  30959. @param overColour the colour to use when the mouse is over the shape
  30960. @param downColour the colour to use when the button is in the pressed-down state
  30961. */
  30962. ShapeButton (const String& name,
  30963. const Colour& normalColour,
  30964. const Colour& overColour,
  30965. const Colour& downColour);
  30966. /** Destructor. */
  30967. ~ShapeButton();
  30968. /** Sets the shape to use.
  30969. @param newShape the shape to use
  30970. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30971. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30972. the button is resized
  30973. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30974. */
  30975. void setShape (const Path& newShape,
  30976. const bool resizeNowToFitThisShape,
  30977. const bool maintainShapeProportions,
  30978. const bool hasDropShadow);
  30979. /** Set the colours to use for drawing the shape.
  30980. @param normalColour the colour to fill the shape with when the mouse isn't over
  30981. @param overColour the colour to use when the mouse is over the shape
  30982. @param downColour the colour to use when the button is in the pressed-down state
  30983. */
  30984. void setColours (const Colour& normalColour,
  30985. const Colour& overColour,
  30986. const Colour& downColour);
  30987. /** Sets up an outline to draw around the shape.
  30988. @param outlineColour the colour to use
  30989. @param outlineStrokeWidth the thickness of line to draw
  30990. */
  30991. void setOutline (const Colour& outlineColour,
  30992. const float outlineStrokeWidth);
  30993. juce_UseDebuggingNewOperator
  30994. protected:
  30995. /** @internal */
  30996. void paintButton (Graphics& g,
  30997. bool isMouseOverButton,
  30998. bool isButtonDown);
  30999. private:
  31000. Colour normalColour, overColour, downColour, outlineColour;
  31001. DropShadowEffect shadow;
  31002. Path shape;
  31003. bool maintainShapeProportions;
  31004. float outlineWidth;
  31005. ShapeButton (const ShapeButton&);
  31006. const ShapeButton& operator= (const ShapeButton&);
  31007. };
  31008. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31009. /********* End of inlined file: juce_ShapeButton.h *********/
  31010. #endif
  31011. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31012. #endif
  31013. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31014. /********* Start of inlined file: juce_ToggleButton.h *********/
  31015. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31016. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31017. /**
  31018. A button that can be toggled on/off.
  31019. All buttons can be toggle buttons, but this lets you create one of the
  31020. standard ones which has a tick-box and a text label next to it.
  31021. @see Button, DrawableButton, TextButton
  31022. */
  31023. class JUCE_API ToggleButton : public Button
  31024. {
  31025. public:
  31026. /** Creates a ToggleButton.
  31027. @param buttonText the text to put in the button (the component's name is also
  31028. initially set to this string, but these can be changed later
  31029. using the setName() and setButtonText() methods)
  31030. */
  31031. ToggleButton (const String& buttonText);
  31032. /** Destructor. */
  31033. ~ToggleButton();
  31034. /** Resizes the button to fit neatly around its current text.
  31035. The button's height won't be affected, only its width.
  31036. */
  31037. void changeWidthToFitText();
  31038. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31039. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31040. methods.
  31041. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31042. */
  31043. enum ColourIds
  31044. {
  31045. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31046. };
  31047. juce_UseDebuggingNewOperator
  31048. protected:
  31049. /** @internal */
  31050. void paintButton (Graphics& g,
  31051. bool isMouseOverButton,
  31052. bool isButtonDown);
  31053. /** @internal */
  31054. void colourChanged();
  31055. private:
  31056. ToggleButton (const ToggleButton&);
  31057. const ToggleButton& operator= (const ToggleButton&);
  31058. };
  31059. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31060. /********* End of inlined file: juce_ToggleButton.h *********/
  31061. #endif
  31062. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31063. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31064. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31065. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31066. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31067. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31068. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31069. /********* Start of inlined file: juce_Toolbar.h *********/
  31070. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31071. #define __JUCE_TOOLBAR_JUCEHEADER__
  31072. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31073. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31074. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31075. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31076. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31077. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31078. /**
  31079. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31080. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31081. derive your component from this class, and make sure that it is somewhere inside a
  31082. DragAndDropContainer component.
  31083. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31084. the operating system onto your component, you don't need any of these classes: instead
  31085. see the FileDragAndDropTarget class.
  31086. @see DragAndDropContainer, FileDragAndDropTarget
  31087. */
  31088. class JUCE_API DragAndDropTarget
  31089. {
  31090. public:
  31091. /** Destructor. */
  31092. virtual ~DragAndDropTarget() {}
  31093. /** Callback to check whether this target is interested in the type of object being
  31094. dragged.
  31095. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31096. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31097. @returns true if this component wants to receive the other callbacks regarging this
  31098. type of object; if it returns false, no other callbacks will be made.
  31099. */
  31100. virtual bool isInterestedInDragSource (const String& sourceDescription,
  31101. Component* sourceComponent) = 0;
  31102. /** Callback to indicate that something is being dragged over this component.
  31103. This gets called when the user moves the mouse into this component while dragging
  31104. something.
  31105. Use this callback as a trigger to make your component repaint itself to give the
  31106. user feedback about whether the item can be dropped here or not.
  31107. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31108. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31109. @param x the mouse x position, relative to this component
  31110. @param y the mouse y position, relative to this component
  31111. @see itemDragExit
  31112. */
  31113. virtual void itemDragEnter (const String& sourceDescription,
  31114. Component* sourceComponent,
  31115. int x,
  31116. int y);
  31117. /** Callback to indicate that the user is dragging something over this component.
  31118. This gets called when the user moves the mouse over this component while dragging
  31119. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  31120. this lets you know what happens in-between.
  31121. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31122. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31123. @param x the mouse x position, relative to this component
  31124. @param y the mouse y position, relative to this component
  31125. */
  31126. virtual void itemDragMove (const String& sourceDescription,
  31127. Component* sourceComponent,
  31128. int x,
  31129. int y);
  31130. /** Callback to indicate that something has been dragged off the edge of this component.
  31131. This gets called when the user moves the mouse out of this component while dragging
  31132. something.
  31133. If you've used itemDragEnter() to repaint your component and give feedback, use this
  31134. as a signal to repaint it in its normal state.
  31135. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31136. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31137. @see itemDragEnter
  31138. */
  31139. virtual void itemDragExit (const String& sourceDescription,
  31140. Component* sourceComponent);
  31141. /** Callback to indicate that the user has dropped something onto this component.
  31142. When the user drops an item this get called, and you can use the description to
  31143. work out whether your object wants to deal with it or not.
  31144. Note that after this is called, the itemDragExit method may not be called, so you should
  31145. clean up in here if there's anything you need to do when the drag finishes.
  31146. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31147. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31148. @param x the mouse x position, relative to this component
  31149. @param y the mouse y position, relative to this component
  31150. */
  31151. virtual void itemDropped (const String& sourceDescription,
  31152. Component* sourceComponent,
  31153. int x,
  31154. int y) = 0;
  31155. /** Overriding this allows the target to tell the drag container whether to
  31156. draw the drag image while the cursor is over it.
  31157. By default it returns true, but if you return false, then the normal drag
  31158. image will not be shown when the cursor is over this target.
  31159. */
  31160. virtual bool shouldDrawDragImageWhenOver();
  31161. };
  31162. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31163. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  31164. /**
  31165. Enables drag-and-drop behaviour for a component and all its sub-components.
  31166. For a component to be able to make or receive drag-and-drop events, one of its parent
  31167. components must derive from this class. It's probably best for the top-level
  31168. component to implement it.
  31169. Then to start a drag operation, any sub-component can just call the startDragging()
  31170. method, and this object will take over, tracking the mouse and sending appropriate
  31171. callbacks to any child components derived from DragAndDropTarget which the mouse
  31172. moves over.
  31173. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31174. the operating system onto your component, you don't need any of these classes: you can do this
  31175. simply by overriding Component::filesDropped().
  31176. @see DragAndDropTarget
  31177. */
  31178. class JUCE_API DragAndDropContainer
  31179. {
  31180. public:
  31181. /** Creates a DragAndDropContainer.
  31182. The object that derives from this class must also be a Component.
  31183. */
  31184. DragAndDropContainer();
  31185. /** Destructor. */
  31186. virtual ~DragAndDropContainer();
  31187. /** Begins a drag-and-drop operation.
  31188. This starts a drag-and-drop operation - call it when the user drags the
  31189. mouse in your drag-source component, and this object will track mouse
  31190. movements until the user lets go of the mouse button, and will send
  31191. appropriate messages to DragAndDropTarget objects that the mouse moves
  31192. over.
  31193. findParentDragContainerFor() is a handy method to call to find the
  31194. drag container to use for a component.
  31195. @param sourceDescription a string to use as the description of the thing being
  31196. dragged - this will be passed to the objects that might be
  31197. dropped-onto so they can decide if they want to handle it or
  31198. not
  31199. @param sourceComponent the component that is being dragged
  31200. @param dragImage the image to drag around underneath the mouse. If this is
  31201. zero, a snapshot of the sourceComponent will be used instead. An
  31202. image passed-in will be deleted by this object when no longer
  31203. needed.
  31204. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  31205. window, and can be dragged to DragAndDropTargets that are the
  31206. children of components other than this one.
  31207. */
  31208. void startDragging (const String& sourceDescription,
  31209. Component* sourceComponent,
  31210. Image* dragImage = 0,
  31211. const bool allowDraggingToOtherJuceWindows = false);
  31212. /** Returns true if something is currently being dragged. */
  31213. bool isDragAndDropActive() const;
  31214. /** Returns the description of the thing that's currently being dragged.
  31215. If nothing's being dragged, this will return an empty string, otherwise it's the
  31216. string that was passed into startDragging().
  31217. @see startDragging
  31218. */
  31219. const String getCurrentDragDescription() const;
  31220. /** Utility to find the DragAndDropContainer for a given Component.
  31221. This will search up this component's parent hierarchy looking for the first
  31222. parent component which is a DragAndDropContainer.
  31223. It's useful when a component wants to call startDragging but doesn't know
  31224. the DragAndDropContainer it should to use.
  31225. Obviously this may return 0 if it doesn't find a suitable component.
  31226. */
  31227. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  31228. /** This performs a synchronous drag-and-drop of a set of files to some external
  31229. application.
  31230. You can call this function in response to a mouseDrag callback, and it will
  31231. block, running its own internal message loop and tracking the mouse, while it
  31232. uses a native operating system drag-and-drop operation to move or copy some
  31233. files to another application.
  31234. @param files a list of filenames to drag
  31235. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  31236. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  31237. @returns true if the files were successfully dropped somewhere, or false if it
  31238. was interrupted
  31239. @see performExternalDragDropOfText
  31240. */
  31241. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  31242. /** This performs a synchronous drag-and-drop of a block of text to some external
  31243. application.
  31244. You can call this function in response to a mouseDrag callback, and it will
  31245. block, running its own internal message loop and tracking the mouse, while it
  31246. uses a native operating system drag-and-drop operation to move or copy some
  31247. text to another application.
  31248. @param text the text to copy
  31249. @returns true if the text was successfully dropped somewhere, or false if it
  31250. was interrupted
  31251. @see performExternalDragDropOfFiles
  31252. */
  31253. static bool performExternalDragDropOfText (const String& text);
  31254. juce_UseDebuggingNewOperator
  31255. protected:
  31256. /** Override this if you want to be able to perform an external drag a set of files
  31257. when the user drags outside of this container component.
  31258. This method will be called when a drag operation moves outside the Juce-based window,
  31259. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31260. to the array passed in, and return true.
  31261. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31262. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31263. @param files on return, the filenames you want to drag
  31264. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31265. it must make a copy of them (see the performExternalDragDropOfFiles()
  31266. method)
  31267. @see performExternalDragDropOfFiles
  31268. */
  31269. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31270. Component* dragSourceComponent,
  31271. StringArray& files,
  31272. bool& canMoveFiles);
  31273. private:
  31274. friend class DragImageComponent;
  31275. Component* dragImageComponent;
  31276. String currentDragDesc;
  31277. };
  31278. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31279. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31280. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31281. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31282. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31283. /**
  31284. Animates a set of components, moving it to a new position.
  31285. To use this, create a ComponentAnimator, and use its animateComponent() method
  31286. to tell it to move components to destination positions. Any number of
  31287. components can be animated by one ComponentAnimator object (if you've got a
  31288. lot of components to move, it's much more efficient to share a single animator
  31289. than to have many animators running at once).
  31290. You'll need to make sure the animator object isn't deleted before it finishes
  31291. moving the components.
  31292. */
  31293. class JUCE_API ComponentAnimator : private Timer
  31294. {
  31295. public:
  31296. /** Creates a ComponentAnimator. */
  31297. ComponentAnimator();
  31298. /** Destructor. */
  31299. ~ComponentAnimator();
  31300. /** Starts a component moving from its current position to a specified position.
  31301. If the component is already in the middle of an animation, that will be abandoned,
  31302. and a new animation will begin, moving the component from its current location.
  31303. The start and end speed parameters let you apply some acceleration to the component's
  31304. movement.
  31305. @param component the component to move
  31306. @param finalPosition the destination position and size to move it to
  31307. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31308. to arrive at its destination
  31309. @param startSpeed a value to indicate the relative start speed of the
  31310. animation. If this is 0, the component will start
  31311. by accelerating from rest; higher values mean that it
  31312. will have an initial speed greater than zero. If the
  31313. value if greater than 1, it will decelerate towards the
  31314. middle of its journey. To move the component at a constant
  31315. rate for its entire animation, set both the start and
  31316. end speeds to 1.0
  31317. @param endSpeed a relative speed at which the component should be moving
  31318. when the animation finishes. If this is 0, the component
  31319. will decelerate to a standstill at its final position; higher
  31320. values mean the component will still be moving when it stops.
  31321. To move the component at a constant rate for its entire
  31322. animation, set both the start and end speeds to 1.0
  31323. */
  31324. void animateComponent (Component* const component,
  31325. const Rectangle& finalPosition,
  31326. const int millisecondsToSpendMoving,
  31327. const double startSpeed = 1.0,
  31328. const double endSpeed = 1.0);
  31329. /** Stops a component if it's currently being animated.
  31330. If moveComponentToItsFinalPosition is true, then the component will
  31331. be immediately moved to its destination position and size. If false, it will be
  31332. left in whatever location it currently occupies.
  31333. */
  31334. void cancelAnimation (Component* const component,
  31335. const bool moveComponentToItsFinalPosition);
  31336. /** Clears all of the active animations.
  31337. If moveComponentsToTheirFinalPositions is true, all the components will
  31338. be immediately set to their final positions. If false, they will be
  31339. left in whatever locations they currently occupy.
  31340. */
  31341. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31342. /** Returns the destination position for a component.
  31343. If the component is being animated, this will return the target position that
  31344. was specified when animateComponent() was called.
  31345. If the specified component isn't currently being animated, this method will just
  31346. return its current position.
  31347. */
  31348. const Rectangle getComponentDestination (Component* const component);
  31349. juce_UseDebuggingNewOperator
  31350. private:
  31351. VoidArray tasks;
  31352. uint32 lastTime;
  31353. void* findTaskFor (Component* const component) const;
  31354. void timerCallback();
  31355. };
  31356. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31357. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31358. class ToolbarItemComponent;
  31359. class ToolbarItemFactory;
  31360. class MissingItemsComponent;
  31361. /**
  31362. A toolbar component.
  31363. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31364. and looks after their order and layout.
  31365. Items (icon buttons or other custom components) are added to a toolbar using a
  31366. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31367. toolbar might contain more than one instance of a particular item type.
  31368. Toolbars can be interactively customised, allowing the user to drag the items
  31369. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31370. component as a source of new items.
  31371. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31372. */
  31373. class JUCE_API Toolbar : public Component,
  31374. public DragAndDropContainer,
  31375. public DragAndDropTarget,
  31376. private ButtonListener
  31377. {
  31378. public:
  31379. /** Creates an empty toolbar component.
  31380. To add some icons or other components to your toolbar, you'll need to
  31381. create a ToolbarItemFactory class that can create a suitable set of
  31382. ToolbarItemComponents.
  31383. @see ToolbarItemFactory, ToolbarItemComponents
  31384. */
  31385. Toolbar();
  31386. /** Destructor.
  31387. Any items on the bar will be deleted when the toolbar is deleted.
  31388. */
  31389. ~Toolbar();
  31390. /** Changes the bar's orientation.
  31391. @see isVertical
  31392. */
  31393. void setVertical (const bool shouldBeVertical);
  31394. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31395. You can change the bar's orientation with setVertical().
  31396. */
  31397. bool isVertical() const throw() { return vertical; }
  31398. /** Returns the depth of the bar.
  31399. If the bar is horizontal, this will return its height; if it's vertical, it
  31400. will return its width.
  31401. @see getLength
  31402. */
  31403. int getThickness() const throw();
  31404. /** Returns the length of the bar.
  31405. If the bar is horizontal, this will return its width; if it's vertical, it
  31406. will return its height.
  31407. @see getThickness
  31408. */
  31409. int getLength() const throw();
  31410. /** Deletes all items from the bar.
  31411. */
  31412. void clear();
  31413. /** Adds an item to the toolbar.
  31414. The factory's ToolbarItemFactory::createItem() will be called by this method
  31415. to create the component that will actually be added to the bar.
  31416. The new item will be inserted at the specified index (if the index is -1, it
  31417. will be added to the right-hand or bottom end of the bar).
  31418. Once added, the component will be automatically deleted by this object when it
  31419. is no longer needed.
  31420. @see ToolbarItemFactory
  31421. */
  31422. void addItem (ToolbarItemFactory& factory,
  31423. const int itemId,
  31424. const int insertIndex = -1);
  31425. /** Deletes one of the items from the bar.
  31426. */
  31427. void removeToolbarItem (const int itemIndex);
  31428. /** Returns the number of items currently on the toolbar.
  31429. @see getItemId, getItemComponent
  31430. */
  31431. int getNumItems() const throw();
  31432. /** Returns the ID of the item with the given index.
  31433. If the index is less than zero or greater than the number of items,
  31434. this will return 0.
  31435. @see getNumItems
  31436. */
  31437. int getItemId (const int itemIndex) const throw();
  31438. /** Returns the component being used for the item with the given index.
  31439. If the index is less than zero or greater than the number of items,
  31440. this will return 0.
  31441. @see getNumItems
  31442. */
  31443. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31444. /** Clears this toolbar and adds to it the default set of items that the specified
  31445. factory creates.
  31446. @see ToolbarItemFactory::getDefaultItemSet
  31447. */
  31448. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31449. /** Options for the way items should be displayed.
  31450. @see setStyle, getStyle
  31451. */
  31452. enum ToolbarItemStyle
  31453. {
  31454. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31455. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31456. textOnly /**< Means that the toolbar only display text labels for each item. */
  31457. };
  31458. /** Returns the toolbar's current style.
  31459. @see ToolbarItemStyle, setStyle
  31460. */
  31461. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31462. /** Changes the toolbar's current style.
  31463. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31464. */
  31465. void setStyle (const ToolbarItemStyle& newStyle);
  31466. /** Flags used by the showCustomisationDialog() method. */
  31467. enum CustomisationFlags
  31468. {
  31469. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31470. show the "icons only" option on its choice of toolbar styles. */
  31471. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31472. show the "icons with text" option on its choice of toolbar styles. */
  31473. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31474. show the "text only" option on its choice of toolbar styles. */
  31475. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31476. show a button to reset the toolbar to its default set of items. */
  31477. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31478. };
  31479. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31480. The dialog contains a ToolbarItemPalette and various controls for editing other
  31481. aspects of the toolbar. This method will block and run the dialog box modally,
  31482. returning when the user closes it.
  31483. The factory is used to determine the set of items that will be shown on the
  31484. palette.
  31485. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31486. enum.
  31487. @see ToolbarItemPalette
  31488. */
  31489. void showCustomisationDialog (ToolbarItemFactory& factory,
  31490. const int optionFlags = allCustomisationOptionsEnabled);
  31491. /** Turns on or off the toolbar's editing mode, in which its items can be
  31492. rearranged by the user.
  31493. (In most cases it's easier just to use showCustomisationDialog() instead of
  31494. trying to enable editing directly).
  31495. @see ToolbarItemPalette
  31496. */
  31497. void setEditingActive (const bool editingEnabled);
  31498. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31499. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31500. methods.
  31501. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31502. */
  31503. enum ColourIds
  31504. {
  31505. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31506. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31507. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31508. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31509. over them. */
  31510. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31511. held down on them. */
  31512. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31513. when the style is set to iconsWithText or textOnly. */
  31514. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31515. the customisation dialog is active and the mouse moves over them. */
  31516. };
  31517. /** Returns a string that represents the toolbar's current set of items.
  31518. This lets you later restore the same item layout using restoreFromString().
  31519. @see restoreFromString
  31520. */
  31521. const String toString() const;
  31522. /** Restores a set of items that was previously stored in a string by the toString()
  31523. method.
  31524. The factory object is used to create any item components that are needed.
  31525. @see toString
  31526. */
  31527. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31528. const String& savedVersion);
  31529. /** @internal */
  31530. void paint (Graphics& g);
  31531. /** @internal */
  31532. void resized();
  31533. /** @internal */
  31534. void buttonClicked (Button*);
  31535. /** @internal */
  31536. void mouseDown (const MouseEvent&);
  31537. /** @internal */
  31538. bool isInterestedInDragSource (const String&, Component*);
  31539. /** @internal */
  31540. void itemDragMove (const String&, Component*, int, int);
  31541. /** @internal */
  31542. void itemDragExit (const String&, Component*);
  31543. /** @internal */
  31544. void itemDropped (const String&, Component*, int, int);
  31545. /** @internal */
  31546. void updateAllItemPositions (const bool animate);
  31547. /** @internal */
  31548. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31549. juce_UseDebuggingNewOperator
  31550. private:
  31551. Button* missingItemsButton;
  31552. bool vertical, isEditingActive;
  31553. ToolbarItemStyle toolbarStyle;
  31554. ComponentAnimator animator;
  31555. friend class MissingItemsComponent;
  31556. Array <ToolbarItemComponent*> items;
  31557. friend class ItemDragAndDropOverlayComponent;
  31558. static const tchar* const toolbarDragDescriptor;
  31559. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31560. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31561. Toolbar (const Toolbar&);
  31562. const Toolbar& operator= (const Toolbar&);
  31563. };
  31564. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31565. /********* End of inlined file: juce_Toolbar.h *********/
  31566. class ItemDragAndDropOverlayComponent;
  31567. /**
  31568. A component that can be used as one of the items in a Toolbar.
  31569. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31570. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31571. class for further info about creating them.
  31572. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31573. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31574. calling the constructor, and override contentAreaChanged(), in which you can position
  31575. any sub-components you need to add.
  31576. To add basic buttons without writing a special subclass, have a look at the
  31577. ToolbarButton class.
  31578. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31579. */
  31580. class JUCE_API ToolbarItemComponent : public Button
  31581. {
  31582. public:
  31583. /** Constructor.
  31584. @param itemId the ID of the type of toolbar item which this represents
  31585. @param labelText the text to display if the toolbar's style is set to
  31586. Toolbar::iconsWithText or Toolbar::textOnly
  31587. @param isBeingUsedAsAButton set this to false if you don't want the button
  31588. to draw itself with button over/down states when the mouse
  31589. moves over it or clicks
  31590. */
  31591. ToolbarItemComponent (const int itemId,
  31592. const String& labelText,
  31593. const bool isBeingUsedAsAButton);
  31594. /** Destructor. */
  31595. ~ToolbarItemComponent();
  31596. /** Returns the item type ID that this component represents.
  31597. This value is in the constructor.
  31598. */
  31599. int getItemId() const throw() { return itemId; }
  31600. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31601. inside one.
  31602. */
  31603. Toolbar* getToolbar() const;
  31604. /** Returns true if this component is currently inside a toolbar which is vertical.
  31605. @see Toolbar::isVertical
  31606. */
  31607. bool isToolbarVertical() const;
  31608. /** Returns the current style setting of this item.
  31609. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31610. @see setStyle, Toolbar::getStyle
  31611. */
  31612. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31613. /** Changes the current style setting of this item.
  31614. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31615. by the toolbar that holds this item.
  31616. @see setStyle, Toolbar::setStyle
  31617. */
  31618. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31619. /** Returns the area of the component that should be used to display the button image or
  31620. other contents of the item.
  31621. This content area may change when the item's style changes, and may leave a space around the
  31622. edge of the component where the text label can be shown.
  31623. @see contentAreaChanged
  31624. */
  31625. const Rectangle getContentArea() const throw() { return contentArea; }
  31626. /** This method must return the size criteria for this item, based on a given toolbar
  31627. size and orientation.
  31628. The preferredSize, minSize and maxSize values must all be set by your implementation
  31629. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31630. toolbar, they refer to the item's height.
  31631. The preferredSize is the size that the component would like to be, and this must be
  31632. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31633. the same value.
  31634. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31635. Toolbar::getThickness().
  31636. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31637. vertically.
  31638. */
  31639. virtual bool getToolbarItemSizes (int toolbarThickness,
  31640. bool isToolbarVertical,
  31641. int& preferredSize,
  31642. int& minSize,
  31643. int& maxSize) = 0;
  31644. /** Your subclass should use this method to draw its content area.
  31645. The graphics object that is passed-in will have been clipped and had its origin
  31646. moved to fit the content area as specified get getContentArea(). The width and height
  31647. parameters are the width and height of the content area.
  31648. If the component you're writing isn't a button, you can just do nothing in this method.
  31649. */
  31650. virtual void paintButtonArea (Graphics& g,
  31651. int width, int height,
  31652. bool isMouseOver, bool isMouseDown) = 0;
  31653. /** Callback to indicate that the content area of this item has changed.
  31654. This might be because the component was resized, or because the style changed and
  31655. the space needed for the text label is different.
  31656. See getContentArea() for a description of what the area is.
  31657. */
  31658. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31659. /** Editing modes.
  31660. These are used by setEditingMode(), but will be rarely needed in user code.
  31661. */
  31662. enum ToolbarEditingMode
  31663. {
  31664. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31665. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31666. customisation mode, and the items can be dragged around. */
  31667. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31668. dragged onto a toolbar to add it to that bar.*/
  31669. };
  31670. /** Changes the editing mode of this component.
  31671. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31672. and is unlikely to be of much use in end-user-code.
  31673. */
  31674. void setEditingMode (const ToolbarEditingMode newMode);
  31675. /** Returns the current editing mode of this component.
  31676. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31677. and is unlikely to be of much use in end-user-code.
  31678. */
  31679. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31680. /** @internal */
  31681. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31682. /** @internal */
  31683. void resized();
  31684. juce_UseDebuggingNewOperator
  31685. private:
  31686. friend class Toolbar;
  31687. friend class ItemDragAndDropOverlayComponent;
  31688. const int itemId;
  31689. ToolbarEditingMode mode;
  31690. Toolbar::ToolbarItemStyle toolbarStyle;
  31691. Component* overlayComp;
  31692. int dragOffsetX, dragOffsetY;
  31693. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31694. Rectangle contentArea;
  31695. ToolbarItemComponent (const ToolbarItemComponent&);
  31696. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31697. };
  31698. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31699. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31700. /**
  31701. A type of button designed to go on a toolbar.
  31702. This simple button can have two Drawable objects specified - one for normal
  31703. use and another one (optionally) for the button's "on" state if it's a
  31704. toggle button.
  31705. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31706. */
  31707. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31708. {
  31709. public:
  31710. /** Creates a ToolbarButton.
  31711. @param itemId the ID for this toolbar item type. This is passed through to the
  31712. ToolbarItemComponent constructor
  31713. @param labelText the text to display on the button (if the toolbar is using a style
  31714. that shows text labels). This is passed through to the
  31715. ToolbarItemComponent constructor
  31716. @param normalImage a drawable object that the button should use as its icon. The object
  31717. that is passed-in here will be kept by this object and will be
  31718. deleted when no longer needed or when this button is deleted.
  31719. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31720. is in a toggled-on state (see the Button::getToggleState() method). If
  31721. 0 is passed-in here, then the normal image will be used instead, regardless
  31722. of the toggle state. The object that is passed-in here will be kept by
  31723. this object and will be deleted when no longer needed or when this button
  31724. is deleted.
  31725. */
  31726. ToolbarButton (const int itemId,
  31727. const String& labelText,
  31728. Drawable* const normalImage,
  31729. Drawable* const toggledOnImage);
  31730. /** Destructor. */
  31731. ~ToolbarButton();
  31732. /** @internal */
  31733. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31734. int& minSize, int& maxSize);
  31735. /** @internal */
  31736. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31737. /** @internal */
  31738. void contentAreaChanged (const Rectangle& newBounds);
  31739. juce_UseDebuggingNewOperator
  31740. private:
  31741. Drawable* const normalImage;
  31742. Drawable* const toggledOnImage;
  31743. ToolbarButton (const ToolbarButton&);
  31744. const ToolbarButton& operator= (const ToolbarButton&);
  31745. };
  31746. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31747. /********* End of inlined file: juce_ToolbarButton.h *********/
  31748. #endif
  31749. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31750. /********* Start of inlined file: juce_ArrowButton.h *********/
  31751. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31752. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31753. /**
  31754. A button with an arrow in it.
  31755. @see Button
  31756. */
  31757. class JUCE_API ArrowButton : public Button
  31758. {
  31759. public:
  31760. /** Creates an ArrowButton.
  31761. @param buttonName the name to give the button
  31762. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31763. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31764. @param arrowColour the colour to use for the arrow
  31765. */
  31766. ArrowButton (const String& buttonName,
  31767. float arrowDirection,
  31768. const Colour& arrowColour);
  31769. /** Destructor. */
  31770. ~ArrowButton();
  31771. juce_UseDebuggingNewOperator
  31772. protected:
  31773. /** @internal */
  31774. void paintButton (Graphics& g,
  31775. bool isMouseOverButton,
  31776. bool isButtonDown);
  31777. /** @internal */
  31778. void buttonStateChanged();
  31779. private:
  31780. Colour colour;
  31781. DropShadowEffect shadow;
  31782. Path path;
  31783. int offset;
  31784. ArrowButton (const ArrowButton&);
  31785. const ArrowButton& operator= (const ArrowButton&);
  31786. };
  31787. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31788. /********* End of inlined file: juce_ArrowButton.h *********/
  31789. #endif
  31790. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31791. #endif
  31792. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31793. /********* Start of inlined file: juce_DrawableButton.h *********/
  31794. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31795. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31796. /**
  31797. A button that displays a Drawable.
  31798. Up to three Drawable objects can be given to this button, to represent the
  31799. 'normal', 'over' and 'down' states.
  31800. @see Button
  31801. */
  31802. class JUCE_API DrawableButton : public Button
  31803. {
  31804. public:
  31805. enum ButtonStyle
  31806. {
  31807. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  31808. ImageRaw, /**< The button will just display the images in their normal size and position.
  31809. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  31810. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  31811. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  31812. };
  31813. /** Creates a DrawableButton.
  31814. After creating one of these, use setImages() to specify the drawables to use.
  31815. @param buttonName the name to give the component
  31816. @param buttonStyle the layout to use
  31817. @see ButtonStyle, setButtonStyle, setImages
  31818. */
  31819. DrawableButton (const String& buttonName,
  31820. const ButtonStyle buttonStyle);
  31821. /** Destructor. */
  31822. ~DrawableButton();
  31823. /** Sets up the images to draw for the various button states.
  31824. The button will keep its own internal copies of these drawables.
  31825. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  31826. will be made of the object passed-in if it is non-zero.
  31827. @param overImage the thing to draw for the button's 'over' state - if this is
  31828. zero, the button's normal image will be used when the mouse is
  31829. over it. An internal copy will be made of the object passed-in
  31830. if it is non-zero.
  31831. @param downImage the thing to draw for the button's 'down' state - if this is
  31832. zero, the 'over' image will be used instead (or the normal image
  31833. as a last resort). An internal copy will be made of the object
  31834. passed-in if it is non-zero.
  31835. @param disabledImage an image to draw when the button is disabled. If this is zero,
  31836. the normal image will be drawn with a reduced opacity instead.
  31837. An internal copy will be made of the object passed-in if it is
  31838. non-zero.
  31839. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  31840. state is 'on'. If this is 0, the normal image is used instead
  31841. @param overImageOn same as the overImage, but this is used when the button's toggle
  31842. state is 'on'. If this is 0, the normalImageOn is drawn instead
  31843. @param downImageOn same as the downImage, but this is used when the button's toggle
  31844. state is 'on'. If this is 0, the overImageOn is drawn instead
  31845. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  31846. state is 'on'. If this is 0, the normal image will be drawn instead
  31847. with a reduced opacity
  31848. */
  31849. void setImages (const Drawable* normalImage,
  31850. const Drawable* overImage = 0,
  31851. const Drawable* downImage = 0,
  31852. const Drawable* disabledImage = 0,
  31853. const Drawable* normalImageOn = 0,
  31854. const Drawable* overImageOn = 0,
  31855. const Drawable* downImageOn = 0,
  31856. const Drawable* disabledImageOn = 0);
  31857. /** Changes the button's style.
  31858. @see ButtonStyle
  31859. */
  31860. void setButtonStyle (const ButtonStyle newStyle);
  31861. /** Changes the button's background colours.
  31862. The toggledOffColour is the colour to use when the button's toggle state
  31863. is off, and toggledOnColour when it's on.
  31864. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  31865. used to fill the background of the component.
  31866. For an ImageOnButtonBackground style, the colour is used to draw the
  31867. button's lozenge shape and exactly how the colour's used will depend
  31868. on the LookAndFeel.
  31869. */
  31870. void setBackgroundColours (const Colour& toggledOffColour,
  31871. const Colour& toggledOnColour);
  31872. /** Returns the current background colour being used.
  31873. @see setBackgroundColour
  31874. */
  31875. const Colour& getBackgroundColour() const throw();
  31876. /** Gives the button an optional amount of space around the edge of the drawable.
  31877. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  31878. ones on a button background. If the button is too small for the given gap, a
  31879. smaller gap will be used.
  31880. By default there's a gap of about 3 pixels.
  31881. */
  31882. void setEdgeIndent (const int numPixelsIndent);
  31883. /** Returns the image that the button is currently displaying. */
  31884. const Drawable* getCurrentImage() const throw();
  31885. const Drawable* getNormalImage() const throw();
  31886. const Drawable* getOverImage() const throw();
  31887. const Drawable* getDownImage() const throw();
  31888. juce_UseDebuggingNewOperator
  31889. protected:
  31890. /** @internal */
  31891. void paintButton (Graphics& g,
  31892. bool isMouseOverButton,
  31893. bool isButtonDown);
  31894. private:
  31895. ButtonStyle style;
  31896. Drawable* normalImage;
  31897. Drawable* overImage;
  31898. Drawable* downImage;
  31899. Drawable* disabledImage;
  31900. Drawable* normalImageOn;
  31901. Drawable* overImageOn;
  31902. Drawable* downImageOn;
  31903. Drawable* disabledImageOn;
  31904. Colour backgroundOff, backgroundOn;
  31905. int edgeIndent;
  31906. void deleteImages();
  31907. DrawableButton (const DrawableButton&);
  31908. const DrawableButton& operator= (const DrawableButton&);
  31909. };
  31910. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31911. /********* End of inlined file: juce_DrawableButton.h *********/
  31912. #endif
  31913. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31914. #endif
  31915. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31916. /********* Start of inlined file: juce_GlowEffect.h *********/
  31917. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31918. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31919. /**
  31920. A component effect that adds a coloured blur around the component's contents.
  31921. (This will only work on non-opaque components).
  31922. @see Component::setComponentEffect, DropShadowEffect
  31923. */
  31924. class JUCE_API GlowEffect : public ImageEffectFilter
  31925. {
  31926. public:
  31927. /** Creates a default 'glow' effect.
  31928. To customise its appearance, use the setGlowProperties() method.
  31929. */
  31930. GlowEffect();
  31931. /** Destructor. */
  31932. ~GlowEffect();
  31933. /** Sets the glow's radius and colour.
  31934. The radius is how large the blur should be, and the colour is
  31935. used to render it (for a less intense glow, lower the colour's
  31936. opacity).
  31937. */
  31938. void setGlowProperties (const float newRadius,
  31939. const Colour& newColour);
  31940. /** @internal */
  31941. void applyEffect (Image& sourceImage, Graphics& destContext);
  31942. juce_UseDebuggingNewOperator
  31943. private:
  31944. float radius;
  31945. Colour colour;
  31946. };
  31947. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31948. /********* End of inlined file: juce_GlowEffect.h *********/
  31949. #endif
  31950. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31951. #endif
  31952. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31953. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31954. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31955. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31956. /**
  31957. An effect filter that reduces the image's opacity.
  31958. This can be used to make a component (and its child components) more
  31959. transparent.
  31960. @see Component::setComponentEffect
  31961. */
  31962. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31963. {
  31964. public:
  31965. /** Creates the effect object.
  31966. The opacity of the component to which the effect is applied will be
  31967. scaled by the given factor (in the range 0 to 1.0f).
  31968. */
  31969. ReduceOpacityEffect (const float opacity = 1.0f);
  31970. /** Destructor. */
  31971. ~ReduceOpacityEffect();
  31972. /** Sets how much to scale the component's opacity.
  31973. @param newOpacity should be between 0 and 1.0f
  31974. */
  31975. void setOpacity (const float newOpacity);
  31976. /** @internal */
  31977. void applyEffect (Image& sourceImage, Graphics& destContext);
  31978. juce_UseDebuggingNewOperator
  31979. private:
  31980. float opacity;
  31981. };
  31982. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31983. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31984. #endif
  31985. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31986. #endif
  31987. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31988. #endif
  31989. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31990. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31991. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31992. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31993. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31994. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31995. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31996. /**
  31997. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31998. command in a ApplicationCommandManager.
  31999. Normally, you won't actually create a KeyPressMappingSet directly, because
  32000. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  32001. you'd create yourself an ApplicationCommandManager, and call its
  32002. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  32003. KeyPressMappingSet.
  32004. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  32005. to the top-level component for which you want to handle keystrokes. So for example:
  32006. @code
  32007. class MyMainWindow : public Component
  32008. {
  32009. ApplicationCommandManager* myCommandManager;
  32010. public:
  32011. MyMainWindow()
  32012. {
  32013. myCommandManager = new ApplicationCommandManager();
  32014. // first, make sure the command manager has registered all the commands that its
  32015. // targets can perform..
  32016. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  32017. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  32018. // this will use the command manager to initialise the KeyPressMappingSet with
  32019. // the default keypresses that were specified when the targets added their commands
  32020. // to the manager.
  32021. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  32022. // having set up the default key-mappings, you might now want to load the last set
  32023. // of mappings that the user configured.
  32024. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  32025. // Now tell our top-level window to send any keypresses that arrive to the
  32026. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  32027. addKeyListener (myCommandManager->getKeyMappings());
  32028. }
  32029. ...
  32030. }
  32031. @endcode
  32032. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  32033. register to be told when a command or mapping is added, removed, etc.
  32034. There's also a UI component called KeyMappingEditorComponent that can be used
  32035. to easily edit the key mappings.
  32036. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  32037. */
  32038. class JUCE_API KeyPressMappingSet : public KeyListener,
  32039. public ChangeBroadcaster,
  32040. public FocusChangeListener
  32041. {
  32042. public:
  32043. /** Creates a KeyPressMappingSet for a given command manager.
  32044. Normally, you won't actually create a KeyPressMappingSet directly, because
  32045. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  32046. best thing to do is to create your ApplicationCommandManager, and use the
  32047. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  32048. When a suitable keypress happens, the manager's invoke() method will be
  32049. used to invoke the appropriate command.
  32050. @see ApplicationCommandManager
  32051. */
  32052. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  32053. /** Creates an copy of a KeyPressMappingSet. */
  32054. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  32055. /** Destructor. */
  32056. ~KeyPressMappingSet();
  32057. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  32058. /** Returns a list of keypresses that are assigned to a particular command.
  32059. @param commandID the command's ID
  32060. */
  32061. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  32062. /** Assigns a keypress to a command.
  32063. If the keypress is already assigned to a different command, it will first be
  32064. removed from that command, to avoid it triggering multiple functions.
  32065. @param commandID the ID of the command that you want to add a keypress to. If
  32066. this is 0, the keypress will be removed from anything that it
  32067. was previously assigned to, but not re-assigned
  32068. @param newKeyPress the new key-press
  32069. @param insertIndex if this is less than zero, the key will be appended to the
  32070. end of the list of keypresses; otherwise the new keypress will
  32071. be inserted into the existing list at this index
  32072. */
  32073. void addKeyPress (const CommandID commandID,
  32074. const KeyPress& newKeyPress,
  32075. int insertIndex = -1) throw();
  32076. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  32077. @see resetToDefaultMapping
  32078. */
  32079. void resetToDefaultMappings() throw();
  32080. /** Resets all key-mappings to the defaults for a particular command.
  32081. @see resetToDefaultMappings
  32082. */
  32083. void resetToDefaultMapping (const CommandID commandID) throw();
  32084. /** Removes all keypresses that are assigned to any commands. */
  32085. void clearAllKeyPresses() throw();
  32086. /** Removes all keypresses that are assigned to a particular command. */
  32087. void clearAllKeyPresses (const CommandID commandID) throw();
  32088. /** Removes one of the keypresses that are assigned to a command.
  32089. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  32090. which the keyPressIndex refers.
  32091. */
  32092. void removeKeyPress (const CommandID commandID,
  32093. const int keyPressIndex) throw();
  32094. /** Removes a keypress from any command that it may be assigned to.
  32095. */
  32096. void removeKeyPress (const KeyPress& keypress) throw();
  32097. /** Returns true if the given command is linked to this key. */
  32098. bool containsMapping (const CommandID commandID,
  32099. const KeyPress& keyPress) const throw();
  32100. /** Looks for a command that corresponds to a keypress.
  32101. @returns the UID of the command or 0 if none was found
  32102. */
  32103. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  32104. /** Tries to recreate the mappings from a previously stored state.
  32105. The XML passed in must have been created by the createXml() method.
  32106. If the stored state makes any reference to commands that aren't
  32107. currently available, these will be ignored.
  32108. If the set of mappings being loaded was a set of differences (using createXml (true)),
  32109. then this will call resetToDefaultMappings() and then merge the saved mappings
  32110. on top. If the saved set was created with createXml (false), then this method
  32111. will first clear all existing mappings and load the saved ones as a complete set.
  32112. @returns true if it manages to load the XML correctly
  32113. @see createXml
  32114. */
  32115. bool restoreFromXml (const XmlElement& xmlVersion);
  32116. /** Creates an XML representation of the current mappings.
  32117. This will produce a lump of XML that can be later reloaded using
  32118. restoreFromXml() to recreate the current mapping state.
  32119. The object that is returned must be deleted by the caller.
  32120. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  32121. will be saved into the XML. If it's true, then the XML will
  32122. only store the differences between the current mappings and
  32123. the default mappings you'd get from calling resetToDefaultMappings().
  32124. The advantage of saving a set of differences from the default is that
  32125. if you change the default mappings (in a new version of your app, for
  32126. example), then these will be merged into a user's saved preferences.
  32127. @see restoreFromXml
  32128. */
  32129. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  32130. /** @internal */
  32131. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  32132. /** @internal */
  32133. bool keyStateChanged (Component* originatingComponent);
  32134. /** @internal */
  32135. void globalFocusChanged (Component* focusedComponent);
  32136. juce_UseDebuggingNewOperator
  32137. private:
  32138. ApplicationCommandManager* commandManager;
  32139. struct CommandMapping
  32140. {
  32141. CommandID commandID;
  32142. Array <KeyPress> keypresses;
  32143. bool wantsKeyUpDownCallbacks;
  32144. };
  32145. OwnedArray <CommandMapping> mappings;
  32146. struct KeyPressTime
  32147. {
  32148. KeyPress key;
  32149. uint32 timeWhenPressed;
  32150. };
  32151. OwnedArray <KeyPressTime> keysDown;
  32152. void handleMessage (const Message& message);
  32153. void invokeCommand (const CommandID commandID,
  32154. const KeyPress& keyPress,
  32155. const bool isKeyDown,
  32156. const int millisecsSinceKeyPressed,
  32157. Component* const originatingComponent) const;
  32158. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  32159. };
  32160. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32161. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  32162. /********* Start of inlined file: juce_TreeView.h *********/
  32163. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  32164. #define __JUCE_TREEVIEW_JUCEHEADER__
  32165. class TreeView;
  32166. /**
  32167. An item in a treeview.
  32168. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  32169. own sub-items.
  32170. To implement an item that contains sub-items, override the itemOpennessChanged()
  32171. method so that when it is opened, it adds the new sub-items to itself using the
  32172. addSubItem method. Depending on the nature of the item it might choose to only
  32173. do this the first time it's opened, or it might want to refresh itself each time.
  32174. It also has the option of deleting its sub-items when it is closed, or leaving them
  32175. in place.
  32176. */
  32177. class JUCE_API TreeViewItem
  32178. {
  32179. public:
  32180. /** Constructor. */
  32181. TreeViewItem();
  32182. /** Destructor. */
  32183. virtual ~TreeViewItem();
  32184. /** Returns the number of sub-items that have been added to this item.
  32185. Note that this doesn't mean much if the node isn't open.
  32186. @see getSubItem, mightContainSubItems, addSubItem
  32187. */
  32188. int getNumSubItems() const throw();
  32189. /** Returns one of the item's sub-items.
  32190. Remember that the object returned might get deleted at any time when its parent
  32191. item is closed or refreshed, depending on the nature of the items you're using.
  32192. @see getNumSubItems
  32193. */
  32194. TreeViewItem* getSubItem (const int index) const throw();
  32195. /** Removes any sub-items. */
  32196. void clearSubItems();
  32197. /** Adds a sub-item.
  32198. @param newItem the object to add to the item's sub-item list. Once added, these can be
  32199. found using getSubItem(). When the items are later removed with
  32200. removeSubItem() (or when this item is deleted), they will be deleted.
  32201. @param insertPosition the index which the new item should have when it's added. If this
  32202. value is less than 0, the item will be added to the end of the list.
  32203. */
  32204. void addSubItem (TreeViewItem* const newItem,
  32205. const int insertPosition = -1);
  32206. /** Removes one of the sub-items.
  32207. @param index the item to remove
  32208. @param deleteItem if true, the item that is removed will also be deleted.
  32209. */
  32210. void removeSubItem (const int index,
  32211. const bool deleteItem = true);
  32212. /** Returns the TreeView to which this item belongs. */
  32213. TreeView* getOwnerView() const throw() { return ownerView; }
  32214. /** Returns the item within which this item is contained. */
  32215. TreeViewItem* getParentItem() const throw() { return parentItem; }
  32216. /** True if this item is currently open in the treeview. */
  32217. bool isOpen() const throw();
  32218. /** Opens or closes the item.
  32219. When opened or closed, the item's itemOpennessChanged() method will be called,
  32220. and a subclass should use this callback to create and add any sub-items that
  32221. it needs to.
  32222. @see itemOpennessChanged, mightContainSubItems
  32223. */
  32224. void setOpen (const bool shouldBeOpen);
  32225. /** True if this item is currently selected.
  32226. Use this when painting the node, to decide whether to draw it as selected or not.
  32227. */
  32228. bool isSelected() const throw();
  32229. /** Selects or deselects the item.
  32230. This will cause a callback to itemSelectionChanged()
  32231. */
  32232. void setSelected (const bool shouldBeSelected,
  32233. const bool deselectOtherItemsFirst);
  32234. /** Returns the rectangle that this item occupies.
  32235. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  32236. top-left of the TreeView comp, so this will depend on the scroll-position of
  32237. the tree. If false, it is relative to the top-left of the topmost item in the
  32238. tree (so this would be unaffected by scrolling the view).
  32239. */
  32240. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  32241. /** Sends a signal to the treeview to make it refresh itself.
  32242. Call this if your items have changed and you want the tree to update to reflect
  32243. this.
  32244. */
  32245. void treeHasChanged() const throw();
  32246. /** Sends a repaint message to redraw just this item.
  32247. Note that you should only call this if you want to repaint a superficial change. If
  32248. you're altering the tree's nodes, you should instead call treeHasChanged().
  32249. */
  32250. void repaintItem() const;
  32251. /** Returns the row number of this item in the tree.
  32252. The row number of an item will change according to which items are open.
  32253. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  32254. */
  32255. int getRowNumberInTree() const throw();
  32256. /** Returns true if all the item's parent nodes are open.
  32257. This is useful to check whether the item might actually be visible or not.
  32258. */
  32259. bool areAllParentsOpen() const throw();
  32260. /** Changes whether lines are drawn to connect any sub-items to this item.
  32261. By default, line-drawing is turned on.
  32262. */
  32263. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  32264. /** Tells the tree whether this item can potentially be opened.
  32265. If your item could contain sub-items, this should return true; if it returns
  32266. false then the tree will not try to open the item. This determines whether or
  32267. not the item will be drawn with a 'plus' button next to it.
  32268. */
  32269. virtual bool mightContainSubItems() = 0;
  32270. /** Returns a string to uniquely identify this item.
  32271. If you're planning on using the TreeView::getOpennessState() method, then
  32272. these strings will be used to identify which nodes are open. The string
  32273. should be unique amongst the item's sibling items, but it's ok for there
  32274. to be duplicates at other levels of the tree.
  32275. If you're not going to store the state, then it's ok not to bother implementing
  32276. this method.
  32277. */
  32278. virtual const String getUniqueName() const;
  32279. /** Called when an item is opened or closed.
  32280. When setOpen() is called and the item has specified that it might
  32281. have sub-items with the mightContainSubItems() method, this method
  32282. is called to let the item create or manage its sub-items.
  32283. So when this is called with isNowOpen set to true (i.e. when the item is being
  32284. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  32285. refresh its sub-item list.
  32286. When this is called with isNowOpen set to false, the subclass might want
  32287. to use clearSubItems() to save on space, or it might choose to leave them,
  32288. depending on the nature of the tree.
  32289. You could also use this callback as a trigger to start a background process
  32290. which asynchronously creates sub-items and adds them, if that's more
  32291. appropriate for the task in hand.
  32292. @see mightContainSubItems
  32293. */
  32294. virtual void itemOpennessChanged (bool isNowOpen);
  32295. /** Must return the width required by this item.
  32296. If your item needs to have a particular width in pixels, return that value; if
  32297. you'd rather have it just fill whatever space is available in the treeview,
  32298. return -1.
  32299. If all your items return -1, no horizontal scrollbar will be shown, but if any
  32300. items have fixed widths and extend beyond the width of the treeview, a
  32301. scrollbar will appear.
  32302. Each item can be a different width, but if they change width, you should call
  32303. treeHasChanged() to update the tree.
  32304. */
  32305. virtual int getItemWidth() const { return -1; }
  32306. /** Must return the height required by this item.
  32307. This is the height in pixels that the item will take up. Items in the tree
  32308. can be different heights, but if they change height, you should call
  32309. treeHasChanged() to update the tree.
  32310. */
  32311. virtual int getItemHeight() const { return 20; }
  32312. /** You can override this method to return false if you don't want to allow the
  32313. user to select this item.
  32314. */
  32315. virtual bool canBeSelected() const { return true; }
  32316. /** Creates a component that will be used to represent this item.
  32317. You don't have to implement this method - if it returns 0 then no component
  32318. will be used for the item, and you can just draw it using the paintItem()
  32319. callback. But if you do return a component, it will be positioned in the
  32320. treeview so that it can be used to represent this item.
  32321. The component returned will be managed by the treeview, so always return
  32322. a new component, and don't keep a reference to it, as the treeview will
  32323. delete it later when it goes off the screen or is no longer needed. Also
  32324. bear in mind that if the component keeps a reference to the item that
  32325. created it, that item could be deleted before the component. Its position
  32326. and size will be completely managed by the tree, so don't attempt to move it
  32327. around.
  32328. Something you may want to do with your component is to give it a pointer to
  32329. the TreeView that created it. This is perfectly safe, and there's no danger
  32330. of it becoming a dangling pointer because the TreeView will always delete
  32331. the component before it is itself deleted.
  32332. As long as you stick to these rules you can return whatever kind of
  32333. component you like. It's most useful if you're doing things like drag-and-drop
  32334. of items, or want to use a Label component to edit item names, etc.
  32335. */
  32336. virtual Component* createItemComponent() { return 0; }
  32337. /** Draws the item's contents.
  32338. You can choose to either implement this method and draw each item, or you
  32339. can use createItemComponent() to create a component that will represent the
  32340. item.
  32341. If all you need in your tree is to be able to draw the items and detect when
  32342. the user selects or double-clicks one of them, it's probably enough to
  32343. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  32344. complicated interactions, you may need to use createItemComponent() instead.
  32345. @param g the graphics context to draw into
  32346. @param width the width of the area available for drawing
  32347. @param height the height of the area available for drawing
  32348. */
  32349. virtual void paintItem (Graphics& g, int width, int height);
  32350. /** Draws the item's open/close button.
  32351. If you don't implement this method, the default behaviour is to
  32352. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  32353. it for custom effects.
  32354. */
  32355. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  32356. /** Called when the user clicks on this item.
  32357. If you're using createItemComponent() to create a custom component for the
  32358. item, the mouse-clicks might not make it through to the treeview, but this
  32359. is how you find out about clicks when just drawing each item individually.
  32360. The associated mouse-event details are passed in, so you can find out about
  32361. which button, where it was, etc.
  32362. @see itemDoubleClicked
  32363. */
  32364. virtual void itemClicked (const MouseEvent& e);
  32365. /** Called when the user double-clicks on this item.
  32366. If you're using createItemComponent() to create a custom component for the
  32367. item, the mouse-clicks might not make it through to the treeview, but this
  32368. is how you find out about clicks when just drawing each item individually.
  32369. The associated mouse-event details are passed in, so you can find out about
  32370. which button, where it was, etc.
  32371. If not overridden, the base class method here will open or close the item as
  32372. if the 'plus' button had been clicked.
  32373. @see itemClicked
  32374. */
  32375. virtual void itemDoubleClicked (const MouseEvent& e);
  32376. /** Called when the item is selected or deselected.
  32377. Use this if you want to do something special when the item's selectedness
  32378. changes. By default it'll get repainted when this happens.
  32379. */
  32380. virtual void itemSelectionChanged (bool isNowSelected);
  32381. /** The item can return a tool tip string here if it wants to.
  32382. @see TooltipClient
  32383. */
  32384. virtual const String getTooltip();
  32385. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  32386. If this returns a non-empty name then when the user drags an item, the treeview will
  32387. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32388. a drag-and-drop operation, using this string as the source description, with the treeview
  32389. itself as the source component.
  32390. If you need more complex drag-and-drop behaviour, you can use custom components for
  32391. the items, and use those to trigger the drag.
  32392. @see DragAndDropContainer::startDragging
  32393. */
  32394. virtual const String getDragSourceDescription();
  32395. /** Sets a flag to indicate that the item wants to be allowed
  32396. to draw all the way across to the left edge of the treeview.
  32397. By default this is false, which means that when the paintItem()
  32398. method is called, its graphics context is clipped to only allow
  32399. drawing within the item's rectangle. If this flag is set to true,
  32400. then the graphics context isn't clipped on its left side, so it
  32401. can draw all the way across to the left margin. Note that the
  32402. context will still have its origin in the same place though, so
  32403. the coordinates of anything to its left will be negative. It's
  32404. mostly useful if you want to draw a wider bar behind the
  32405. highlighted item.
  32406. */
  32407. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  32408. juce_UseDebuggingNewOperator
  32409. private:
  32410. TreeView* ownerView;
  32411. TreeViewItem* parentItem;
  32412. OwnedArray <TreeViewItem> subItems;
  32413. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  32414. int uid;
  32415. bool selected : 1;
  32416. bool redrawNeeded : 1;
  32417. bool drawLinesInside : 1;
  32418. bool drawsInLeftMargin : 1;
  32419. unsigned int openness : 2;
  32420. friend class TreeView;
  32421. friend class TreeViewContentComponent;
  32422. void updatePositions (int newY);
  32423. int getIndentX() const throw();
  32424. void setOwnerView (TreeView* const newOwner) throw();
  32425. void paintRecursively (Graphics& g, int width);
  32426. TreeViewItem* findItemRecursively (int y) throw();
  32427. TreeViewItem* getDeepestOpenParentItem() throw();
  32428. void restoreFromXml (const XmlElement& e);
  32429. XmlElement* createXmlOpenness() const;
  32430. bool isLastOfSiblings() const throw();
  32431. TreeViewItem* getTopLevelItem() throw();
  32432. int getNumRows() const throw();
  32433. TreeViewItem* getItemOnRow (int index) throw();
  32434. void deselectAllRecursively();
  32435. int countSelectedItemsRecursively() const throw();
  32436. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  32437. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  32438. TreeViewItem (const TreeViewItem&);
  32439. const TreeViewItem& operator= (const TreeViewItem&);
  32440. };
  32441. /**
  32442. A tree-view component.
  32443. Use one of these to hold and display a structure of TreeViewItem objects.
  32444. */
  32445. class JUCE_API TreeView : public Component,
  32446. public SettableTooltipClient,
  32447. private AsyncUpdater
  32448. {
  32449. public:
  32450. /** Creates an empty treeview.
  32451. Once you've got a treeview component, you'll need to give it something to
  32452. display, using the setRootItem() method.
  32453. */
  32454. TreeView (const String& componentName = String::empty);
  32455. /** Destructor. */
  32456. ~TreeView();
  32457. /** Sets the item that is displayed in the treeview.
  32458. A tree has a single root item which contains as many sub-items as it needs. If
  32459. you want the tree to contain a number of root items, you should still use a single
  32460. root item above these, but hide it using setRootItemVisible().
  32461. You can pass in 0 to this method to clear the tree and remove its current root item.
  32462. The object passed in will not be deleted by the treeview, it's up to the caller
  32463. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32464. this item until you've removed it from the tree, either by calling setRootItem (0),
  32465. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  32466. to delete it.
  32467. */
  32468. void setRootItem (TreeViewItem* const newRootItem);
  32469. /** Returns the tree's root item.
  32470. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32471. */
  32472. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32473. /** This will remove and delete the current root item.
  32474. It's a convenient way of deleting the item and calling setRootItem (0).
  32475. */
  32476. void deleteRootItem();
  32477. /** Changes whether the tree's root item is shown or not.
  32478. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32479. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32480. will also make sure the root item is open (otherwise the treeview would look empty).
  32481. */
  32482. void setRootItemVisible (const bool shouldBeVisible);
  32483. /** Returns true if the root item is visible.
  32484. @see setRootItemVisible
  32485. */
  32486. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32487. /** Sets whether items are open or closed by default.
  32488. Normally, items are closed until the user opens them, but you can use this
  32489. to make them default to being open until explicitly closed.
  32490. @see areItemsOpenByDefault
  32491. */
  32492. void setDefaultOpenness (const bool isOpenByDefault);
  32493. /** Returns true if the tree's items default to being open.
  32494. @see setDefaultOpenness
  32495. */
  32496. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32497. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32498. You can always select multiple items internally by calling the
  32499. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32500. is allowed to multi-select by clicking on the tree.
  32501. By default it is disabled.
  32502. @see isMultiSelectEnabled
  32503. */
  32504. void setMultiSelectEnabled (const bool canMultiSelect);
  32505. /** Returns whether multi-select has been enabled for the tree.
  32506. @see setMultiSelectEnabled
  32507. */
  32508. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32509. /** Sets a flag to indicate whether to hide the open/close buttons.
  32510. @see areOpenCloseButtonsVisible
  32511. */
  32512. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  32513. /** Returns whether open/close buttons are shown.
  32514. @see setOpenCloseButtonsVisible
  32515. */
  32516. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  32517. /** Deselects any items that are currently selected. */
  32518. void clearSelectedItems();
  32519. /** Returns the number of items that are currently selected.
  32520. @see getSelectedItem, clearSelectedItems
  32521. */
  32522. int getNumSelectedItems() const throw();
  32523. /** Returns one of the selected items in the tree.
  32524. @param index the index, 0 to (getNumSelectedItems() - 1)
  32525. */
  32526. TreeViewItem* getSelectedItem (const int index) const throw();
  32527. /** Returns the number of rows the tree is using.
  32528. This will depend on which items are open.
  32529. @see TreeViewItem::getRowNumberInTree()
  32530. */
  32531. int getNumRowsInTree() const;
  32532. /** Returns the item on a particular row of the tree.
  32533. If the index is out of range, this will return 0.
  32534. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  32535. */
  32536. TreeViewItem* getItemOnRow (int index) const;
  32537. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  32538. void scrollToKeepItemVisible (TreeViewItem* item);
  32539. /** Returns the treeview's Viewport object. */
  32540. Viewport* getViewport() const throw() { return viewport; }
  32541. /** Returns the number of pixels by which each nested level of the tree is indented.
  32542. @see setIndentSize
  32543. */
  32544. int getIndentSize() const throw() { return indentSize; }
  32545. /** Changes the distance by which each nested level of the tree is indented.
  32546. @see getIndentSize
  32547. */
  32548. void setIndentSize (const int newIndentSize);
  32549. /** Saves the current state of open/closed nodes so it can be restored later.
  32550. This takes a snapshot of which nodes have been explicitly opened or closed,
  32551. and records it as XML. To identify node objects it uses the
  32552. TreeViewItem::getUniqueName() method to create named paths. This
  32553. means that the same state of open/closed nodes can be restored to a
  32554. completely different instance of the tree, as long as it contains nodes
  32555. whose unique names are the same.
  32556. The caller is responsible for deleting the object that is returned.
  32557. @param alsoIncludeScrollPosition if this is true, the state will also
  32558. include information about where the
  32559. tree has been scrolled to vertically,
  32560. so this can also be restored
  32561. @see restoreOpennessState
  32562. */
  32563. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32564. /** Restores a previously saved arrangement of open/closed nodes.
  32565. This will try to restore a snapshot of the tree's state that was created by
  32566. the getOpennessState() method. If any of the nodes named in the original
  32567. XML aren't present in this tree, they will be ignored.
  32568. @see getOpennessState
  32569. */
  32570. void restoreOpennessState (const XmlElement& newState);
  32571. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32572. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32573. methods.
  32574. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32575. */
  32576. enum ColourIds
  32577. {
  32578. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32579. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32580. };
  32581. /** @internal */
  32582. void paint (Graphics& g);
  32583. /** @internal */
  32584. void resized();
  32585. /** @internal */
  32586. bool keyPressed (const KeyPress& key);
  32587. /** @internal */
  32588. void colourChanged();
  32589. /** @internal */
  32590. void enablementChanged();
  32591. juce_UseDebuggingNewOperator
  32592. private:
  32593. friend class TreeViewItem;
  32594. friend class TreeViewContentComponent;
  32595. Viewport* viewport;
  32596. CriticalSection nodeAlterationLock;
  32597. TreeViewItem* rootItem;
  32598. int indentSize;
  32599. bool defaultOpenness : 1;
  32600. bool needsRecalculating : 1;
  32601. bool rootItemVisible : 1;
  32602. bool multiSelectEnabled : 1;
  32603. bool openCloseButtonsVisible : 1;
  32604. void itemsChanged() throw();
  32605. void handleAsyncUpdate();
  32606. void moveSelectedRow (int delta);
  32607. void updateButtonUnderMouse (const MouseEvent& e);
  32608. TreeView (const TreeView&);
  32609. const TreeView& operator= (const TreeView&);
  32610. };
  32611. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32612. /********* End of inlined file: juce_TreeView.h *********/
  32613. /**
  32614. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32615. object.
  32616. @see KeyPressMappingSet
  32617. */
  32618. class JUCE_API KeyMappingEditorComponent : public Component,
  32619. public TreeViewItem,
  32620. public ChangeListener,
  32621. private ButtonListener
  32622. {
  32623. public:
  32624. /** Creates a KeyMappingEditorComponent.
  32625. @param mappingSet this is the set of mappings to display and
  32626. edit. Make sure the mappings object is not
  32627. deleted before this component!
  32628. @param showResetToDefaultButton if true, then at the bottom of the
  32629. list, the component will include a 'reset to
  32630. defaults' button.
  32631. */
  32632. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32633. const bool showResetToDefaultButton);
  32634. /** Destructor. */
  32635. virtual ~KeyMappingEditorComponent();
  32636. /** Sets up the colours to use for parts of the component.
  32637. @param mainBackground colour to use for most of the background
  32638. @param textColour colour to use for the text
  32639. */
  32640. void setColours (const Colour& mainBackground,
  32641. const Colour& textColour);
  32642. /** Returns the KeyPressMappingSet that this component is acting upon.
  32643. */
  32644. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32645. /** Can be overridden if some commands need to be excluded from the list.
  32646. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32647. method to decide what to return, but you can override it to handle special cases.
  32648. */
  32649. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32650. /** Can be overridden to indicate that some commands are shown as read-only.
  32651. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32652. method to decide what to return, but you can override it to handle special cases.
  32653. */
  32654. virtual bool isCommandReadOnly (const CommandID commandID);
  32655. /** This can be overridden to let you change the format of the string used
  32656. to describe a keypress.
  32657. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32658. keys that are triggered by something else externally. If you override the
  32659. method, be sure to let the base class's method handle keys you're not
  32660. interested in.
  32661. */
  32662. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32663. /** @internal */
  32664. void parentHierarchyChanged();
  32665. /** @internal */
  32666. void resized();
  32667. /** @internal */
  32668. void changeListenerCallback (void*);
  32669. /** @internal */
  32670. bool mightContainSubItems();
  32671. /** @internal */
  32672. const String getUniqueName() const;
  32673. /** @internal */
  32674. void buttonClicked (Button* button);
  32675. juce_UseDebuggingNewOperator
  32676. private:
  32677. KeyPressMappingSet* mappings;
  32678. TreeView* tree;
  32679. friend class KeyMappingTreeViewItem;
  32680. friend class KeyCategoryTreeViewItem;
  32681. friend class KeyMappingItemComponent;
  32682. friend class KeyMappingChangeButton;
  32683. Colour backgroundColour, textColour;
  32684. TextButton* resetButton;
  32685. void assignNewKey (const CommandID commandID, int index);
  32686. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32687. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32688. };
  32689. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32690. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32691. #endif
  32692. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32693. #endif
  32694. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32695. #endif
  32696. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32697. #endif
  32698. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32699. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32700. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32701. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32702. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32703. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32704. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32705. class MenuBarModel;
  32706. /**
  32707. A class to receive callbacks when a MenuBarModel changes.
  32708. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32709. */
  32710. class JUCE_API MenuBarModelListener
  32711. {
  32712. public:
  32713. /** Destructor. */
  32714. virtual ~MenuBarModelListener() {}
  32715. /** This callback is made when items are changed in the menu bar model.
  32716. */
  32717. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32718. /** This callback is made when an application command is invoked that
  32719. is represented by one of the items in the menu bar model.
  32720. */
  32721. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32722. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32723. };
  32724. /**
  32725. A class for controlling MenuBar components.
  32726. This class is used to tell a MenuBar what menus to show, and to respond
  32727. to a menu being selected.
  32728. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32729. */
  32730. class JUCE_API MenuBarModel : private AsyncUpdater,
  32731. private ApplicationCommandManagerListener
  32732. {
  32733. public:
  32734. MenuBarModel() throw();
  32735. /** Destructor. */
  32736. virtual ~MenuBarModel();
  32737. /** Call this when some of your menu items have changed.
  32738. This method will cause a callback to any MenuBarListener objects that
  32739. are registered with this model.
  32740. If this model is displaying items from an ApplicationCommandManager, you
  32741. can use the setApplicationCommandManagerToWatch() method to cause
  32742. change messages to be sent automatically when the ApplicationCommandManager
  32743. is changed.
  32744. @see addListener, removeListener, MenuBarListener
  32745. */
  32746. void menuItemsChanged();
  32747. /** Tells the menu bar to listen to the specified command manager, and to update
  32748. itself when the commands change.
  32749. This will also allow it to flash a menu name when a command from that menu
  32750. is invoked using a keystroke.
  32751. */
  32752. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32753. /** Registers a listener for callbacks when the menu items in this model change.
  32754. The listener object will get callbacks when this object's menuItemsChanged()
  32755. method is called.
  32756. @see removeListener
  32757. */
  32758. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32759. /** Removes a listener.
  32760. @see addListener
  32761. */
  32762. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32763. /** This method must return a list of the names of the menus. */
  32764. virtual const StringArray getMenuBarNames() = 0;
  32765. /** This should return the popup menu to display for a given top-level menu.
  32766. @param topLevelMenuIndex the index of the top-level menu to show
  32767. @param menuName the name of the top-level menu item to show
  32768. */
  32769. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32770. const String& menuName) = 0;
  32771. /** This is called when a menu item has been clicked on.
  32772. @param menuItemID the item ID of the PopupMenu item that was selected
  32773. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32774. chosen (just in case you've used duplicate ID numbers
  32775. on more than one of the popup menus)
  32776. */
  32777. virtual void menuItemSelected (int menuItemID,
  32778. int topLevelMenuIndex) = 0;
  32779. #if JUCE_MAC || DOXYGEN
  32780. /** MAC ONLY - Sets the model that is currently being shown as the main
  32781. menu bar at the top of the screen on the Mac.
  32782. You can pass 0 to stop the current model being displayed. Be careful
  32783. not to delete a model while it is being used.
  32784. An optional extra menu can be specified, containing items to add to the top of
  32785. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  32786. an apple, it's the one next to it, with your application's name at the top
  32787. and the services menu etc on it). When one of these items is selected, the
  32788. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  32789. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  32790. object then newMenuBarModel must be non-null.
  32791. */
  32792. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  32793. const PopupMenu* extraAppleMenuItems = 0) throw();
  32794. /** MAC ONLY - Returns the menu model that is currently being shown as
  32795. the main menu bar.
  32796. */
  32797. static MenuBarModel* getMacMainMenu() throw();
  32798. #endif
  32799. /** @internal */
  32800. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32801. /** @internal */
  32802. void applicationCommandListChanged();
  32803. /** @internal */
  32804. void handleAsyncUpdate();
  32805. juce_UseDebuggingNewOperator
  32806. private:
  32807. ApplicationCommandManager* manager;
  32808. SortedSet <void*> listeners;
  32809. MenuBarModel (const MenuBarModel&);
  32810. const MenuBarModel& operator= (const MenuBarModel&);
  32811. };
  32812. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32813. /********* End of inlined file: juce_MenuBarModel.h *********/
  32814. /**
  32815. A menu bar component.
  32816. @see MenuBarModel
  32817. */
  32818. class JUCE_API MenuBarComponent : public Component,
  32819. private MenuBarModelListener,
  32820. private Timer
  32821. {
  32822. public:
  32823. /** Creates a menu bar.
  32824. @param model the model object to use to control this bar. You can
  32825. pass 0 into this if you like, and set the model later
  32826. using the setModel() method
  32827. */
  32828. MenuBarComponent (MenuBarModel* const model);
  32829. /** Destructor. */
  32830. ~MenuBarComponent();
  32831. /** Changes the model object to use to control the bar.
  32832. This can be 0, in which case the bar will be empty. Don't delete the object
  32833. that is passed-in while it's still being used by this MenuBar.
  32834. */
  32835. void setModel (MenuBarModel* const newModel);
  32836. /** Pops up one of the menu items.
  32837. This lets you manually open one of the menus - it could be triggered by a
  32838. key shortcut, for example.
  32839. */
  32840. void showMenu (const int menuIndex);
  32841. /** @internal */
  32842. void paint (Graphics& g);
  32843. /** @internal */
  32844. void resized();
  32845. /** @internal */
  32846. void mouseEnter (const MouseEvent& e);
  32847. /** @internal */
  32848. void mouseExit (const MouseEvent& e);
  32849. /** @internal */
  32850. void mouseDown (const MouseEvent& e);
  32851. /** @internal */
  32852. void mouseDrag (const MouseEvent& e);
  32853. /** @internal */
  32854. void mouseUp (const MouseEvent& e);
  32855. /** @internal */
  32856. void mouseMove (const MouseEvent& e);
  32857. /** @internal */
  32858. void inputAttemptWhenModal();
  32859. /** @internal */
  32860. void handleCommandMessage (int commandId);
  32861. /** @internal */
  32862. bool keyPressed (const KeyPress& key);
  32863. /** @internal */
  32864. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32865. /** @internal */
  32866. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32867. const ApplicationCommandTarget::InvocationInfo& info);
  32868. juce_UseDebuggingNewOperator
  32869. private:
  32870. MenuBarModel* model;
  32871. StringArray menuNames;
  32872. Array <int> xPositions;
  32873. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32874. int lastMouseX, lastMouseY;
  32875. bool inModalState;
  32876. Component* currentPopup;
  32877. int getItemAt (int x, int y);
  32878. void updateItemUnderMouse (const int x, const int y);
  32879. void hideCurrentMenu();
  32880. void timerCallback();
  32881. void repaintMenuItem (int index);
  32882. MenuBarComponent (const MenuBarComponent&);
  32883. const MenuBarComponent& operator= (const MenuBarComponent&);
  32884. };
  32885. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32886. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32887. #endif
  32888. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32889. #endif
  32890. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32891. #endif
  32892. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32893. #endif
  32894. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32895. #endif
  32896. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32897. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32898. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32899. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32900. /**
  32901. Components derived from this class can have files dropped onto them by an external application.
  32902. @see DragAndDropContainer
  32903. */
  32904. class JUCE_API FileDragAndDropTarget
  32905. {
  32906. public:
  32907. /** Destructor. */
  32908. virtual ~FileDragAndDropTarget() {}
  32909. /** Callback to check whether this target is interested in the set of files being offered.
  32910. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32911. component, so don't do anything time-consuming in here, like opening the files to have a look
  32912. inside them!
  32913. @param files the set of (absolute) pathnames of the files that the user is dragging
  32914. @returns true if this component wants to receive the other callbacks regarging this
  32915. type of object; if it returns false, no other callbacks will be made.
  32916. */
  32917. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32918. /** Callback to indicate that some files are being dragged over this component.
  32919. This gets called when the user moves the mouse into this component while dragging.
  32920. Use this callback as a trigger to make your component repaint itself to give the
  32921. user feedback about whether the files can be dropped here or not.
  32922. @param files the set of (absolute) pathnames of the files that the user is dragging
  32923. @param x the mouse x position, relative to this component
  32924. @param y the mouse y position, relative to this component
  32925. */
  32926. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32927. /** Callback to indicate that the user is dragging some files over this component.
  32928. This gets called when the user moves the mouse over this component while dragging.
  32929. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32930. this lets you know what happens in-between.
  32931. @param files the set of (absolute) pathnames of the files that the user is dragging
  32932. @param x the mouse x position, relative to this component
  32933. @param y the mouse y position, relative to this component
  32934. */
  32935. virtual void fileDragMove (const StringArray& files, int x, int y);
  32936. /** Callback to indicate that the mouse has moved away from this component.
  32937. This gets called when the user moves the mouse out of this component while dragging
  32938. the files.
  32939. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32940. as a signal to repaint it in its normal state.
  32941. @param files the set of (absolute) pathnames of the files that the user is dragging
  32942. */
  32943. virtual void fileDragExit (const StringArray& files);
  32944. /** Callback to indicate that the user has dropped the files onto this component.
  32945. When the user drops the files, this get called, and you can use the files in whatever
  32946. way is appropriate.
  32947. Note that after this is called, the fileDragExit method may not be called, so you should
  32948. clean up in here if there's anything you need to do when the drag finishes.
  32949. @param files the set of (absolute) pathnames of the files that the user is dragging
  32950. @param x the mouse x position, relative to this component
  32951. @param y the mouse y position, relative to this component
  32952. */
  32953. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32954. };
  32955. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32956. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32957. #endif
  32958. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32959. /********* Start of inlined file: juce_LassoComponent.h *********/
  32960. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32961. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32962. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  32963. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32964. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32965. /** Manages a list of selectable items.
  32966. Use one of these to keep a track of things that the user has highlighted, like
  32967. icons or things in a list.
  32968. The class is templated so that you can use it to hold either a set of pointers
  32969. to objects, or a set of ID numbers or handles, for cases where each item may
  32970. not always have a corresponding object.
  32971. To be informed when items are selected/deselected, register a ChangeListener with
  32972. this object.
  32973. @see SelectableObject
  32974. */
  32975. template <class SelectableItemType>
  32976. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  32977. {
  32978. public:
  32979. /** Creates an empty set. */
  32980. SelectedItemSet()
  32981. {
  32982. }
  32983. /** Creates a set based on an array of items. */
  32984. SelectedItemSet (const Array <SelectableItemType>& items)
  32985. : selectedItems (items)
  32986. {
  32987. }
  32988. /** Creates a copy of another set. */
  32989. SelectedItemSet (const SelectedItemSet& other)
  32990. : selectedItems (other.selectedItems)
  32991. {
  32992. }
  32993. /** Creates a copy of another set. */
  32994. const SelectedItemSet& operator= (const SelectedItemSet& other)
  32995. {
  32996. if (selectedItems != other.selectedItems)
  32997. {
  32998. selectedItems = other.selectedItems;
  32999. changed();
  33000. }
  33001. return *this;
  33002. }
  33003. /** Destructor. */
  33004. ~SelectedItemSet()
  33005. {
  33006. }
  33007. /** Clears any other currently selected items, and selects this item.
  33008. If this item is already the only thing selected, no change notification
  33009. will be sent out.
  33010. @see addToSelection, addToSelectionBasedOnModifiers
  33011. */
  33012. void selectOnly (SelectableItemType item)
  33013. {
  33014. if (isSelected (item))
  33015. {
  33016. for (int i = selectedItems.size(); --i >= 0;)
  33017. {
  33018. if (selectedItems.getUnchecked(i) != item)
  33019. {
  33020. deselect (selectedItems.getUnchecked(i));
  33021. i = jmin (i, selectedItems.size());
  33022. }
  33023. }
  33024. }
  33025. else
  33026. {
  33027. deselectAll();
  33028. changed();
  33029. selectedItems.add (item);
  33030. itemSelected (item);
  33031. }
  33032. }
  33033. /** Selects an item.
  33034. If the item is already selected, no change notification will be sent out.
  33035. @see selectOnly, addToSelectionBasedOnModifiers
  33036. */
  33037. void addToSelection (SelectableItemType item)
  33038. {
  33039. if (! isSelected (item))
  33040. {
  33041. changed();
  33042. selectedItems.add (item);
  33043. itemSelected (item);
  33044. }
  33045. }
  33046. /** Selects or deselects an item.
  33047. This will use the modifier keys to decide whether to deselect other items
  33048. first.
  33049. So if the shift key is held down, the item will be added without deselecting
  33050. anything (same as calling addToSelection() )
  33051. If no modifiers are down, the current selection will be cleared first (same
  33052. as calling selectOnly() )
  33053. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  33054. so it'll be added to the set unless it's already there, in which case it'll be
  33055. deselected.
  33056. If the items that you're selecting can also be dragged, you may need to use the
  33057. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  33058. subtleties of this kind of usage.
  33059. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  33060. */
  33061. void addToSelectionBasedOnModifiers (SelectableItemType item,
  33062. const ModifierKeys& modifiers)
  33063. {
  33064. if (modifiers.isShiftDown())
  33065. {
  33066. addToSelection (item);
  33067. }
  33068. else if (modifiers.isCommandDown())
  33069. {
  33070. if (isSelected (item))
  33071. deselect (item);
  33072. else
  33073. addToSelection (item);
  33074. }
  33075. else
  33076. {
  33077. selectOnly (item);
  33078. }
  33079. }
  33080. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  33081. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  33082. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  33083. makes it easy to handle multiple-selection of sets of objects that can also
  33084. be dragged.
  33085. For example, if you have several items already selected, and you click on
  33086. one of them (without dragging), then you'd expect this to deselect the other, and
  33087. just select the item you clicked on. But if you had clicked on this item and
  33088. dragged it, you'd have expected them all to stay selected.
  33089. When you call this method, you'll need to store the boolean result, because the
  33090. addToSelectionOnMouseUp() method will need to be know this value.
  33091. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  33092. */
  33093. bool addToSelectionOnMouseDown (SelectableItemType item,
  33094. const ModifierKeys& modifiers)
  33095. {
  33096. if (isSelected (item))
  33097. {
  33098. return ! modifiers.isPopupMenu();
  33099. }
  33100. else
  33101. {
  33102. addToSelectionBasedOnModifiers (item, modifiers);
  33103. return false;
  33104. }
  33105. }
  33106. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  33107. Call this during a mouseUp callback, when you have previously called the
  33108. addToSelectionOnMouseDown() method during your mouseDown event.
  33109. See addToSelectionOnMouseDown() for more info
  33110. @param item the item to select (or deselect)
  33111. @param modifiers the modifiers from the mouse-up event
  33112. @param wasItemDragged true if your item was dragged during the mouse click
  33113. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  33114. back from the addToSelectionOnMouseDown() call that you
  33115. should have made during the matching mouseDown event
  33116. */
  33117. void addToSelectionOnMouseUp (SelectableItemType item,
  33118. const ModifierKeys& modifiers,
  33119. const bool wasItemDragged,
  33120. const bool resultOfMouseDownSelectMethod)
  33121. {
  33122. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  33123. addToSelectionBasedOnModifiers (item, modifiers);
  33124. }
  33125. /** Deselects an item. */
  33126. void deselect (SelectableItemType item)
  33127. {
  33128. const int i = selectedItems.indexOf (item);
  33129. if (i >= 0)
  33130. {
  33131. changed();
  33132. itemDeselected (selectedItems.remove (i));
  33133. }
  33134. }
  33135. /** Deselects all items. */
  33136. void deselectAll()
  33137. {
  33138. if (selectedItems.size() > 0)
  33139. {
  33140. changed();
  33141. for (int i = selectedItems.size(); --i >= 0;)
  33142. {
  33143. itemDeselected (selectedItems.remove (i));
  33144. i = jmin (i, selectedItems.size());
  33145. }
  33146. }
  33147. }
  33148. /** Returns the number of currently selected items.
  33149. @see getSelectedItem
  33150. */
  33151. int getNumSelected() const throw()
  33152. {
  33153. return selectedItems.size();
  33154. }
  33155. /** Returns one of the currently selected items.
  33156. Returns 0 if the index is out-of-range.
  33157. @see getNumSelected
  33158. */
  33159. SelectableItemType getSelectedItem (const int index) const throw()
  33160. {
  33161. return selectedItems [index];
  33162. }
  33163. /** True if this item is currently selected. */
  33164. bool isSelected (const SelectableItemType item) const throw()
  33165. {
  33166. return selectedItems.contains (item);
  33167. }
  33168. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  33169. /** Can be overridden to do special handling when an item is selected.
  33170. For example, if the item is an object, you might want to call it and tell
  33171. it that it's being selected.
  33172. */
  33173. virtual void itemSelected (SelectableItemType item) {}
  33174. /** Can be overridden to do special handling when an item is deselected.
  33175. For example, if the item is an object, you might want to call it and tell
  33176. it that it's being deselected.
  33177. */
  33178. virtual void itemDeselected (SelectableItemType item) {}
  33179. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  33180. */
  33181. void changed (const bool synchronous = false)
  33182. {
  33183. if (synchronous)
  33184. sendSynchronousChangeMessage (this);
  33185. else
  33186. sendChangeMessage (this);
  33187. }
  33188. juce_UseDebuggingNewOperator
  33189. private:
  33190. Array <SelectableItemType> selectedItems;
  33191. };
  33192. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33193. /********* End of inlined file: juce_SelectedItemSet.h *********/
  33194. /**
  33195. A class used by the LassoComponent to manage the things that it selects.
  33196. This allows the LassoComponent to find out which items are within the lasso,
  33197. and to change the list of selected items.
  33198. @see LassoComponent, SelectedItemSet
  33199. */
  33200. template <class SelectableItemType>
  33201. class LassoSource
  33202. {
  33203. public:
  33204. /** Destructor. */
  33205. virtual ~LassoSource() {}
  33206. /** Returns the set of items that lie within a given lassoable region.
  33207. Your implementation of this method must find all the relevent items that lie
  33208. within the given rectangle. and add them to the itemsFound array.
  33209. The co-ordinates are relative to the top-left of the lasso component's parent
  33210. component. (i.e. they are the same as the size and position of the lasso
  33211. component itself).
  33212. */
  33213. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  33214. int x, int y, int width, int height) = 0;
  33215. /** Returns the SelectedItemSet that the lasso should update.
  33216. This set will be continuously updated by the LassoComponent as it gets
  33217. dragged around, so make sure that you've got a ChangeListener attached to
  33218. the set so that your UI objects will know when the selection changes and
  33219. be able to update themselves appropriately.
  33220. */
  33221. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  33222. };
  33223. /**
  33224. A component that acts as a rectangular selection region, which you drag with
  33225. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  33226. To use one of these:
  33227. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  33228. component, and call its beginLasso() method, giving it a
  33229. suitable LassoSource object that it can use to find out which items are in
  33230. the active area.
  33231. - Each time your parent component gets a mouseDrag event, call dragLasso()
  33232. to update the lasso's position - it will use its LassoSource to calculate and
  33233. update the current selection.
  33234. - After the drag has finished and you get a mouseUp callback, you should call
  33235. endLasso() to clean up. This will make the lasso component invisible, and you
  33236. can remove it from the parent component, or delete it.
  33237. The class takes into account the modifier keys that are being held down while
  33238. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  33239. be added to the original selection; if ctrl or command is pressed, they will be
  33240. xor'ed with any previously selected items.
  33241. @see LassoSource, SelectedItemSet
  33242. */
  33243. template <class SelectableItemType>
  33244. class LassoComponent : public Component
  33245. {
  33246. public:
  33247. /** Creates a Lasso component.
  33248. The fill colour is used to fill the lasso'ed rectangle, and the outline
  33249. colour is used to draw a line around its edge.
  33250. */
  33251. LassoComponent (const int outlineThickness_ = 1)
  33252. : source (0),
  33253. outlineThickness (outlineThickness_)
  33254. {
  33255. }
  33256. /** Destructor. */
  33257. ~LassoComponent()
  33258. {
  33259. }
  33260. /** Call this in your mouseDown event, to initialise a drag.
  33261. Pass in a suitable LassoSource object which the lasso will use to find
  33262. the items and change the selection.
  33263. After using this method to initialise the lasso, repeatedly call dragLasso()
  33264. in your component's mouseDrag callback.
  33265. @see dragLasso, endLasso, LassoSource
  33266. */
  33267. void beginLasso (const MouseEvent& e,
  33268. LassoSource <SelectableItemType>* const lassoSource)
  33269. {
  33270. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  33271. jassert (lassoSource != 0); // the source can't be null!
  33272. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  33273. source = lassoSource;
  33274. if (lassoSource != 0)
  33275. originalSelection = lassoSource->getLassoSelection().getItemArray();
  33276. setSize (0, 0);
  33277. }
  33278. /** Call this in your mouseDrag event, to update the lasso's position.
  33279. This must be repeatedly calling when the mouse is dragged, after you've
  33280. first initialised the lasso with beginLasso().
  33281. This method takes into account the modifier keys that are being held down, so
  33282. if shift is pressed, then the lassoed items will be added to any that were
  33283. previously selected; if ctrl or command is pressed, then they will be xor'ed
  33284. with previously selected items.
  33285. @see beginLasso, endLasso
  33286. */
  33287. void dragLasso (const MouseEvent& e)
  33288. {
  33289. if (source != 0)
  33290. {
  33291. const int x1 = e.getMouseDownX();
  33292. const int y1 = e.getMouseDownY();
  33293. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  33294. setVisible (true);
  33295. Array <SelectableItemType> itemsInLasso;
  33296. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33297. if (e.mods.isShiftDown())
  33298. {
  33299. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33300. itemsInLasso.addArray (originalSelection);
  33301. }
  33302. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33303. {
  33304. Array <SelectableItemType> originalMinusNew (originalSelection);
  33305. originalMinusNew.removeValuesIn (itemsInLasso);
  33306. itemsInLasso.removeValuesIn (originalSelection);
  33307. itemsInLasso.addArray (originalMinusNew);
  33308. }
  33309. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33310. }
  33311. }
  33312. /** Call this in your mouseUp event, after the lasso has been dragged.
  33313. @see beginLasso, dragLasso
  33314. */
  33315. void endLasso()
  33316. {
  33317. source = 0;
  33318. originalSelection.clear();
  33319. setVisible (false);
  33320. }
  33321. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33322. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33323. methods.
  33324. Note that you can also use the constants from TextEditor::ColourIds to change the
  33325. colour of the text editor that is opened when a label is editable.
  33326. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33327. */
  33328. enum ColourIds
  33329. {
  33330. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  33331. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  33332. };
  33333. /** @internal */
  33334. void paint (Graphics& g)
  33335. {
  33336. g.fillAll (findColour (lassoFillColourId));
  33337. g.setColour (findColour (lassoOutlineColourId));
  33338. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33339. // this suggests that you've left a lasso comp lying around after the
  33340. // mouse drag has finished.. Be careful to call endLasso() when you get a
  33341. // mouse-up event.
  33342. jassert (isMouseButtonDownAnywhere());
  33343. }
  33344. /** @internal */
  33345. bool hitTest (int x, int y) { return false; }
  33346. juce_UseDebuggingNewOperator
  33347. private:
  33348. Array <SelectableItemType> originalSelection;
  33349. LassoSource <SelectableItemType>* source;
  33350. int outlineThickness;
  33351. };
  33352. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33353. /********* End of inlined file: juce_LassoComponent.h *********/
  33354. #endif
  33355. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  33356. #endif
  33357. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  33358. #endif
  33359. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33360. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  33361. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33362. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33363. /**
  33364. Monitors a component for mouse activity, and triggers a callback
  33365. when the mouse hovers in one place for a specified length of time.
  33366. To use a hover-detector, just create one and call its setHoverComponent()
  33367. method to start it watching a component. You can call setHoverComponent (0)
  33368. to make it inactive.
  33369. (Be careful not to delete a component that's being monitored without first
  33370. stopping or deleting the hover detector).
  33371. */
  33372. class JUCE_API MouseHoverDetector
  33373. {
  33374. public:
  33375. /** Creates a hover detector.
  33376. Initially the object is inactive, and you need to tell it which component
  33377. to monitor, using the setHoverComponent() method.
  33378. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  33379. needs to stay still before the mouseHovered() method
  33380. is invoked. You can change this setting later with
  33381. the setHoverTimeMillisecs() method
  33382. */
  33383. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  33384. /** Destructor. */
  33385. virtual ~MouseHoverDetector();
  33386. /** Changes the time for which the mouse has to stay still before it's considered
  33387. to be hovering.
  33388. */
  33389. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  33390. /** Changes the component that's being monitored for hovering.
  33391. Be careful not to delete a component that's being monitored without first
  33392. stopping or deleting the hover detector.
  33393. */
  33394. void setHoverComponent (Component* const newSourceComponent);
  33395. protected:
  33396. /** Called back when the mouse hovers.
  33397. After the mouse has stayed still over the component for the length of time
  33398. specified by setHoverTimeMillisecs(), this method will be invoked.
  33399. When the mouse is first moved after this callback has occurred, the
  33400. mouseMovedAfterHover() method will be called.
  33401. @param mouseX the mouse's X position relative to the component being monitored
  33402. @param mouseY the mouse's Y position relative to the component being monitored
  33403. */
  33404. virtual void mouseHovered (int mouseX,
  33405. int mouseY) = 0;
  33406. /** Called when the mouse is moved away after just having hovered. */
  33407. virtual void mouseMovedAfterHover() = 0;
  33408. private:
  33409. class JUCE_API HoverDetectorInternal : public MouseListener,
  33410. public Timer
  33411. {
  33412. public:
  33413. MouseHoverDetector* owner;
  33414. int lastX, lastY;
  33415. void timerCallback();
  33416. void mouseEnter (const MouseEvent&);
  33417. void mouseExit (const MouseEvent&);
  33418. void mouseDown (const MouseEvent&);
  33419. void mouseUp (const MouseEvent&);
  33420. void mouseMove (const MouseEvent&);
  33421. void mouseWheelMove (const MouseEvent&, float, float);
  33422. } internalTimer;
  33423. friend class HoverDetectorInternal;
  33424. Component* source;
  33425. int hoverTimeMillisecs;
  33426. bool hasJustHovered;
  33427. void hoverTimerCallback();
  33428. void checkJustHoveredCallback();
  33429. };
  33430. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33431. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33432. #endif
  33433. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33434. #endif
  33435. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33436. #endif
  33437. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33438. /********* Start of inlined file: juce_ComponentDragger.h *********/
  33439. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33440. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33441. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33442. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33443. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33444. /**
  33445. A class that imposes restrictions on a Component's size or position.
  33446. This is used by classes such as ResizableCornerComponent,
  33447. ResizableBorderComponent and ResizableWindow.
  33448. The base class can impose some basic size and position limits, but you can
  33449. also subclass this for custom uses.
  33450. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  33451. */
  33452. class JUCE_API ComponentBoundsConstrainer
  33453. {
  33454. public:
  33455. /** When first created, the object will not impose any restrictions on the components. */
  33456. ComponentBoundsConstrainer() throw();
  33457. /** Destructor. */
  33458. virtual ~ComponentBoundsConstrainer();
  33459. /** Imposes a minimum width limit. */
  33460. void setMinimumWidth (const int minimumWidth) throw();
  33461. /** Returns the current minimum width. */
  33462. int getMinimumWidth() const throw() { return minW; }
  33463. /** Imposes a maximum width limit. */
  33464. void setMaximumWidth (const int maximumWidth) throw();
  33465. /** Returns the current maximum width. */
  33466. int getMaximumWidth() const throw() { return maxW; }
  33467. /** Imposes a minimum height limit. */
  33468. void setMinimumHeight (const int minimumHeight) throw();
  33469. /** Returns the current minimum height. */
  33470. int getMinimumHeight() const throw() { return minH; }
  33471. /** Imposes a maximum height limit. */
  33472. void setMaximumHeight (const int maximumHeight) throw();
  33473. /** Returns the current maximum height. */
  33474. int getMaximumHeight() const throw() { return maxH; }
  33475. /** Imposes a minimum width and height limit. */
  33476. void setMinimumSize (const int minimumWidth,
  33477. const int minimumHeight) throw();
  33478. /** Imposes a maximum width and height limit. */
  33479. void setMaximumSize (const int maximumWidth,
  33480. const int maximumHeight) throw();
  33481. /** Set all the maximum and minimum dimensions. */
  33482. void setSizeLimits (const int minimumWidth,
  33483. const int minimumHeight,
  33484. const int maximumWidth,
  33485. const int maximumHeight) throw();
  33486. /** Sets the amount by which the component is allowed to go off-screen.
  33487. The values indicate how many pixels must remain on-screen when dragged off
  33488. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  33489. when the component goes off the top of the screen, its y-position will be
  33490. clipped so that there are always at least 10 pixels on-screen. In other words,
  33491. the lowest y-position it can take would be (10 - the component's height).
  33492. If you pass 0 or less for one of these amounts, the component is allowed
  33493. to move beyond that edge completely, with no restrictions at all.
  33494. If you pass a very large number (i.e. larger that the dimensions of the
  33495. component itself), then the component won't be allowed to overlap that
  33496. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  33497. the component will bump into the left side of the screen and go no further.
  33498. */
  33499. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  33500. const int minimumWhenOffTheLeft,
  33501. const int minimumWhenOffTheBottom,
  33502. const int minimumWhenOffTheRight) throw();
  33503. /** Specifies a width-to-height ratio that the resizer should always maintain.
  33504. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  33505. will always be maintained as this multiple of the height.
  33506. @see setResizeLimits
  33507. */
  33508. void setFixedAspectRatio (const double widthOverHeight) throw();
  33509. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  33510. If no aspect ratio is being enforced, this will return 0.
  33511. */
  33512. double getFixedAspectRatio() const throw();
  33513. /** This callback changes the given co-ordinates to impose whatever the current
  33514. constraints are set to be.
  33515. @param x the x position that should be examined and adjusted
  33516. @param y the y position that should be examined and adjusted
  33517. @param w the width that should be examined and adjusted
  33518. @param h the height that should be examined and adjusted
  33519. @param previousBounds the component's current size
  33520. @param limits the region in which the component can be positioned
  33521. @param isStretchingTop whether the top edge of the component is being resized
  33522. @param isStretchingLeft whether the left edge of the component is being resized
  33523. @param isStretchingBottom whether the bottom edge of the component is being resized
  33524. @param isStretchingRight whether the right edge of the component is being resized
  33525. */
  33526. virtual void checkBounds (int& x, int& y, int& w, int& h,
  33527. const Rectangle& previousBounds,
  33528. const Rectangle& limits,
  33529. const bool isStretchingTop,
  33530. const bool isStretchingLeft,
  33531. const bool isStretchingBottom,
  33532. const bool isStretchingRight);
  33533. /** This callback happens when the resizer is about to start dragging. */
  33534. virtual void resizeStart();
  33535. /** This callback happens when the resizer has finished dragging. */
  33536. virtual void resizeEnd();
  33537. /** Checks the given bounds, and then sets the component to the corrected size. */
  33538. void setBoundsForComponent (Component* const component,
  33539. int x, int y, int w, int h,
  33540. const bool isStretchingTop,
  33541. const bool isStretchingLeft,
  33542. const bool isStretchingBottom,
  33543. const bool isStretchingRight);
  33544. /** Performs a check on the current size of a component, and moves or resizes
  33545. it if it fails the constraints.
  33546. */
  33547. void checkComponentBounds (Component* component);
  33548. /** Called by setBoundsForComponent() to apply a new constrained size to a
  33549. component.
  33550. By default this just calls setBounds(), but it virtual in case it's needed for
  33551. extremely cunning purposes.
  33552. */
  33553. virtual void applyBoundsToComponent (Component* component,
  33554. int x, int y, int w, int h);
  33555. juce_UseDebuggingNewOperator
  33556. private:
  33557. int minW, maxW, minH, maxH;
  33558. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  33559. double aspectRatio;
  33560. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  33561. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  33562. };
  33563. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33564. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33565. /**
  33566. An object to take care of the logic for dragging components around with the mouse.
  33567. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  33568. then in your mouseDrag() callback, call dragComponent().
  33569. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  33570. to limit the component's position and keep it on-screen.
  33571. e.g. @code
  33572. class MyDraggableComp
  33573. {
  33574. ComponentDragger myDragger;
  33575. void mouseDown (const MouseEvent& e)
  33576. {
  33577. myDragger.startDraggingComponent (this, 0);
  33578. }
  33579. void mouseDrag (const MouseEvent& e)
  33580. {
  33581. myDragger.dragComponent (this, e);
  33582. }
  33583. };
  33584. @endcode
  33585. */
  33586. class JUCE_API ComponentDragger
  33587. {
  33588. public:
  33589. /** Creates a ComponentDragger. */
  33590. ComponentDragger();
  33591. /** Destructor. */
  33592. virtual ~ComponentDragger();
  33593. /** Call this from your component's mouseDown() method, to prepare for dragging.
  33594. @param componentToDrag the component that you want to drag
  33595. @param constrainer a constrainer object to use to keep the component
  33596. from going offscreen
  33597. @see dragComponent
  33598. */
  33599. void startDraggingComponent (Component* const componentToDrag,
  33600. ComponentBoundsConstrainer* constrainer);
  33601. /** Call this from your mouseDrag() callback to move the component.
  33602. This will move the component, but will first check the validity of the
  33603. component's new position using the checkPosition() method, which you
  33604. can override if you need to enforce special positioning limits on the
  33605. component.
  33606. @param componentToDrag the component that you want to drag
  33607. @param e the current mouse-drag event
  33608. @see dragComponent
  33609. */
  33610. void dragComponent (Component* const componentToDrag,
  33611. const MouseEvent& e);
  33612. juce_UseDebuggingNewOperator
  33613. private:
  33614. ComponentBoundsConstrainer* constrainer;
  33615. int originalX, originalY;
  33616. };
  33617. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33618. /********* End of inlined file: juce_ComponentDragger.h *********/
  33619. #endif
  33620. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33621. #endif
  33622. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33623. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  33624. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33625. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33626. /**
  33627. A factory object which can create ToolbarItemComponent objects.
  33628. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  33629. that it can create.
  33630. Each type of item is identified by a unique ID, and multiple instances of an
  33631. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  33632. bars).
  33633. @see Toolbar, ToolbarItemComponent, ToolbarButton
  33634. */
  33635. class JUCE_API ToolbarItemFactory
  33636. {
  33637. public:
  33638. ToolbarItemFactory();
  33639. /** Destructor. */
  33640. virtual ~ToolbarItemFactory();
  33641. /** A set of reserved item ID values, used for the built-in item types.
  33642. */
  33643. enum SpecialItemIds
  33644. {
  33645. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  33646. can be placed between sets of items to break them into groups. */
  33647. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  33648. items.*/
  33649. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  33650. either side of it, filling any available space. */
  33651. };
  33652. /** Must return a list of the IDs for all the item types that this factory can create.
  33653. The ids should be added to the array that is passed-in.
  33654. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  33655. and the predefined IDs in the SpecialItemIds enum.
  33656. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  33657. to this list if you want your toolbar to be able to contain those items.
  33658. The list returned here is used by the ToolbarItemPalette class to obtain its list
  33659. of available items, and their order on the palette will reflect the order in which
  33660. they appear on this list.
  33661. @see ToolbarItemPalette
  33662. */
  33663. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  33664. /** Must return the set of items that should be added to a toolbar as its default set.
  33665. This method is used by Toolbar::addDefaultItems() to determine which items to
  33666. create.
  33667. The items that your method adds to the array that is passed-in will be added to the
  33668. toolbar in the same order. Items can appear in the list more than once.
  33669. */
  33670. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  33671. /** Must create an instance of one of the items that the factory lists in its
  33672. getAllToolbarItemIds() method.
  33673. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  33674. method, except for the built-in item types from the SpecialItemIds enum, which
  33675. are created internally by the toolbar code.
  33676. Try not to keep a pointer to the object that is returned, as it will be deleted
  33677. automatically by the toolbar, and remember that multiple instances of the same
  33678. item type are likely to exist at the same time.
  33679. */
  33680. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  33681. };
  33682. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33683. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  33684. #endif
  33685. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33686. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  33687. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33688. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33689. /**
  33690. A component containing a list of toolbar items, which the user can drag onto
  33691. a toolbar to add them.
  33692. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  33693. which automatically shows one of these in a dialog box with lots of extra controls.
  33694. @see Toolbar
  33695. */
  33696. class JUCE_API ToolbarItemPalette : public Component,
  33697. public DragAndDropContainer
  33698. {
  33699. public:
  33700. /** Creates a palette of items for a given factory, with the aim of adding them
  33701. to the specified toolbar.
  33702. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  33703. set of items that are shown in this palette.
  33704. The toolbar and factory must not be deleted while this object exists.
  33705. */
  33706. ToolbarItemPalette (ToolbarItemFactory& factory,
  33707. Toolbar* const toolbar);
  33708. /** Destructor. */
  33709. ~ToolbarItemPalette();
  33710. /** @internal */
  33711. void resized();
  33712. juce_UseDebuggingNewOperator
  33713. private:
  33714. ToolbarItemFactory& factory;
  33715. Toolbar* toolbar;
  33716. Viewport* viewport;
  33717. friend class Toolbar;
  33718. void replaceComponent (ToolbarItemComponent* const comp);
  33719. ToolbarItemPalette (const ToolbarItemPalette&);
  33720. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  33721. };
  33722. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33723. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  33724. #endif
  33725. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33726. /********* Start of inlined file: juce_Slider.h *********/
  33727. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33728. #define __JUCE_SLIDER_JUCEHEADER__
  33729. /********* Start of inlined file: juce_SliderListener.h *********/
  33730. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33731. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33732. class Slider;
  33733. /**
  33734. A class for receiving callbacks from a Slider.
  33735. To be told when a slider's value changes, you can register a SliderListener
  33736. object using Slider::addListener().
  33737. @see Slider::addListener, Slider::removeListener
  33738. */
  33739. class JUCE_API SliderListener
  33740. {
  33741. public:
  33742. /** Destructor. */
  33743. virtual ~SliderListener() {}
  33744. /** Called when the slider's value is changed.
  33745. This may be caused by dragging it, or by typing in its text entry box,
  33746. or by a call to Slider::setValue().
  33747. You can find out the new value using Slider::getValue().
  33748. @see Slider::valueChanged
  33749. */
  33750. virtual void sliderValueChanged (Slider* slider) = 0;
  33751. /** Called when the slider is about to be dragged.
  33752. This is called when a drag begins, then it's followed by multiple calls
  33753. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33754. user lets go.
  33755. @see sliderDragEnded, Slider::startedDragging
  33756. */
  33757. virtual void sliderDragStarted (Slider* slider);
  33758. /** Called after a drag operation has finished.
  33759. @see sliderDragStarted, Slider::stoppedDragging
  33760. */
  33761. virtual void sliderDragEnded (Slider* slider);
  33762. };
  33763. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33764. /********* End of inlined file: juce_SliderListener.h *********/
  33765. /**
  33766. A slider control for changing a value.
  33767. The slider can be horizontal, vertical, or rotary, and can optionally have
  33768. a text-box inside it to show an editable display of the current value.
  33769. To use it, create a Slider object and use the setSliderStyle() method
  33770. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33771. To define the values that it can be set to, see the setRange() and setValue() methods.
  33772. There are also lots of custom tweaks you can do by subclassing and overriding
  33773. some of the virtual methods, such as changing the scaling, changing the format of
  33774. the text display, custom ways of limiting the values, etc.
  33775. You can register SliderListeners with a slider, which will be informed when the value
  33776. changes, or a subclass can override valueChanged() to be informed synchronously.
  33777. @see SliderListener
  33778. */
  33779. class JUCE_API Slider : public Component,
  33780. public SettableTooltipClient,
  33781. private AsyncUpdater,
  33782. private ButtonListener,
  33783. private LabelListener
  33784. {
  33785. public:
  33786. /** Creates a slider.
  33787. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33788. setRange(), etc.
  33789. */
  33790. Slider (const String& componentName);
  33791. /** Destructor. */
  33792. ~Slider();
  33793. /** The types of slider available.
  33794. @see setSliderStyle, setRotaryParameters
  33795. */
  33796. enum SliderStyle
  33797. {
  33798. LinearHorizontal, /**< A traditional horizontal slider. */
  33799. LinearVertical, /**< A traditional vertical slider. */
  33800. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33801. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33802. @see setRotaryParameters */
  33803. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33804. @see setRotaryParameters */
  33805. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33806. @see setRotaryParameters */
  33807. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33808. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33809. @see setMinValue, setMaxValue */
  33810. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33811. @see setMinValue, setMaxValue */
  33812. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33813. value, with the current value being somewhere between them.
  33814. @see setMinValue, setMaxValue */
  33815. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33816. value, with the current value being somewhere between them.
  33817. @see setMinValue, setMaxValue */
  33818. };
  33819. /** Changes the type of slider interface being used.
  33820. @param newStyle the type of interface
  33821. @see setRotaryParameters, setVelocityBasedMode,
  33822. */
  33823. void setSliderStyle (const SliderStyle newStyle);
  33824. /** Returns the slider's current style.
  33825. @see setSliderStyle
  33826. */
  33827. SliderStyle getSliderStyle() const throw() { return style; }
  33828. /** Changes the properties of a rotary slider.
  33829. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33830. the slider's minimum value is represented
  33831. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33832. the slider's maximum value is represented. This must be
  33833. greater than startAngleRadians
  33834. @param stopAtEnd if true, then when the slider is dragged around past the
  33835. minimum or maximum, it'll stop there; if false, it'll wrap
  33836. back to the opposite value
  33837. */
  33838. void setRotaryParameters (const float startAngleRadians,
  33839. const float endAngleRadians,
  33840. const bool stopAtEnd);
  33841. /** Sets the distance the mouse has to move to drag the slider across
  33842. the full extent of its range.
  33843. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33844. relative mouse movements to adjust the slider.
  33845. */
  33846. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33847. /** Changes the way the the mouse is used when dragging the slider.
  33848. If true, this will turn on velocity-sensitive dragging, so that
  33849. the faster the mouse moves, the bigger the movement to the slider. This
  33850. helps when making accurate adjustments if the slider's range is quite large.
  33851. If false, the slider will just try to snap to wherever the mouse is.
  33852. */
  33853. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33854. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33855. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33856. or if you're holding down ctrl.
  33857. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33858. @param threshold the minimum number of pixels that the mouse needs to move for it
  33859. to be treated as a movement
  33860. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33861. the threshold is reached
  33862. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33863. key to toggle velocity-sensitive mode
  33864. */
  33865. void setVelocityModeParameters (const double sensitivity = 1.0,
  33866. const int threshold = 1,
  33867. const double offset = 0.0,
  33868. const bool userCanPressKeyToSwapMode = true) throw();
  33869. /** Sets up a skew factor to alter the way values are distributed.
  33870. You may want to use a range of values on the slider where more accuracy
  33871. is required towards one end of the range, so this will logarithmically
  33872. spread the values across the length of the slider.
  33873. If the factor is < 1.0, the lower end of the range will fill more of the
  33874. slider's length; if the factor is > 1.0, the upper end of the range
  33875. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33876. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33877. method instead.
  33878. @see getSkewFactor, setSkewFactorFromMidPoint
  33879. */
  33880. void setSkewFactor (const double factor) throw();
  33881. /** Sets up a skew factor to alter the way values are distributed.
  33882. This allows you to specify the slider value that should appear in the
  33883. centre of the slider's visible range.
  33884. @see setSkewFactor, getSkewFactor
  33885. */
  33886. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33887. /** Returns the current skew factor.
  33888. See setSkewFactor for more info.
  33889. @see setSkewFactor, setSkewFactorFromMidPoint
  33890. */
  33891. double getSkewFactor() const throw() { return skewFactor; }
  33892. /** Used by setIncDecButtonsMode().
  33893. */
  33894. enum IncDecButtonMode
  33895. {
  33896. incDecButtonsNotDraggable,
  33897. incDecButtonsDraggable_AutoDirection,
  33898. incDecButtonsDraggable_Horizontal,
  33899. incDecButtonsDraggable_Vertical
  33900. };
  33901. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33902. can be dragged on the buttons to drag the values.
  33903. By default this is turned off. When enabled, clicking on the buttons still works
  33904. them as normal, but by holding down the mouse on a button and dragging it a little
  33905. distance, it flips into a mode where the value can be dragged. The drag direction can
  33906. either be set explicitly to be vertical or horizontal, or can be set to
  33907. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33908. are side-by-side or above each other.
  33909. */
  33910. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33911. /** The position of the slider's text-entry box.
  33912. @see setTextBoxStyle
  33913. */
  33914. enum TextEntryBoxPosition
  33915. {
  33916. NoTextBox, /**< Doesn't display a text box. */
  33917. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33918. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33919. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33920. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33921. };
  33922. /** Changes the location and properties of the text-entry box.
  33923. @param newPosition where it should go (or NoTextBox to not have one at all)
  33924. @param isReadOnly if true, it's a read-only display
  33925. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33926. room for the slider as well!
  33927. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33928. room for the slider as well!
  33929. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33930. */
  33931. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33932. const bool isReadOnly,
  33933. const int textEntryBoxWidth,
  33934. const int textEntryBoxHeight);
  33935. /** Returns the status of the text-box.
  33936. @see setTextBoxStyle
  33937. */
  33938. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33939. /** Returns the width used for the text-box.
  33940. @see setTextBoxStyle
  33941. */
  33942. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33943. /** Returns the height used for the text-box.
  33944. @see setTextBoxStyle
  33945. */
  33946. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33947. /** Makes the text-box editable.
  33948. By default this is true, and the user can enter values into the textbox,
  33949. but it can be turned off if that's not suitable.
  33950. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33951. */
  33952. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33953. /** Returns true if the text-box is read-only.
  33954. @see setTextBoxStyle
  33955. */
  33956. bool isTextBoxEditable() const throw() { return editableText; }
  33957. /** If the text-box is editable, this will give it the focus so that the user can
  33958. type directly into it.
  33959. This is basically the effect as the user clicking on it.
  33960. */
  33961. void showTextBox();
  33962. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33963. focus away from it.
  33964. @param discardCurrentEditorContents if true, the slider's value will be left
  33965. unchanged; if false, the current contents of the
  33966. text editor will be used to set the slider position
  33967. before it is hidden.
  33968. */
  33969. void hideTextBox (const bool discardCurrentEditorContents);
  33970. /** Changes the slider's current value.
  33971. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33972. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33973. want to handle it.
  33974. @param newValue the new value to set - this will be restricted by the
  33975. minimum and maximum range, and will be snapped to the
  33976. nearest interval if one has been set
  33977. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33978. any SliderListeners or the valueChanged() method
  33979. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33980. synchronously; if false, it will be asynchronous
  33981. */
  33982. void setValue (double newValue,
  33983. const bool sendUpdateMessage = true,
  33984. const bool sendMessageSynchronously = false);
  33985. /** Returns the slider's current value. */
  33986. double getValue() const throw();
  33987. /** Sets the limits that the slider's value can take.
  33988. @param newMinimum the lowest value allowed
  33989. @param newMaximum the highest value allowed
  33990. @param newInterval the steps in which the value is allowed to increase - if this
  33991. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33992. */
  33993. void setRange (const double newMinimum,
  33994. const double newMaximum,
  33995. const double newInterval = 0);
  33996. /** Returns the current maximum value.
  33997. @see setRange
  33998. */
  33999. double getMaximum() const throw() { return maximum; }
  34000. /** Returns the current minimum value.
  34001. @see setRange
  34002. */
  34003. double getMinimum() const throw() { return minimum; }
  34004. /** Returns the current step-size for values.
  34005. @see setRange
  34006. */
  34007. double getInterval() const throw() { return interval; }
  34008. /** For a slider with two or three thumbs, this returns the lower of its values.
  34009. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34010. A slider with three values also uses the normal getValue() and setValue() methods to
  34011. control the middle value.
  34012. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34013. */
  34014. double getMinValue() const throw();
  34015. /** For a slider with two or three thumbs, this sets the lower of its values.
  34016. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34017. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34018. want to handle it.
  34019. @param newValue the new value to set - this will be restricted by the
  34020. minimum and maximum range, and will be snapped to the nearest
  34021. interval if one has been set.
  34022. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34023. any SliderListeners or the valueChanged() method
  34024. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34025. synchronously; if false, it will be asynchronous
  34026. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34027. max value (in a two-value slider) or the mid value (in a three-value
  34028. slider). If false, then if this value goes beyond those values,
  34029. it will push them along with it.
  34030. @see getMinValue, setMaxValue, setValue
  34031. */
  34032. void setMinValue (double newValue,
  34033. const bool sendUpdateMessage = true,
  34034. const bool sendMessageSynchronously = false,
  34035. const bool allowNudgingOfOtherValues = false);
  34036. /** For a slider with two or three thumbs, this returns the higher of its values.
  34037. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34038. A slider with three values also uses the normal getValue() and setValue() methods to
  34039. control the middle value.
  34040. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34041. */
  34042. double getMaxValue() const throw();
  34043. /** For a slider with two or three thumbs, this sets the lower of its values.
  34044. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34045. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34046. want to handle it.
  34047. @param newValue the new value to set - this will be restricted by the
  34048. minimum and maximum range, and will be snapped to the nearest
  34049. interval if one has been set.
  34050. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34051. any SliderListeners or the valueChanged() method
  34052. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34053. synchronously; if false, it will be asynchronous
  34054. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34055. min value (in a two-value slider) or the mid value (in a three-value
  34056. slider). If false, then if this value goes beyond those values,
  34057. it will push them along with it.
  34058. @see getMaxValue, setMinValue, setValue
  34059. */
  34060. void setMaxValue (double newValue,
  34061. const bool sendUpdateMessage = true,
  34062. const bool sendMessageSynchronously = false,
  34063. const bool allowNudgingOfOtherValues = false);
  34064. /** Adds a listener to be called when this slider's value changes. */
  34065. void addListener (SliderListener* const listener) throw();
  34066. /** Removes a previously-registered listener. */
  34067. void removeListener (SliderListener* const listener) throw();
  34068. /** This lets you choose whether double-clicking moves the slider to a given position.
  34069. By default this is turned off, but it's handy if you want a double-click to act
  34070. as a quick way of resetting a slider. Just pass in the value you want it to
  34071. go to when double-clicked.
  34072. @see getDoubleClickReturnValue
  34073. */
  34074. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34075. const double valueToSetOnDoubleClick) throw();
  34076. /** Returns the values last set by setDoubleClickReturnValue() method.
  34077. Sets isEnabled to true if double-click is enabled, and returns the value
  34078. that was set.
  34079. @see setDoubleClickReturnValue
  34080. */
  34081. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  34082. /** Tells the slider whether to keep sending change messages while the user
  34083. is dragging the slider.
  34084. If set to true, a change message will only be sent when the user has
  34085. dragged the slider and let go. If set to false (the default), then messages
  34086. will be continuously sent as they drag it while the mouse button is still
  34087. held down.
  34088. */
  34089. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  34090. /** This lets you change whether the slider thumb jumps to the mouse position
  34091. when you click.
  34092. By default, this is true. If it's false, then the slider moves with relative
  34093. motion when you drag it.
  34094. This only applies to linear bars, and won't affect two- or three- value
  34095. sliders.
  34096. */
  34097. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  34098. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34099. slider is being dragged.
  34100. This can be handy if your slider doesn't have a text-box, so that users can
  34101. see the value just when they're changing it.
  34102. If you pass a component as the parentComponentToUse parameter, the pop-up
  34103. bubble will be added as a child of that component when it's needed. If you
  34104. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34105. transparent window, so if you're using an OS that can't do transparent windows
  34106. you'll have to add it to a parent component instead).
  34107. */
  34108. void setPopupDisplayEnabled (const bool isEnabled,
  34109. Component* const parentComponentToUse) throw();
  34110. /** If this is set to true, then right-clicking on the slider will pop-up
  34111. a menu to let the user change the way it works.
  34112. By default this is turned off, but when turned on, the menu will include
  34113. things like velocity sensitivity, and for rotary sliders, whether they
  34114. use a linear or rotary mouse-drag to move them.
  34115. */
  34116. void setPopupMenuEnabled (const bool menuEnabled) throw();
  34117. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34118. By default it's enabled.
  34119. */
  34120. void setScrollWheelEnabled (const bool enabled) throw();
  34121. /** Returns a number to indicate which thumb is currently being dragged by the
  34122. mouse.
  34123. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34124. the maximum-value thumb, or -1 if none is currently down.
  34125. */
  34126. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  34127. /** Callback to indicate that the user is about to start dragging the slider.
  34128. @see SliderListener::sliderDragStarted
  34129. */
  34130. virtual void startedDragging();
  34131. /** Callback to indicate that the user has just stopped dragging the slider.
  34132. @see SliderListener::sliderDragEnded
  34133. */
  34134. virtual void stoppedDragging();
  34135. /** Callback to indicate that the user has just moved the slider.
  34136. @see SliderListener::sliderValueChanged
  34137. */
  34138. virtual void valueChanged();
  34139. /** Callback to indicate that the user has just moved the slider.
  34140. Note - the valueChanged() method has changed its format and now no longer has
  34141. any parameters. Update your code to use the new version.
  34142. This version has been left here with an int as its return value to cause
  34143. a syntax error if you've got existing code that uses the old version.
  34144. */
  34145. virtual int valueChanged (double) { jassertfalse; return 0; }
  34146. /** Subclasses can override this to convert a text string to a value.
  34147. When the user enters something into the text-entry box, this method is
  34148. called to convert it to a value.
  34149. The default routine just tries to convert it to a double.
  34150. @see getTextFromValue
  34151. */
  34152. virtual double getValueFromText (const String& text);
  34153. /** Turns the slider's current value into a text string.
  34154. Subclasses can override this to customise the formatting of the text-entry box.
  34155. The default implementation just turns the value into a string, using
  34156. a number of decimal places based on the range interval. If a suffix string
  34157. has been set using setTextValueSuffix(), this will be appended to the text.
  34158. @see getValueFromText
  34159. */
  34160. virtual const String getTextFromValue (double value);
  34161. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34162. a string.
  34163. This is used by the default implementation of getTextFromValue(), and is just
  34164. appended to the numeric value. For more advanced formatting, you can override
  34165. getTextFromValue() and do something else.
  34166. */
  34167. void setTextValueSuffix (const String& suffix);
  34168. /** Allows a user-defined mapping of distance along the slider to its value.
  34169. The default implementation for this performs the skewing operation that
  34170. can be set up in the setSkewFactor() method. Override it if you need
  34171. some kind of custom mapping instead, but make sure you also implement the
  34172. inverse function in valueToProportionOfLength().
  34173. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34174. @returns the slider value that is represented by this position
  34175. @see valueToProportionOfLength
  34176. */
  34177. virtual double proportionOfLengthToValue (double proportion);
  34178. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34179. The default implementation for this performs the skewing operation that
  34180. can be set up in the setSkewFactor() method. Override it if you need
  34181. some kind of custom mapping instead, but make sure you also implement the
  34182. inverse function in proportionOfLengthToValue().
  34183. @param value a valid slider value, between the range of values specified in
  34184. setRange()
  34185. @returns a value 0 to 1.0 indicating the distance along the slider that
  34186. represents this value
  34187. @see proportionOfLengthToValue
  34188. */
  34189. virtual double valueToProportionOfLength (double value);
  34190. /** Returns the X or Y coordinate of a value along the slider's length.
  34191. If the slider is horizontal, this will be the X coordinate of the given
  34192. value, relative to the left of the slider. If it's vertical, then this will
  34193. be the Y coordinate, relative to the top of the slider.
  34194. If the slider is rotary, this will throw an assertion and return 0. If the
  34195. value is out-of-range, it will be constrained to the length of the slider.
  34196. */
  34197. float getPositionOfValue (const double value);
  34198. /** This can be overridden to allow the slider to snap to user-definable values.
  34199. If overridden, it will be called when the user tries to move the slider to
  34200. a given position, and allows a subclass to sanity-check this value, possibly
  34201. returning a different value to use instead.
  34202. @param attemptedValue the value the user is trying to enter
  34203. @param userIsDragging true if the user is dragging with the mouse; false if
  34204. they are entering the value using the text box
  34205. @returns the value to use instead
  34206. */
  34207. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  34208. /** This can be called to force the text box to update its contents.
  34209. (Not normally needed, as this is done automatically).
  34210. */
  34211. void updateText();
  34212. /** True if the slider moves horizontally. */
  34213. bool isHorizontal() const throw();
  34214. /** True if the slider moves vertically. */
  34215. bool isVertical() const throw();
  34216. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34217. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34218. methods.
  34219. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34220. */
  34221. enum ColourIds
  34222. {
  34223. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34224. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34225. and feel class how this is used. */
  34226. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34227. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34228. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34229. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34230. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34231. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34232. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34233. };
  34234. juce_UseDebuggingNewOperator
  34235. protected:
  34236. /** @internal */
  34237. void labelTextChanged (Label*);
  34238. /** @internal */
  34239. void paint (Graphics& g);
  34240. /** @internal */
  34241. void resized();
  34242. /** @internal */
  34243. void mouseDown (const MouseEvent& e);
  34244. /** @internal */
  34245. void mouseUp (const MouseEvent& e);
  34246. /** @internal */
  34247. void mouseDrag (const MouseEvent& e);
  34248. /** @internal */
  34249. void mouseDoubleClick (const MouseEvent& e);
  34250. /** @internal */
  34251. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34252. /** @internal */
  34253. void modifierKeysChanged (const ModifierKeys& modifiers);
  34254. /** @internal */
  34255. void buttonClicked (Button* button);
  34256. /** @internal */
  34257. void lookAndFeelChanged();
  34258. /** @internal */
  34259. void enablementChanged();
  34260. /** @internal */
  34261. void focusOfChildComponentChanged (FocusChangeType cause);
  34262. /** @internal */
  34263. void handleAsyncUpdate();
  34264. /** @internal */
  34265. void colourChanged();
  34266. private:
  34267. SortedSet <void*> listeners;
  34268. double currentValue, valueMin, valueMax;
  34269. double minimum, maximum, interval, doubleClickReturnValue;
  34270. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34271. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34272. int velocityModeThreshold;
  34273. float rotaryStart, rotaryEnd;
  34274. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34275. int mouseDragStartX, mouseDragStartY;
  34276. int sliderRegionStart, sliderRegionSize;
  34277. int sliderBeingDragged;
  34278. int pixelsForFullDragExtent;
  34279. Rectangle sliderRect;
  34280. String textSuffix;
  34281. SliderStyle style;
  34282. TextEntryBoxPosition textBoxPos;
  34283. int textBoxWidth, textBoxHeight;
  34284. IncDecButtonMode incDecButtonMode;
  34285. bool editableText : 1, doubleClickToValue : 1;
  34286. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34287. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34288. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34289. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34290. Font font;
  34291. Label* valueBox;
  34292. Button* incButton;
  34293. Button* decButton;
  34294. Component* popupDisplay;
  34295. Component* parentForPopupDisplay;
  34296. float getLinearSliderPos (const double value);
  34297. void restoreMouseIfHidden();
  34298. void sendDragStart();
  34299. void sendDragEnd();
  34300. double constrainedValue (double value) const throw();
  34301. void triggerChangeMessage (const bool synchronous);
  34302. bool incDecDragDirectionIsHorizontal() const throw();
  34303. Slider (const Slider&);
  34304. const Slider& operator= (const Slider&);
  34305. };
  34306. #endif // __JUCE_SLIDER_JUCEHEADER__
  34307. /********* End of inlined file: juce_Slider.h *********/
  34308. #endif
  34309. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34310. #endif
  34311. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34312. #endif
  34313. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34314. #endif
  34315. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34316. #endif
  34317. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34318. /********* Start of inlined file: juce_ProgressBar.h *********/
  34319. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34320. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34321. /**
  34322. A progress bar component.
  34323. To use this, just create one and make it visible. It'll run its own timer
  34324. to keep an eye on a variable that you give it, and will automatically
  34325. redraw itself when the variable changes.
  34326. For an easy way of running a background task with a dialog box showing its
  34327. progress, see the ThreadWithProgressWindow class.
  34328. @see ThreadWithProgressWindow
  34329. */
  34330. class JUCE_API ProgressBar : public Component,
  34331. public SettableTooltipClient,
  34332. private Timer
  34333. {
  34334. public:
  34335. /** Creates a ProgressBar.
  34336. @param progress pass in a reference to a double that you're going to
  34337. update with your task's progress. The ProgressBar will
  34338. monitor the value of this variable and will redraw itself
  34339. when the value changes. The range is from 0 to 1.0. Obviously
  34340. you'd better be careful not to delete this variable while the
  34341. ProgressBar still exists!
  34342. */
  34343. ProgressBar (double& progress);
  34344. /** Destructor. */
  34345. ~ProgressBar();
  34346. /** Turns the percentage display on or off.
  34347. By default this is on, and the progress bar will display a text string showing
  34348. its current percentage.
  34349. */
  34350. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34351. /** Gives the progress bar a string to display inside it.
  34352. If you call this, it will turn off the percentage display.
  34353. @see setPercentageDisplay
  34354. */
  34355. void setTextToDisplay (const String& text);
  34356. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34357. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34358. methods.
  34359. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34360. */
  34361. enum ColourIds
  34362. {
  34363. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34364. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34365. classes will probably use variations on this colour. */
  34366. };
  34367. juce_UseDebuggingNewOperator
  34368. protected:
  34369. /** @internal */
  34370. void paint (Graphics& g);
  34371. /** @internal */
  34372. void lookAndFeelChanged();
  34373. /** @internal */
  34374. void visibilityChanged();
  34375. /** @internal */
  34376. void colourChanged();
  34377. private:
  34378. double& progress;
  34379. double currentValue;
  34380. bool displayPercentage;
  34381. String displayedMessage, currentMessage;
  34382. uint32 lastCallbackTime;
  34383. void timerCallback();
  34384. ProgressBar (const ProgressBar&);
  34385. const ProgressBar& operator= (const ProgressBar&);
  34386. };
  34387. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34388. /********* End of inlined file: juce_ProgressBar.h *********/
  34389. #endif
  34390. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34391. #endif
  34392. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34393. /********* Start of inlined file: juce_TableListBox.h *********/
  34394. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34395. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34396. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  34397. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34398. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34399. class TableHeaderComponent;
  34400. /**
  34401. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34402. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34403. and TableHeaderComponent::removeListener().
  34404. @see TableHeaderComponent
  34405. */
  34406. class JUCE_API TableHeaderListener
  34407. {
  34408. public:
  34409. TableHeaderListener() {}
  34410. /** Destructor. */
  34411. virtual ~TableHeaderListener() {}
  34412. /** This is called when some of the table's columns are added, removed, hidden,
  34413. or rearranged.
  34414. */
  34415. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34416. /** This is called when one or more of the table's columns are resized.
  34417. */
  34418. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34419. /** This is called when the column by which the table should be sorted is changed.
  34420. */
  34421. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34422. /** This is called when the user begins or ends dragging one of the columns around.
  34423. When the user starts dragging a column, this is called with the ID of that
  34424. column. When they finish dragging, it is called again with 0 as the ID.
  34425. */
  34426. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34427. int columnIdNowBeingDragged);
  34428. };
  34429. /**
  34430. A component that displays a strip of column headings for a table, and allows these
  34431. to be resized, dragged around, etc.
  34432. This is just the component that goes at the top of a table. You can use it
  34433. directly for custom components, or to create a simple table, use the
  34434. TableListBox class.
  34435. To use one of these, create it and use addColumn() to add all the columns that you need.
  34436. Each column must be given a unique ID number that's used to refer to it.
  34437. @see TableListBox, TableHeaderListener
  34438. */
  34439. class JUCE_API TableHeaderComponent : public Component,
  34440. private AsyncUpdater
  34441. {
  34442. public:
  34443. /** Creates an empty table header.
  34444. */
  34445. TableHeaderComponent();
  34446. /** Destructor. */
  34447. ~TableHeaderComponent();
  34448. /** A combination of these flags are passed into the addColumn() method to specify
  34449. the properties of a column.
  34450. */
  34451. enum ColumnPropertyFlags
  34452. {
  34453. 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. */
  34454. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34455. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34456. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34457. 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. */
  34458. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34459. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34460. /** This set of default flags is used as the default parameter value in addColumn(). */
  34461. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34462. /** A quick way of combining flags for a column that's not resizable. */
  34463. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34464. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34465. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34466. /** A quick way of combining flags for a column that's not sortable. */
  34467. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34468. };
  34469. /** Adds a column to the table.
  34470. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34471. registered listeners.
  34472. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34473. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34474. a unique ID. This is used to identify the column later on, after the user may have
  34475. changed the order that they appear in
  34476. @param width the initial width of the column, in pixels
  34477. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34478. if the 'resizable' flag is specified for this column
  34479. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34480. if the 'resizable' flag is specified for this column
  34481. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34482. properties of this column
  34483. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34484. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34485. all columns, not just the index amongst those that are currently visible
  34486. */
  34487. void addColumn (const String& columnName,
  34488. const int columnId,
  34489. const int width,
  34490. const int minimumWidth = 30,
  34491. const int maximumWidth = -1,
  34492. const int propertyFlags = defaultFlags,
  34493. const int insertIndex = -1);
  34494. /** Removes a column with the given ID.
  34495. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34496. registered listeners.
  34497. */
  34498. void removeColumn (const int columnIdToRemove);
  34499. /** Deletes all columns from the table.
  34500. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34501. registered listeners.
  34502. */
  34503. void removeAllColumns();
  34504. /** Returns the number of columns in the table.
  34505. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34506. return the total number of columns, including hidden ones.
  34507. @see isColumnVisible
  34508. */
  34509. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  34510. /** Returns the name for a column.
  34511. @see setColumnName
  34512. */
  34513. const String getColumnName (const int columnId) const throw();
  34514. /** Changes the name of a column. */
  34515. void setColumnName (const int columnId, const String& newName);
  34516. /** Moves a column to a different index in the table.
  34517. @param columnId the column to move
  34518. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34519. */
  34520. void moveColumn (const int columnId, int newVisibleIndex);
  34521. /** Changes the width of a column.
  34522. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34523. */
  34524. void setColumnWidth (const int columnId, const int newWidth);
  34525. /** Shows or hides a column.
  34526. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34527. @see isColumnVisible
  34528. */
  34529. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  34530. /** Returns true if this column is currently visible.
  34531. @see setColumnVisible
  34532. */
  34533. bool isColumnVisible (const int columnId) const;
  34534. /** Changes the column which is the sort column.
  34535. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34536. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34537. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34538. @see getSortColumnId, isSortedForwards, reSortTable
  34539. */
  34540. void setSortColumnId (const int columnId, const bool sortForwards);
  34541. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34542. @see setSortColumnId, isSortedForwards
  34543. */
  34544. int getSortColumnId() const throw();
  34545. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34546. @see setSortColumnId
  34547. */
  34548. bool isSortedForwards() const throw();
  34549. /** Triggers a re-sort of the table according to the current sort-column.
  34550. If you modifiy the table's contents, you can call this to signal that the table needs
  34551. to be re-sorted.
  34552. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34553. tableSortOrderChanged() method of any listeners).
  34554. */
  34555. void reSortTable();
  34556. /** Returns the total width of all the visible columns in the table.
  34557. */
  34558. int getTotalWidth() const throw();
  34559. /** Returns the index of a given column.
  34560. If there's no such column ID, this will return -1.
  34561. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34562. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34563. */
  34564. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  34565. /** Returns the ID of the column at a given index.
  34566. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34567. otherwise it'll count it amongst all the columns, including any hidden ones.
  34568. If the index is out-of-range, it'll return 0.
  34569. */
  34570. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  34571. /** Returns the rectangle containing of one of the columns.
  34572. The index is an index from 0 to the number of columns that are currently visible (hidden
  34573. ones are not counted). It returns a rectangle showing the position of the column relative
  34574. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34575. */
  34576. const Rectangle getColumnPosition (const int index) const throw();
  34577. /** Finds the column ID at a given x-position in the component.
  34578. If there is a column at this point this returns its ID, or if not, it will return 0.
  34579. */
  34580. int getColumnIdAtX (const int xToFind) const throw();
  34581. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34582. entire width of the component.
  34583. By default this is disabled. Turning it on also means that when resizing a column, those
  34584. on the right will be squashed to fit.
  34585. */
  34586. void setStretchToFitActive (const bool shouldStretchToFit);
  34587. /** Returns true if stretch-to-fit has been enabled.
  34588. @see setStretchToFitActive
  34589. */
  34590. bool isStretchToFitActive() const throw();
  34591. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34592. specified width, keeping their relative proportions the same.
  34593. If the minimum widths of the columns are too wide to fit into this space, it may
  34594. actually end up wider.
  34595. */
  34596. void resizeAllColumnsToFit (int targetTotalWidth);
  34597. /** Enables or disables the pop-up menu.
  34598. The default menu allows the user to show or hide columns. You can add custom
  34599. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34600. By default the menu is enabled.
  34601. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34602. */
  34603. void setPopupMenuActive (const bool hasMenu);
  34604. /** Returns true if the pop-up menu is enabled.
  34605. @see setPopupMenuActive
  34606. */
  34607. bool isPopupMenuActive() const throw();
  34608. /** Returns a string that encapsulates the table's current layout.
  34609. This can be restored later using restoreFromString(). It saves the order of
  34610. the columns, the currently-sorted column, and the widths.
  34611. @see restoreFromString
  34612. */
  34613. const String toString() const;
  34614. /** Restores the state of the table, based on a string previously created with
  34615. toString().
  34616. @see toString
  34617. */
  34618. void restoreFromString (const String& storedVersion);
  34619. /** Adds a listener to be informed about things that happen to the header. */
  34620. void addListener (TableHeaderListener* const newListener) throw();
  34621. /** Removes a previously-registered listener. */
  34622. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34623. /** This can be overridden to handle a mouse-click on one of the column headers.
  34624. The default implementation will use this click to call getSortColumnId() and
  34625. change the sort order.
  34626. */
  34627. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34628. /** This can be overridden to add custom items to the pop-up menu.
  34629. If you override this, you should call the superclass's method to add its
  34630. column show/hide items, if you want them on the menu as well.
  34631. Then to handle the result, override reactToMenuItem().
  34632. @see reactToMenuItem
  34633. */
  34634. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  34635. /** Override this to handle any custom items that you have added to the
  34636. pop-up menu with an addMenuItems() override.
  34637. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34638. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34639. handle the items that it had added.
  34640. @see addMenuItems
  34641. */
  34642. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  34643. /** @internal */
  34644. void paint (Graphics& g);
  34645. /** @internal */
  34646. void resized();
  34647. /** @internal */
  34648. void mouseMove (const MouseEvent&);
  34649. /** @internal */
  34650. void mouseEnter (const MouseEvent&);
  34651. /** @internal */
  34652. void mouseExit (const MouseEvent&);
  34653. /** @internal */
  34654. void mouseDown (const MouseEvent&);
  34655. /** @internal */
  34656. void mouseDrag (const MouseEvent&);
  34657. /** @internal */
  34658. void mouseUp (const MouseEvent&);
  34659. /** @internal */
  34660. const MouseCursor getMouseCursor();
  34661. /** Can be overridden for more control over the pop-up menu behaviour. */
  34662. virtual void showColumnChooserMenu (const int columnIdClicked);
  34663. juce_UseDebuggingNewOperator
  34664. private:
  34665. struct ColumnInfo
  34666. {
  34667. String name;
  34668. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34669. double lastDeliberateWidth;
  34670. bool isVisible() const throw();
  34671. };
  34672. OwnedArray <ColumnInfo> columns;
  34673. Array <TableHeaderListener*> listeners;
  34674. Component* dragOverlayComp;
  34675. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34676. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34677. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34678. ColumnInfo* getInfoForId (const int columnId) const throw();
  34679. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  34680. void sendColumnsChanged();
  34681. void handleAsyncUpdate();
  34682. void beginDrag (const MouseEvent&);
  34683. void endDrag (const int finalIndex);
  34684. int getResizeDraggerAt (const int mouseX) const throw();
  34685. void updateColumnUnderMouse (int x, int y);
  34686. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34687. TableHeaderComponent (const TableHeaderComponent&);
  34688. const TableHeaderComponent operator= (const TableHeaderComponent&);
  34689. };
  34690. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34691. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  34692. /**
  34693. One of these is used by a TableListBox as the data model for the table's contents.
  34694. The virtual methods that you override in this class take care of drawing the
  34695. table cells, and reacting to events.
  34696. @see TableListBox
  34697. */
  34698. class JUCE_API TableListBoxModel
  34699. {
  34700. public:
  34701. TableListBoxModel() {}
  34702. /** Destructor. */
  34703. virtual ~TableListBoxModel() {}
  34704. /** This must return the number of rows currently in the table.
  34705. If the number of rows changes, you must call TableListBox::updateContent() to
  34706. cause it to refresh the list.
  34707. */
  34708. virtual int getNumRows() = 0;
  34709. /** This must draw the background behind one of the rows in the table.
  34710. The graphics context has its origin at the row's top-left, and your method
  34711. should fill the area specified by the width and height parameters.
  34712. */
  34713. virtual void paintRowBackground (Graphics& g,
  34714. int rowNumber,
  34715. int width, int height,
  34716. bool rowIsSelected) = 0;
  34717. /** This must draw one of the cells.
  34718. The graphics context's origin will already be set to the top-left of the cell,
  34719. whose size is specified by (width, height).
  34720. */
  34721. virtual void paintCell (Graphics& g,
  34722. int rowNumber,
  34723. int columnId,
  34724. int width, int height,
  34725. bool rowIsSelected) = 0;
  34726. /** This is used to create or update a custom component to go in a cell.
  34727. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34728. and handle mouse clicks with cellClicked().
  34729. This method will be called whenever a custom component might need to be updated - e.g.
  34730. when the table is changed, or TableListBox::updateContent() is called.
  34731. If you don't need a custom component for the specified cell, then return 0.
  34732. If you do want a custom component, and the existingComponentToUpdate is null, then
  34733. this method must create a new component suitable for the cell, and return it.
  34734. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34735. by this method. In this case, the method must either update it to make sure it's correctly representing
  34736. the given cell (which may be different from the one that the component was created for), or it can
  34737. delete this component and return a new one.
  34738. */
  34739. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34740. Component* existingComponentToUpdate);
  34741. /** This callback is made when the user clicks on one of the cells in the table.
  34742. The mouse event's coordinates will be relative to the entire table row.
  34743. @see cellDoubleClicked, backgroundClicked
  34744. */
  34745. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34746. /** This callback is made when the user clicks on one of the cells in the table.
  34747. The mouse event's coordinates will be relative to the entire table row.
  34748. @see cellClicked, backgroundClicked
  34749. */
  34750. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34751. /** This can be overridden to react to the user double-clicking on a part of the list where
  34752. there are no rows.
  34753. @see cellClicked
  34754. */
  34755. virtual void backgroundClicked();
  34756. /** This callback is made when the table's sort order is changed.
  34757. This could be because the user has clicked a column header, or because the
  34758. TableHeaderComponent::setSortColumnId() method was called.
  34759. If you implement this, your method should re-sort the table using the given
  34760. column as the key.
  34761. */
  34762. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34763. /** Returns the best width for one of the columns.
  34764. If you implement this method, you should measure the width of all the items
  34765. in this column, and return the best size.
  34766. Returning 0 means that the column shouldn't be changed.
  34767. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34768. */
  34769. virtual int getColumnAutoSizeWidth (int columnId);
  34770. /** Override this to be informed when rows are selected or deselected.
  34771. @see ListBox::selectedRowsChanged()
  34772. */
  34773. virtual void selectedRowsChanged (int lastRowSelected);
  34774. /** Override this to be informed when the delete key is pressed.
  34775. @see ListBox::deleteKeyPressed()
  34776. */
  34777. virtual void deleteKeyPressed (int lastRowSelected);
  34778. /** Override this to be informed when the return key is pressed.
  34779. @see ListBox::returnKeyPressed()
  34780. */
  34781. virtual void returnKeyPressed (int lastRowSelected);
  34782. /** Override this to be informed when the list is scrolled.
  34783. This might be caused by the user moving the scrollbar, or by programmatic changes
  34784. to the list position.
  34785. */
  34786. virtual void listWasScrolled();
  34787. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34788. If this returns a non-empty name then when the user drags a row, the table will try to
  34789. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34790. drag-and-drop operation, using this string as the source description, and the listbox
  34791. itself as the source component.
  34792. @see DragAndDropContainer::startDragging
  34793. */
  34794. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34795. };
  34796. /**
  34797. A table of cells, using a TableHeaderComponent as its header.
  34798. This component makes it easy to create a table by providing a TableListBoxModel as
  34799. the data source.
  34800. @see TableListBoxModel, TableHeaderComponent
  34801. */
  34802. class JUCE_API TableListBox : public ListBox,
  34803. private ListBoxModel,
  34804. private TableHeaderListener
  34805. {
  34806. public:
  34807. /** Creates a TableListBox.
  34808. The model pointer passed-in can be null, in which case you can set it later
  34809. with setModel().
  34810. */
  34811. TableListBox (const String& componentName,
  34812. TableListBoxModel* const model);
  34813. /** Destructor. */
  34814. ~TableListBox();
  34815. /** Changes the TableListBoxModel that is being used for this table.
  34816. */
  34817. void setModel (TableListBoxModel* const newModel);
  34818. /** Returns the model currently in use. */
  34819. TableListBoxModel* getModel() const throw() { return model; }
  34820. /** Returns the header component being used in this table. */
  34821. TableHeaderComponent* getHeader() const throw() { return header; }
  34822. /** Changes the height of the table header component.
  34823. @see getHeaderHeight
  34824. */
  34825. void setHeaderHeight (const int newHeight);
  34826. /** Returns the height of the table header.
  34827. @see setHeaderHeight
  34828. */
  34829. int getHeaderHeight() const throw();
  34830. /** Resizes a column to fit its contents.
  34831. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34832. and applies that to the column.
  34833. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34834. */
  34835. void autoSizeColumn (const int columnId);
  34836. /** Calls autoSizeColumn() for all columns in the table. */
  34837. void autoSizeAllColumns();
  34838. /** Enables or disables the auto size options on the popup menu.
  34839. By default, these are enabled.
  34840. */
  34841. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34842. /** True if the auto-size options should be shown on the menu.
  34843. @see setAutoSizeMenuOptionsShown
  34844. */
  34845. bool isAutoSizeMenuOptionShown() const throw();
  34846. /** Returns the position of one of the cells in the table.
  34847. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34848. the table component's top-left. The row number isn't checked to see if it's
  34849. in-range, but the column ID must exist or this will return an empty rectangle.
  34850. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34851. top-left of the table's top-left cell.
  34852. */
  34853. const Rectangle getCellPosition (const int columnId,
  34854. const int rowNumber,
  34855. const bool relativeToComponentTopLeft) const;
  34856. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34857. @see ListBox::scrollToEnsureRowIsOnscreen
  34858. */
  34859. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34860. /** @internal */
  34861. int getNumRows();
  34862. /** @internal */
  34863. void paintListBoxItem (int, Graphics&, int, int, bool);
  34864. /** @internal */
  34865. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34866. /** @internal */
  34867. void selectedRowsChanged (int lastRowSelected);
  34868. /** @internal */
  34869. void deleteKeyPressed (int currentSelectedRow);
  34870. /** @internal */
  34871. void returnKeyPressed (int currentSelectedRow);
  34872. /** @internal */
  34873. void backgroundClicked();
  34874. /** @internal */
  34875. void listWasScrolled();
  34876. /** @internal */
  34877. void tableColumnsChanged (TableHeaderComponent*);
  34878. /** @internal */
  34879. void tableColumnsResized (TableHeaderComponent*);
  34880. /** @internal */
  34881. void tableSortOrderChanged (TableHeaderComponent*);
  34882. /** @internal */
  34883. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34884. /** @internal */
  34885. void resized();
  34886. juce_UseDebuggingNewOperator
  34887. private:
  34888. TableHeaderComponent* header;
  34889. TableListBoxModel* model;
  34890. int columnIdNowBeingDragged;
  34891. bool autoSizeOptionsShown;
  34892. void updateColumnComponents() const;
  34893. TableListBox (const TableListBox&);
  34894. const TableListBox& operator= (const TableListBox&);
  34895. };
  34896. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34897. /********* End of inlined file: juce_TableListBox.h *********/
  34898. #endif
  34899. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34900. #endif
  34901. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34902. #endif
  34903. #ifndef __JUCE_LABEL_JUCEHEADER__
  34904. #endif
  34905. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34906. #endif
  34907. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34908. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34909. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34910. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34911. /**
  34912. A PropertyComponent that shows its value as a slider.
  34913. @see PropertyComponent, Slider
  34914. */
  34915. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  34916. private SliderListener
  34917. {
  34918. public:
  34919. /** Creates the property component.
  34920. The ranges, interval and skew factor are passed to the Slider component.
  34921. If you need to customise the slider in other ways, your constructor can
  34922. access the slider member variable and change it directly.
  34923. */
  34924. SliderPropertyComponent (const String& propertyName,
  34925. const double rangeMin,
  34926. const double rangeMax,
  34927. const double interval,
  34928. const double skewFactor = 1.0);
  34929. /** Destructor. */
  34930. ~SliderPropertyComponent();
  34931. /** Called when the user moves the slider to change its value.
  34932. Your subclass must use this method to update whatever item this property
  34933. represents.
  34934. */
  34935. virtual void setValue (const double newValue) = 0;
  34936. /** Returns the value that the slider should show. */
  34937. virtual const double getValue() const = 0;
  34938. /** @internal */
  34939. void refresh();
  34940. /** @internal */
  34941. void changeListenerCallback (void*);
  34942. /** @internal */
  34943. void sliderValueChanged (Slider*);
  34944. juce_UseDebuggingNewOperator
  34945. protected:
  34946. /** The slider component being used in this component.
  34947. Your subclass has access to this in case it needs to customise it in some way.
  34948. */
  34949. Slider* slider;
  34950. };
  34951. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34952. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  34953. #endif
  34954. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34955. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  34956. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34957. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34958. /**
  34959. A PropertyComponent that shows its value as editable text.
  34960. @see PropertyComponent
  34961. */
  34962. class JUCE_API TextPropertyComponent : public PropertyComponent
  34963. {
  34964. public:
  34965. /** Creates a text property component.
  34966. The maxNumChars is used to set the length of string allowable, and isMultiLine
  34967. sets whether the text editor allows carriage returns.
  34968. @see TextEditor
  34969. */
  34970. TextPropertyComponent (const String& propertyName,
  34971. const int maxNumChars,
  34972. const bool isMultiLine);
  34973. /** Destructor. */
  34974. ~TextPropertyComponent();
  34975. /** Called when the user edits the text.
  34976. Your subclass must use this callback to change the value of whatever item
  34977. this property component represents.
  34978. */
  34979. virtual void setText (const String& newText) = 0;
  34980. /** Returns the text that should be shown in the text editor.
  34981. */
  34982. virtual const String getText() const = 0;
  34983. /** @internal */
  34984. void refresh();
  34985. /** @internal */
  34986. void textWasEdited();
  34987. juce_UseDebuggingNewOperator
  34988. private:
  34989. Label* textEditor;
  34990. };
  34991. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34992. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  34993. #endif
  34994. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34995. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34996. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34997. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34998. /**
  34999. A PropertyComponent that contains an on/off toggle button.
  35000. This type of property component can be used if you have a boolean value to
  35001. toggle on/off.
  35002. @see PropertyComponent
  35003. */
  35004. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  35005. private ButtonListener
  35006. {
  35007. public:
  35008. /** Creates a button component.
  35009. @param propertyName the property name to be passed to the PropertyComponent
  35010. @param buttonTextWhenTrue the text shown in the button when the value is true
  35011. @param buttonTextWhenFalse the text shown in the button when the value is false
  35012. */
  35013. BooleanPropertyComponent (const String& propertyName,
  35014. const String& buttonTextWhenTrue,
  35015. const String& buttonTextWhenFalse);
  35016. /** Destructor. */
  35017. ~BooleanPropertyComponent();
  35018. /** Called to change the state of the boolean value. */
  35019. virtual void setState (const bool newState) = 0;
  35020. /** Must return the current value of the property. */
  35021. virtual bool getState() const = 0;
  35022. /** @internal */
  35023. void paint (Graphics& g);
  35024. /** @internal */
  35025. void refresh();
  35026. /** @internal */
  35027. void buttonClicked (Button*);
  35028. juce_UseDebuggingNewOperator
  35029. private:
  35030. ToggleButton* button;
  35031. String onText, offText;
  35032. };
  35033. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35034. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  35035. #endif
  35036. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35037. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  35038. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35039. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35040. /**
  35041. A PropertyComponent that contains a button.
  35042. This type of property component can be used if you need a button to trigger some
  35043. kind of action.
  35044. @see PropertyComponent
  35045. */
  35046. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  35047. private ButtonListener
  35048. {
  35049. public:
  35050. /** Creates a button component.
  35051. @param propertyName the property name to be passed to the PropertyComponent
  35052. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  35053. */
  35054. ButtonPropertyComponent (const String& propertyName,
  35055. const bool triggerOnMouseDown);
  35056. /** Destructor. */
  35057. ~ButtonPropertyComponent();
  35058. /** Called when the user clicks the button.
  35059. */
  35060. virtual void buttonClicked() = 0;
  35061. /** Returns the string that should be displayed in the button.
  35062. If you need to change this string, call refresh() to update the component.
  35063. */
  35064. virtual const String getButtonText() const = 0;
  35065. /** @internal */
  35066. void refresh();
  35067. /** @internal */
  35068. void buttonClicked (Button*);
  35069. juce_UseDebuggingNewOperator
  35070. private:
  35071. TextButton* button;
  35072. };
  35073. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35074. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  35075. #endif
  35076. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35077. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  35078. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35079. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35080. /**
  35081. A PropertyComponent that shows its value as a combo box.
  35082. This type of property component contains a list of options and has a
  35083. combo box to choose one.
  35084. Your subclass's constructor must add some strings to the choices StringArray
  35085. and these are shown in the list.
  35086. The getIndex() method will be called to find out which option is the currently
  35087. selected one. If you call refresh() it will call getIndex() to check whether
  35088. the value has changed, and will update the combo box if needed.
  35089. If the user selects a different item from the list, setIndex() will be
  35090. called to let your class process this.
  35091. @see PropertyComponent, PropertyPanel
  35092. */
  35093. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  35094. private ComboBoxListener
  35095. {
  35096. public:
  35097. /** Creates the component.
  35098. Your subclass's constructor must add a list of options to the choices
  35099. member variable.
  35100. */
  35101. ChoicePropertyComponent (const String& propertyName);
  35102. /** Destructor. */
  35103. ~ChoicePropertyComponent();
  35104. /** Called when the user selects an item from the combo box.
  35105. Your subclass must use this callback to update the value that this component
  35106. represents. The index is the index of the chosen item in the choices
  35107. StringArray.
  35108. */
  35109. virtual void setIndex (const int newIndex) = 0;
  35110. /** Returns the index of the item that should currently be shown.
  35111. This is the index of the item in the choices StringArray that will be
  35112. shown.
  35113. */
  35114. virtual int getIndex() const = 0;
  35115. /** Returns the list of options. */
  35116. const StringArray& getChoices() const throw();
  35117. /** @internal */
  35118. void refresh();
  35119. /** @internal */
  35120. void comboBoxChanged (ComboBox*);
  35121. juce_UseDebuggingNewOperator
  35122. protected:
  35123. /** The list of options that will be shown in the combo box.
  35124. Your subclass must populate this array in its constructor. If any empty
  35125. strings are added, these will be replaced with horizontal separators (see
  35126. ComboBox::addSeparator() for more info).
  35127. */
  35128. StringArray choices;
  35129. private:
  35130. ComboBox* comboBox;
  35131. };
  35132. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35133. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  35134. #endif
  35135. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35136. #endif
  35137. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35138. #endif
  35139. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35140. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  35141. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35142. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35143. /********* Start of inlined file: juce_TabbedComponent.h *********/
  35144. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35145. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35146. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  35147. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35148. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35149. class TabbedButtonBar;
  35150. /** In a TabbedButtonBar, this component is used for each of the buttons.
  35151. If you want to create a TabbedButtonBar with custom tab components, derive
  35152. your component from this class, and override the TabbedButtonBar::createTabButton()
  35153. method to create it instead of the default one.
  35154. @see TabbedButtonBar
  35155. */
  35156. class JUCE_API TabBarButton : public Button
  35157. {
  35158. public:
  35159. /** Creates the tab button. */
  35160. TabBarButton (const String& name,
  35161. TabbedButtonBar* const ownerBar,
  35162. const int tabIndex);
  35163. /** Destructor. */
  35164. ~TabBarButton();
  35165. /** Chooses the best length for the tab, given the specified depth.
  35166. If the tab is horizontal, this should return its width, and the depth
  35167. specifies its height. If it's vertical, it should return the height, and
  35168. the depth is actually its width.
  35169. */
  35170. virtual int getBestTabLength (const int depth);
  35171. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35172. void clicked (const ModifierKeys& mods);
  35173. bool hitTest (int x, int y);
  35174. juce_UseDebuggingNewOperator
  35175. protected:
  35176. friend class TabbedButtonBar;
  35177. TabbedButtonBar* const owner;
  35178. int tabIndex, overlapPixels;
  35179. DropShadowEffect shadow;
  35180. /** Returns an area of the component that's safe to draw in.
  35181. This deals with the orientation of the tabs, which affects which side is
  35182. touching the tabbed box's content component.
  35183. */
  35184. void getActiveArea (int& x, int& y, int& w, int& h);
  35185. private:
  35186. TabBarButton (const TabBarButton&);
  35187. const TabBarButton& operator= (const TabBarButton&);
  35188. };
  35189. /**
  35190. A vertical or horizontal bar containing tabs that you can select.
  35191. You can use one of these to generate things like a dialog box that has
  35192. tabbed pages you can flip between. Attach a ChangeListener to the
  35193. button bar to be told when the user changes the page.
  35194. An easier method than doing this is to use a TabbedComponent, which
  35195. contains its own TabbedButtonBar and which takes care of the layout
  35196. and other housekeeping.
  35197. @see TabbedComponent
  35198. */
  35199. class JUCE_API TabbedButtonBar : public Component,
  35200. public ChangeBroadcaster,
  35201. public ButtonListener
  35202. {
  35203. public:
  35204. /** The placement of the tab-bar
  35205. @see setOrientation, getOrientation
  35206. */
  35207. enum Orientation
  35208. {
  35209. TabsAtTop,
  35210. TabsAtBottom,
  35211. TabsAtLeft,
  35212. TabsAtRight
  35213. };
  35214. /** Creates a TabbedButtonBar with a given placement.
  35215. You can change the orientation later if you need to.
  35216. */
  35217. TabbedButtonBar (const Orientation orientation);
  35218. /** Destructor. */
  35219. ~TabbedButtonBar();
  35220. /** Changes the bar's orientation.
  35221. This won't change the bar's actual size - you'll need to do that yourself,
  35222. but this determines which direction the tabs go in, and which side they're
  35223. stuck to.
  35224. */
  35225. void setOrientation (const Orientation orientation);
  35226. /** Returns the current orientation.
  35227. @see setOrientation
  35228. */
  35229. Orientation getOrientation() const throw() { return orientation; }
  35230. /** Deletes all the tabs from the bar.
  35231. @see addTab
  35232. */
  35233. void clearTabs();
  35234. /** Adds a tab to the bar.
  35235. Tabs are added in left-to-right reading order.
  35236. If this is the first tab added, it'll also be automatically selected.
  35237. */
  35238. void addTab (const String& tabName,
  35239. const Colour& tabBackgroundColour,
  35240. int insertIndex = -1);
  35241. /** Changes the name of one of the tabs. */
  35242. void setTabName (const int tabIndex,
  35243. const String& newName);
  35244. /** Gets rid of one of the tabs. */
  35245. void removeTab (const int tabIndex);
  35246. /** Moves a tab to a new index in the list.
  35247. Pass -1 as the index to move it to the end of the list.
  35248. */
  35249. void moveTab (const int currentIndex,
  35250. const int newIndex);
  35251. /** Returns the number of tabs in the bar. */
  35252. int getNumTabs() const;
  35253. /** Returns a list of all the tab names in the bar. */
  35254. const StringArray getTabNames() const;
  35255. /** Changes the currently selected tab.
  35256. This will send a change message and cause a synchronous callback to
  35257. the currentTabChanged() method. (But if the given tab is already selected,
  35258. nothing will be done).
  35259. To deselect all the tabs, use an index of -1.
  35260. */
  35261. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  35262. /** Returns the name of the currently selected tab.
  35263. This could be an empty string if none are selected.
  35264. */
  35265. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  35266. /** Returns the index of the currently selected tab.
  35267. This could return -1 if none are selected.
  35268. */
  35269. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  35270. /** Returns the button for a specific tab.
  35271. The button that is returned may be deleted later by this component, so don't hang
  35272. on to the pointer that is returned. A null pointer may be returned if the index is
  35273. out of range.
  35274. */
  35275. TabBarButton* getTabButton (const int index) const;
  35276. /** Callback method to indicate the selected tab has been changed.
  35277. @see setCurrentTabIndex
  35278. */
  35279. virtual void currentTabChanged (const int newCurrentTabIndex,
  35280. const String& newCurrentTabName);
  35281. /** Callback method to indicate that the user has right-clicked on a tab.
  35282. (Or ctrl-clicked on the Mac)
  35283. */
  35284. virtual void popupMenuClickOnTab (const int tabIndex,
  35285. const String& tabName);
  35286. /** Returns the colour of a tab.
  35287. This is the colour that was specified in addTab().
  35288. */
  35289. const Colour getTabBackgroundColour (const int tabIndex);
  35290. /** Changes the background colour of a tab.
  35291. @see addTab, getTabBackgroundColour
  35292. */
  35293. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35294. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35295. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35296. methods.
  35297. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35298. */
  35299. enum ColourIds
  35300. {
  35301. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  35302. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  35303. the look and feel will choose an appropriate colour. */
  35304. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  35305. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  35306. this isn't specified, the look and feel will choose an appropriate
  35307. colour. */
  35308. };
  35309. /** @internal */
  35310. void resized();
  35311. /** @internal */
  35312. void buttonClicked (Button* button);
  35313. /** @internal */
  35314. void lookAndFeelChanged();
  35315. juce_UseDebuggingNewOperator
  35316. protected:
  35317. /** This creates one of the tabs.
  35318. If you need to use custom tab components, you can override this method and
  35319. return your own class instead of the default.
  35320. */
  35321. virtual TabBarButton* createTabButton (const String& tabName,
  35322. const int tabIndex);
  35323. private:
  35324. Orientation orientation;
  35325. StringArray tabs;
  35326. Array <Colour> tabColours;
  35327. int currentTabIndex;
  35328. Component* behindFrontTab;
  35329. Button* extraTabsButton;
  35330. TabbedButtonBar (const TabbedButtonBar&);
  35331. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  35332. };
  35333. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35334. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  35335. /**
  35336. A component with a TabbedButtonBar along one of its sides.
  35337. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  35338. with addTab(), and this will take care of showing the pages for you when the
  35339. user clicks on a different tab.
  35340. @see TabbedButtonBar
  35341. */
  35342. class JUCE_API TabbedComponent : public Component
  35343. {
  35344. public:
  35345. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  35346. Once created, add some tabs with the addTab() method.
  35347. */
  35348. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  35349. /** Destructor. */
  35350. ~TabbedComponent();
  35351. /** Changes the placement of the tabs.
  35352. This will rearrange the layout to place the tabs along the appropriate
  35353. side of this component, and will shift the content component accordingly.
  35354. @see TabbedButtonBar::setOrientation
  35355. */
  35356. void setOrientation (const TabbedButtonBar::Orientation orientation);
  35357. /** Returns the current tab placement.
  35358. @see setOrientation, TabbedButtonBar::getOrientation
  35359. */
  35360. TabbedButtonBar::Orientation getOrientation() const throw();
  35361. /** Specifies how many pixels wide or high the tab-bar should be.
  35362. If the tabs are placed along the top or bottom, this specified the height
  35363. of the bar; if they're along the left or right edges, it'll be the width
  35364. of the bar.
  35365. */
  35366. void setTabBarDepth (const int newDepth);
  35367. /** Returns the current thickness of the tab bar.
  35368. @see setTabBarDepth
  35369. */
  35370. int getTabBarDepth() const throw() { return tabDepth; }
  35371. /** Specifies the thickness of an outline that should be drawn around the content component.
  35372. If this thickness is > 0, a line will be drawn around the three sides of the content
  35373. component which don't touch the tab-bar, and the content component will be inset by this amount.
  35374. To set the colour of the line, use setColour (outlineColourId, ...).
  35375. */
  35376. void setOutline (const int newThickness);
  35377. /** Specifies a gap to leave around the edge of the content component.
  35378. Each edge of the content component will be indented by the given number of pixels.
  35379. */
  35380. void setIndent (const int indentThickness);
  35381. /** Removes all the tabs from the bar.
  35382. @see TabbedButtonBar::clearTabs
  35383. */
  35384. void clearTabs();
  35385. /** Adds a tab to the tab-bar.
  35386. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  35387. is true, it will be deleted when the tab is removed or when this object is
  35388. deleted.
  35389. @see TabbedButtonBar::addTab
  35390. */
  35391. void addTab (const String& tabName,
  35392. const Colour& tabBackgroundColour,
  35393. Component* const contentComponent,
  35394. const bool deleteComponentWhenNotNeeded,
  35395. const int insertIndex = -1);
  35396. /** Changes the name of one of the tabs. */
  35397. void setTabName (const int tabIndex,
  35398. const String& newName);
  35399. /** Gets rid of one of the tabs. */
  35400. void removeTab (const int tabIndex);
  35401. /** Returns the number of tabs in the bar. */
  35402. int getNumTabs() const;
  35403. /** Returns a list of all the tab names in the bar. */
  35404. const StringArray getTabNames() const;
  35405. /** Returns the content component that was added for the given index.
  35406. Be sure not to use or delete the components that are returned, as this may interfere
  35407. with the TabbedComponent's use of them.
  35408. */
  35409. Component* getTabContentComponent (const int tabIndex) const throw();
  35410. /** Returns the colour of one of the tabs. */
  35411. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  35412. /** Changes the background colour of one of the tabs. */
  35413. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35414. /** Changes the currently-selected tab.
  35415. To deselect all the tabs, pass -1 as the index.
  35416. @see TabbedButtonBar::setCurrentTabIndex
  35417. */
  35418. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  35419. /** Returns the index of the currently selected tab.
  35420. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  35421. */
  35422. int getCurrentTabIndex() const;
  35423. /** Returns the name of the currently selected tab.
  35424. @see addTab, TabbedButtonBar::getCurrentTabName()
  35425. */
  35426. const String& getCurrentTabName() const;
  35427. /** Returns the current component that's filling the panel.
  35428. This will return 0 if there isn't one.
  35429. */
  35430. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  35431. /** Callback method to indicate the selected tab has been changed.
  35432. @see setCurrentTabIndex
  35433. */
  35434. virtual void currentTabChanged (const int newCurrentTabIndex,
  35435. const String& newCurrentTabName);
  35436. /** Callback method to indicate that the user has right-clicked on a tab.
  35437. (Or ctrl-clicked on the Mac)
  35438. */
  35439. virtual void popupMenuClickOnTab (const int tabIndex,
  35440. const String& tabName);
  35441. /** Returns the tab button bar component that is being used.
  35442. */
  35443. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  35444. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35445. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35446. methods.
  35447. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35448. */
  35449. enum ColourIds
  35450. {
  35451. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  35452. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  35453. (See setOutline) */
  35454. };
  35455. /** @internal */
  35456. void paint (Graphics& g);
  35457. /** @internal */
  35458. void resized();
  35459. /** @internal */
  35460. void lookAndFeelChanged();
  35461. juce_UseDebuggingNewOperator
  35462. protected:
  35463. TabbedButtonBar* tabs;
  35464. /** This creates one of the tab buttons.
  35465. If you need to use custom tab components, you can override this method and
  35466. return your own class instead of the default.
  35467. */
  35468. virtual TabBarButton* createTabButton (const String& tabName,
  35469. const int tabIndex);
  35470. private:
  35471. Array <Component*> contentComponents;
  35472. Component* panelComponent;
  35473. int tabDepth;
  35474. int outlineThickness, edgeIndent;
  35475. friend class TabCompButtonBar;
  35476. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  35477. TabbedComponent (const TabbedComponent&);
  35478. const TabbedComponent& operator= (const TabbedComponent&);
  35479. };
  35480. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35481. /********* End of inlined file: juce_TabbedComponent.h *********/
  35482. /********* Start of inlined file: juce_DocumentWindow.h *********/
  35483. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35484. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35485. /********* Start of inlined file: juce_ResizableWindow.h *********/
  35486. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35487. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35488. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  35489. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35490. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35491. /********* Start of inlined file: juce_DropShadower.h *********/
  35492. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  35493. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  35494. /**
  35495. Adds a drop-shadow to a component.
  35496. This object creates and manages a set of components which sit around a
  35497. component, creating a gaussian shadow around it. The components will track
  35498. the position of the component and if it's brought to the front they'll also
  35499. follow this.
  35500. For desktop windows you don't need to use this class directly - just
  35501. set the Component::windowHasDropShadow flag when calling
  35502. Component::addToDesktop(), and the system will create one of these if it's
  35503. needed (which it obviously isn't on the Mac, for example).
  35504. */
  35505. class JUCE_API DropShadower : public ComponentListener
  35506. {
  35507. public:
  35508. /** Creates a DropShadower.
  35509. @param alpha the opacity of the shadows, from 0 to 1.0
  35510. @param xOffset the horizontal displacement of the shadow, in pixels
  35511. @param yOffset the vertical displacement of the shadow, in pixels
  35512. @param blurRadius the radius of the blur to use for creating the shadow
  35513. */
  35514. DropShadower (const float alpha = 0.5f,
  35515. const int xOffset = 1,
  35516. const int yOffset = 5,
  35517. const float blurRadius = 10.0f);
  35518. /** Destructor. */
  35519. virtual ~DropShadower();
  35520. /** Attaches the DropShadower to the component you want to shadow. */
  35521. void setOwner (Component* componentToFollow);
  35522. /** @internal */
  35523. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35524. /** @internal */
  35525. void componentBroughtToFront (Component& component);
  35526. /** @internal */
  35527. void componentChildrenChanged (Component& component);
  35528. /** @internal */
  35529. void componentParentHierarchyChanged (Component& component);
  35530. /** @internal */
  35531. void componentVisibilityChanged (Component& component);
  35532. juce_UseDebuggingNewOperator
  35533. private:
  35534. Component* owner;
  35535. int numShadows;
  35536. Component* shadowWindows[4];
  35537. Image* shadowImageSections[12];
  35538. const int shadowEdge, xOffset, yOffset;
  35539. const float alpha, blurRadius;
  35540. bool inDestructor, reentrant;
  35541. void updateShadows();
  35542. void setShadowImage (Image* const src,
  35543. const int num,
  35544. const int w, const int h,
  35545. const int sx, const int sy) throw();
  35546. void bringShadowWindowsToFront();
  35547. void deleteShadowWindows();
  35548. DropShadower (const DropShadower&);
  35549. const DropShadower& operator= (const DropShadower&);
  35550. };
  35551. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35552. /********* End of inlined file: juce_DropShadower.h *********/
  35553. /**
  35554. A base class for top-level windows.
  35555. This class is used for components that are considered a major part of your
  35556. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35557. etc. Things like menus that pop up briefly aren't derived from it.
  35558. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35559. could itself be the child of another component.
  35560. The class manages a list of all instances of top-level windows that are in use,
  35561. and each one is also given the concept of being "active". The active window is
  35562. one that is actively being used by the user. This isn't quite the same as the
  35563. component with the keyboard focus, because there may be a popup menu or other
  35564. temporary window which gets keyboard focus while the active top level window is
  35565. unchanged.
  35566. A top-level window also has an optional drop-shadow.
  35567. @see ResizableWindow, DocumentWindow, DialogWindow
  35568. */
  35569. class JUCE_API TopLevelWindow : public Component
  35570. {
  35571. public:
  35572. /** Creates a TopLevelWindow.
  35573. @param name the name to give the component
  35574. @param addToDesktop if true, the window will be automatically added to the
  35575. desktop; if false, you can use it as a child component
  35576. */
  35577. TopLevelWindow (const String& name,
  35578. const bool addToDesktop);
  35579. /** Destructor. */
  35580. ~TopLevelWindow();
  35581. /** True if this is currently the TopLevelWindow that is actively being used.
  35582. This isn't quite the same as having keyboard focus, because the focus may be
  35583. on a child component or a temporary pop-up menu, etc, while this window is
  35584. still considered to be active.
  35585. @see activeWindowStatusChanged
  35586. */
  35587. bool isActiveWindow() const throw() { return windowIsActive_; }
  35588. /** This will set the bounds of the window so that it's centred in front of another
  35589. window.
  35590. If your app has a few windows open and want to pop up a dialog box for one of
  35591. them, you can use this to show it in front of the relevent parent window, which
  35592. is a bit neater than just having it appear in the middle of the screen.
  35593. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35594. be used instead. If no window is focused, it'll just default to the middle of the
  35595. screen.
  35596. */
  35597. void centreAroundComponent (Component* componentToCentreAround,
  35598. const int width, const int height);
  35599. /** Turns the drop-shadow on and off. */
  35600. void setDropShadowEnabled (const bool useShadow);
  35601. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35602. @see isUsingNativeTitleBar
  35603. */
  35604. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35605. /** Returns true if the window is currently using an OS-native title bar.
  35606. @see setUsingNativeTitleBar
  35607. */
  35608. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35609. /** Returns the number of TopLevelWindow objects currently in use.
  35610. @see getTopLevelWindow
  35611. */
  35612. static int getNumTopLevelWindows() throw();
  35613. /** Returns one of the TopLevelWindow objects currently in use.
  35614. The index is 0 to (getNumTopLevelWindows() - 1).
  35615. */
  35616. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35617. /** Returns the currently-active top level window.
  35618. There might not be one, of course, so this can return 0.
  35619. */
  35620. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35621. juce_UseDebuggingNewOperator
  35622. /** @internal */
  35623. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35624. protected:
  35625. /** This callback happens when this window becomes active or inactive.
  35626. @see isActiveWindow
  35627. */
  35628. virtual void activeWindowStatusChanged();
  35629. /** @internal */
  35630. void focusOfChildComponentChanged (FocusChangeType cause);
  35631. /** @internal */
  35632. void parentHierarchyChanged();
  35633. /** @internal */
  35634. void visibilityChanged();
  35635. /** @internal */
  35636. virtual int getDesktopWindowStyleFlags() const;
  35637. /** @internal */
  35638. void recreateDesktopWindow();
  35639. private:
  35640. friend class TopLevelWindowManager;
  35641. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35642. DropShadower* shadower;
  35643. void setWindowActive (const bool isNowActive) throw();
  35644. TopLevelWindow (const TopLevelWindow&);
  35645. const TopLevelWindow& operator= (const TopLevelWindow&);
  35646. };
  35647. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35648. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35649. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35650. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35651. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35652. /**
  35653. A component that resizes its parent window when dragged.
  35654. This component forms a frame around the edge of a component, allowing it to
  35655. be dragged by the edges or corners to resize it - like the way windows are
  35656. resized in MSWindows or Linux.
  35657. To use it, just add it to your component, making it fill the entire parent component
  35658. (there's a mouse hit-test that only traps mouse-events which land around the
  35659. edge of the component, so it's even ok to put it on top of any other components
  35660. you're using). Make sure you rescale the resizer component to fill the parent
  35661. each time the parent's size changes.
  35662. @see ResizableCornerComponent
  35663. */
  35664. class JUCE_API ResizableBorderComponent : public Component
  35665. {
  35666. public:
  35667. /** Creates a resizer.
  35668. Pass in the target component which you want to be resized when this one is
  35669. dragged.
  35670. The target component will usually be a parent of the resizer component, but this
  35671. isn't mandatory.
  35672. Remember that when the target component is resized, it'll need to move and
  35673. resize this component to keep it in place, as this won't happen automatically.
  35674. If the constrainer parameter is non-zero, then this object will be used to enforce
  35675. limits on the size and position that the component can be stretched to. Make sure
  35676. that the constrainer isn't deleted while still in use by this object.
  35677. @see ComponentBoundsConstrainer
  35678. */
  35679. ResizableBorderComponent (Component* const componentToResize,
  35680. ComponentBoundsConstrainer* const constrainer);
  35681. /** Destructor. */
  35682. ~ResizableBorderComponent();
  35683. /** Specifies how many pixels wide the draggable edges of this component are.
  35684. @see getBorderThickness
  35685. */
  35686. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35687. /** Returns the number of pixels wide that the draggable edges of this component are.
  35688. @see setBorderThickness
  35689. */
  35690. const BorderSize getBorderThickness() const throw();
  35691. juce_UseDebuggingNewOperator
  35692. protected:
  35693. /** @internal */
  35694. void paint (Graphics& g);
  35695. /** @internal */
  35696. void mouseEnter (const MouseEvent& e);
  35697. /** @internal */
  35698. void mouseMove (const MouseEvent& e);
  35699. /** @internal */
  35700. void mouseDown (const MouseEvent& e);
  35701. /** @internal */
  35702. void mouseDrag (const MouseEvent& e);
  35703. /** @internal */
  35704. void mouseUp (const MouseEvent& e);
  35705. /** @internal */
  35706. bool hitTest (int x, int y);
  35707. private:
  35708. Component* const component;
  35709. ComponentBoundsConstrainer* constrainer;
  35710. BorderSize borderSize;
  35711. int originalX, originalY, originalW, originalH;
  35712. int mouseZone;
  35713. void updateMouseZone (const MouseEvent& e) throw();
  35714. ResizableBorderComponent (const ResizableBorderComponent&);
  35715. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35716. };
  35717. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35718. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35719. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35720. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35721. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35722. /** A component that resizes a parent window when dragged.
  35723. This is the small triangular stripey resizer component you get in the bottom-right
  35724. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35725. a larger component and it will automatically resize its parent when it gets dragged
  35726. around.
  35727. @see ResizableFrameComponent
  35728. */
  35729. class JUCE_API ResizableCornerComponent : public Component
  35730. {
  35731. public:
  35732. /** Creates a resizer.
  35733. Pass in the target component which you want to be resized when this one is
  35734. dragged.
  35735. The target component will usually be a parent of the resizer component, but this
  35736. isn't mandatory.
  35737. Remember that when the target component is resized, it'll need to move and
  35738. resize this component to keep it in place, as this won't happen automatically.
  35739. If the constrainer parameter is non-zero, then this object will be used to enforce
  35740. limits on the size and position that the component can be stretched to. Make sure
  35741. that the constrainer isn't deleted while still in use by this object. If you
  35742. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35743. @see ComponentBoundsConstrainer
  35744. */
  35745. ResizableCornerComponent (Component* const componentToResize,
  35746. ComponentBoundsConstrainer* const constrainer);
  35747. /** Destructor. */
  35748. ~ResizableCornerComponent();
  35749. juce_UseDebuggingNewOperator
  35750. protected:
  35751. /** @internal */
  35752. void paint (Graphics& g);
  35753. /** @internal */
  35754. void mouseDown (const MouseEvent& e);
  35755. /** @internal */
  35756. void mouseDrag (const MouseEvent& e);
  35757. /** @internal */
  35758. void mouseUp (const MouseEvent& e);
  35759. /** @internal */
  35760. bool hitTest (int x, int y);
  35761. private:
  35762. Component* const component;
  35763. ComponentBoundsConstrainer* constrainer;
  35764. int originalX, originalY, originalW, originalH;
  35765. ResizableCornerComponent (const ResizableCornerComponent&);
  35766. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35767. };
  35768. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35769. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35770. /**
  35771. A base class for top-level windows that can be dragged around and resized.
  35772. To add content to the window, use its setContentComponent() method to
  35773. give it a component that will remain positioned inside it (leaving a gap around
  35774. the edges for a border).
  35775. It's not advisable to add child components directly to a ResizableWindow: put them
  35776. inside your content component instead. And overriding methods like resized(), moved(), etc
  35777. is also not recommended - instead override these methods for your content component.
  35778. (If for some obscure reason you do need to override these methods, always remember to
  35779. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35780. decorations correctly).
  35781. By default resizing isn't enabled - use the setResizable() method to enable it and
  35782. to choose the style of resizing to use.
  35783. @see TopLevelWindow
  35784. */
  35785. class JUCE_API ResizableWindow : public TopLevelWindow
  35786. {
  35787. public:
  35788. /** Creates a ResizableWindow.
  35789. This constructor doesn't specify a background colour, so the LookAndFeel's default
  35790. background colour will be used.
  35791. @param name the name to give the component
  35792. @param addToDesktop if true, the window will be automatically added to the
  35793. desktop; if false, you can use it as a child component
  35794. */
  35795. ResizableWindow (const String& name,
  35796. const bool addToDesktop);
  35797. /** Creates a ResizableWindow.
  35798. @param name the name to give the component
  35799. @param backgroundColour the colour to use for filling the window's background.
  35800. @param addToDesktop if true, the window will be automatically added to the
  35801. desktop; if false, you can use it as a child component
  35802. */
  35803. ResizableWindow (const String& name,
  35804. const Colour& backgroundColour,
  35805. const bool addToDesktop);
  35806. /** Destructor.
  35807. If a content component has been set with setContentComponent(), it
  35808. will be deleted.
  35809. */
  35810. ~ResizableWindow();
  35811. /** Returns the colour currently being used for the window's background.
  35812. As a convenience the window will fill itself with this colour, but you
  35813. can override the paint() method if you need more customised behaviour.
  35814. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  35815. @see setBackgroundColour
  35816. */
  35817. const Colour getBackgroundColour() const throw();
  35818. /** Changes the colour currently being used for the window's background.
  35819. As a convenience the window will fill itself with this colour, but you
  35820. can override the paint() method if you need more customised behaviour.
  35821. Note that the opaque state of this window is altered by this call to reflect
  35822. the opacity of the colour passed-in. On window systems which can't support
  35823. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35824. be using this class as a base for a semi-transparent component anyway).
  35825. You can also use the ResizableWindow::backgroundColourId colour id to set
  35826. this colour.
  35827. @see getBackgroundColour
  35828. */
  35829. void setBackgroundColour (const Colour& newColour);
  35830. /** Make the window resizable or fixed.
  35831. @param shouldBeResizable whether it's resizable at all
  35832. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35833. bottom-right; if false, it'll use a ResizableBorderComponent
  35834. around the edge
  35835. @see setResizeLimits, isResizable
  35836. */
  35837. void setResizable (const bool shouldBeResizable,
  35838. const bool useBottomRightCornerResizer);
  35839. /** True if resizing is enabled.
  35840. @see setResizable
  35841. */
  35842. bool isResizable() const throw();
  35843. /** This sets the maximum and minimum sizes for the window.
  35844. If the window's current size is outside these limits, it will be resized to
  35845. make sure it's within them.
  35846. Calling setBounds() on the component will bypass any size checking - it's only when
  35847. the window is being resized by the user that these values are enforced.
  35848. @see setResizable, setFixedAspectRatio
  35849. */
  35850. void setResizeLimits (const int newMinimumWidth,
  35851. const int newMinimumHeight,
  35852. const int newMaximumWidth,
  35853. const int newMaximumHeight) throw();
  35854. /** Returns the bounds constrainer object that this window is using.
  35855. You can access this to change its properties.
  35856. */
  35857. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35858. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35859. A pointer to the object you pass in will be kept, but it won't be deleted
  35860. by this object, so it's the caller's responsiblity to manage it.
  35861. If you pass 0, then no contraints will be placed on the positioning of the window.
  35862. */
  35863. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35864. /** Calls the window's setBounds method, after first checking these bounds
  35865. with the current constrainer.
  35866. @see setConstrainer
  35867. */
  35868. void setBoundsConstrained (int x, int y, int width, int height);
  35869. /** Returns true if the window is currently in full-screen mode.
  35870. @see setFullScreen
  35871. */
  35872. bool isFullScreen() const;
  35873. /** Puts the window into full-screen mode, or restores it to its normal size.
  35874. If true, the window will become full-screen; if false, it will return to the
  35875. last size it was before being made full-screen.
  35876. @see isFullScreen
  35877. */
  35878. void setFullScreen (const bool shouldBeFullScreen);
  35879. /** Returns true if the window is currently minimised.
  35880. @see setMinimised
  35881. */
  35882. bool isMinimised() const;
  35883. /** Minimises the window, or restores it to its previous position and size.
  35884. When being un-minimised, it'll return to the last position and size it
  35885. was in before being minimised.
  35886. @see isMinimised
  35887. */
  35888. void setMinimised (const bool shouldMinimise);
  35889. /** Returns a string which encodes the window's current size and position.
  35890. This string will encapsulate the window's size, position, and whether it's
  35891. in full-screen mode. It's intended for letting your application save and
  35892. restore a window's position.
  35893. Use the restoreWindowStateFromString() to restore from a saved state.
  35894. @see restoreWindowStateFromString
  35895. */
  35896. const String getWindowStateAsString();
  35897. /** Restores the window to a previously-saved size and position.
  35898. This restores the window's size, positon and full-screen status from an
  35899. string that was previously created with the getWindowStateAsString()
  35900. method.
  35901. @returns false if the string wasn't a valid window state
  35902. @see getWindowStateAsString
  35903. */
  35904. bool restoreWindowStateFromString (const String& previousState);
  35905. /** Returns the current content component.
  35906. This will be the component set by setContentComponent(), or 0 if none
  35907. has yet been specified.
  35908. @see setContentComponent
  35909. */
  35910. Component* getContentComponent() const throw() { return contentComponent; }
  35911. /** Changes the current content component.
  35912. This sets a component that will be placed in the centre of the ResizableWindow,
  35913. (leaving a space around the edge for the border).
  35914. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35915. with addChildComponent(). Instead, add them to the content component.
  35916. @param newContentComponent the new component to use (or null to not use one) - this
  35917. component will be deleted either when replaced by another call
  35918. to this method, or when the ResizableWindow is deleted.
  35919. To remove a content component without deleting it, use
  35920. setContentComponent (0, false).
  35921. @param deleteOldOne if true, the previous content component will be deleted; if
  35922. false, the previous component will just be removed without
  35923. deleting it.
  35924. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35925. it always fits around the size of the content component. If false, the
  35926. new content will be resized to fit the current space available.
  35927. */
  35928. void setContentComponent (Component* const newContentComponent,
  35929. const bool deleteOldOne = true,
  35930. const bool resizeToFit = false);
  35931. /** Changes the window so that the content component ends up with the specified size.
  35932. This is basically a setSize call on the window, but which adds on the borders,
  35933. so you can specify the content component's target size.
  35934. */
  35935. void setContentComponentSize (int width, int height);
  35936. /** A set of colour IDs to use to change the colour of various aspects of the window.
  35937. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35938. methods.
  35939. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35940. */
  35941. enum ColourIds
  35942. {
  35943. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  35944. };
  35945. juce_UseDebuggingNewOperator
  35946. protected:
  35947. /** @internal */
  35948. void paint (Graphics& g);
  35949. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35950. void moved();
  35951. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35952. void resized();
  35953. /** @internal */
  35954. void mouseDown (const MouseEvent& e);
  35955. /** @internal */
  35956. void mouseDrag (const MouseEvent& e);
  35957. /** @internal */
  35958. void lookAndFeelChanged();
  35959. /** @internal */
  35960. void childBoundsChanged (Component* child);
  35961. /** @internal */
  35962. void parentSizeChanged();
  35963. /** @internal */
  35964. void visibilityChanged();
  35965. /** @internal */
  35966. void activeWindowStatusChanged();
  35967. /** @internal */
  35968. int getDesktopWindowStyleFlags() const;
  35969. /** Returns the width of the border to use around the window.
  35970. @see getContentComponentBorder
  35971. */
  35972. virtual const BorderSize getBorderThickness();
  35973. /** Returns the insets to use when positioning the content component.
  35974. @see getBorderThickness
  35975. */
  35976. virtual const BorderSize getContentComponentBorder();
  35977. #ifdef JUCE_DEBUG
  35978. /** Overridden to warn people about adding components directly to this component
  35979. instead of using setContentComponent().
  35980. If you know what you're doing and are sure you really want to add a component, specify
  35981. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35982. */
  35983. void addChildComponent (Component* const child, int zOrder = -1);
  35984. /** Overridden to warn people about adding components directly to this component
  35985. instead of using setContentComponent().
  35986. If you know what you're doing and are sure you really want to add a component, specify
  35987. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35988. */
  35989. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35990. #endif
  35991. ResizableCornerComponent* resizableCorner;
  35992. ResizableBorderComponent* resizableBorder;
  35993. private:
  35994. Component* contentComponent;
  35995. bool resizeToFitContent, fullscreen;
  35996. ComponentDragger dragger;
  35997. Rectangle lastNonFullScreenPos;
  35998. ComponentBoundsConstrainer defaultConstrainer;
  35999. ComponentBoundsConstrainer* constrainer;
  36000. #ifdef JUCE_DEBUG
  36001. bool hasBeenResized;
  36002. #endif
  36003. void updateLastPos();
  36004. ResizableWindow (const ResizableWindow&);
  36005. const ResizableWindow& operator= (const ResizableWindow&);
  36006. // (xxx remove these eventually)
  36007. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36008. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  36009. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36010. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  36011. };
  36012. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36013. /********* End of inlined file: juce_ResizableWindow.h *********/
  36014. /**
  36015. A resizable window with a title bar and maximise, minimise and close buttons.
  36016. This subclass of ResizableWindow creates a fairly standard type of window with
  36017. a title bar and various buttons. The name of the component is shown in the
  36018. title bar, and an icon can optionally be specified with setIcon().
  36019. All the methods available to a ResizableWindow are also available to this,
  36020. so it can easily be made resizable, minimised, maximised, etc.
  36021. It's not advisable to add child components directly to a DocumentWindow: put them
  36022. inside your content component instead. And overriding methods like resized(), moved(), etc
  36023. is also not recommended - instead override these methods for your content component.
  36024. (If for some obscure reason you do need to override these methods, always remember to
  36025. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36026. decorations correctly).
  36027. You can also automatically add a menu bar to the window, using the setMenuBar()
  36028. method.
  36029. @see ResizableWindow, DialogWindow
  36030. */
  36031. class JUCE_API DocumentWindow : public ResizableWindow
  36032. {
  36033. public:
  36034. /** The set of available button-types that can be put on the title bar.
  36035. @see setTitleBarButtonsRequired
  36036. */
  36037. enum TitleBarButtons
  36038. {
  36039. minimiseButton = 1,
  36040. maximiseButton = 2,
  36041. closeButton = 4,
  36042. /** A combination of all the buttons above. */
  36043. allButtons = 7
  36044. };
  36045. /** Creates a DocumentWindow.
  36046. @param name the name to give the component - this is also
  36047. the title shown at the top of the window. To change
  36048. this later, use setName()
  36049. @param backgroundColour the colour to use for filling the window's background.
  36050. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36051. should be shown on the title bar. This value is a bitwise
  36052. combination of values from the TitleBarButtons enum. Note
  36053. that it can be "allButtons" to get them all. You
  36054. can change this later with the setTitleBarButtonsRequired()
  36055. method, which can also specify where they are positioned.
  36056. @param addToDesktop if true, the window will be automatically added to the
  36057. desktop; if false, you can use it as a child component
  36058. @see TitleBarButtons
  36059. */
  36060. DocumentWindow (const String& name,
  36061. const Colour& backgroundColour,
  36062. const int requiredButtons,
  36063. const bool addToDesktop = true);
  36064. /** Destructor.
  36065. If a content component has been set with setContentComponent(), it
  36066. will be deleted.
  36067. */
  36068. ~DocumentWindow();
  36069. /** Changes the component's name.
  36070. (This is overridden from Component::setName() to cause a repaint, as
  36071. the name is what gets drawn across the window's title bar).
  36072. */
  36073. void setName (const String& newName);
  36074. /** Sets an icon to show in the title bar, next to the title.
  36075. A copy is made internally of the image, so the caller can delete the
  36076. image after calling this. If 0 is passed-in, any existing icon will be
  36077. removed.
  36078. */
  36079. void setIcon (const Image* imageToUse);
  36080. /** Changes the height of the title-bar. */
  36081. void setTitleBarHeight (const int newHeight);
  36082. /** Returns the current title bar height. */
  36083. int getTitleBarHeight() const;
  36084. /** Changes the set of title-bar buttons being shown.
  36085. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36086. should be shown on the title bar. This value is a bitwise
  36087. combination of values from the TitleBarButtons enum. Note
  36088. that it can be "allButtons" to get them all.
  36089. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  36090. left side of the bar; if false, they'll be placed at the right
  36091. */
  36092. void setTitleBarButtonsRequired (const int requiredButtons,
  36093. const bool positionTitleBarButtonsOnLeft);
  36094. /** Sets whether the title should be centred within the window.
  36095. If true, the title text is shown in the middle of the title-bar; if false,
  36096. it'll be shown at the left of the bar.
  36097. */
  36098. void setTitleBarTextCentred (const bool textShouldBeCentred);
  36099. /** Creates a menu inside this window.
  36100. @param menuBarModel this specifies a MenuBarModel that should be used to
  36101. generate the contents of a menu bar that will be placed
  36102. just below the title bar, and just above any content
  36103. component. If this value is zero, any existing menu bar
  36104. will be removed from the component; if non-zero, one will
  36105. be added if it's required.
  36106. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  36107. or less to use the look-and-feel's default size.
  36108. */
  36109. void setMenuBar (MenuBarModel* menuBarModel,
  36110. const int menuBarHeight = 0);
  36111. /** This method is called when the user tries to close the window.
  36112. This is triggered by the user clicking the close button, or using some other
  36113. OS-specific key shortcut or OS menu for getting rid of a window.
  36114. If the window is just a pop-up, you should override this closeButtonPressed()
  36115. method and make it delete the window in whatever way is appropriate for your
  36116. app. E.g. you might just want to call "delete this".
  36117. If your app is centred around this window such that the whole app should quit when
  36118. the window is closed, then you will probably want to use this method as an opportunity
  36119. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  36120. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  36121. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  36122. or closing it via the taskbar icon on Windows).
  36123. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  36124. redirects it to call this method, so any methods of closing the window that are
  36125. caught by userTriedToCloseWindow() will also end up here).
  36126. */
  36127. virtual void closeButtonPressed();
  36128. /** Callback that is triggered when the minimise button is pressed.
  36129. The default implementation of this calls ResizableWindow::setMinimised(), but
  36130. you can override it to do more customised behaviour.
  36131. */
  36132. virtual void minimiseButtonPressed();
  36133. /** Callback that is triggered when the maximise button is pressed, or when the
  36134. title-bar is double-clicked.
  36135. The default implementation of this calls ResizableWindow::setFullScreen(), but
  36136. you can override it to do more customised behaviour.
  36137. */
  36138. virtual void maximiseButtonPressed();
  36139. /** Returns the close button, (or 0 if there isn't one). */
  36140. Button* getCloseButton() const throw();
  36141. /** Returns the minimise button, (or 0 if there isn't one). */
  36142. Button* getMinimiseButton() const throw();
  36143. /** Returns the maximise button, (or 0 if there isn't one). */
  36144. Button* getMaximiseButton() const throw();
  36145. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36146. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36147. methods.
  36148. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36149. */
  36150. enum ColourIds
  36151. {
  36152. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  36153. and feel class how this is used. */
  36154. };
  36155. /** @internal */
  36156. void paint (Graphics& g);
  36157. /** @internal */
  36158. void resized();
  36159. /** @internal */
  36160. void lookAndFeelChanged();
  36161. /** @internal */
  36162. const BorderSize getBorderThickness();
  36163. /** @internal */
  36164. const BorderSize getContentComponentBorder();
  36165. /** @internal */
  36166. void mouseDoubleClick (const MouseEvent& e);
  36167. /** @internal */
  36168. void userTriedToCloseWindow();
  36169. /** @internal */
  36170. void activeWindowStatusChanged();
  36171. /** @internal */
  36172. int getDesktopWindowStyleFlags() const;
  36173. /** @internal */
  36174. void parentHierarchyChanged();
  36175. juce_UseDebuggingNewOperator
  36176. private:
  36177. int titleBarHeight, menuBarHeight, requiredButtons;
  36178. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  36179. Button* titleBarButtons [3];
  36180. Image* titleBarIcon;
  36181. MenuBarComponent* menuBar;
  36182. MenuBarModel* menuBarModel;
  36183. class ButtonListenerProxy : public ButtonListener
  36184. {
  36185. public:
  36186. ButtonListenerProxy();
  36187. void buttonClicked (Button* button);
  36188. DocumentWindow* owner;
  36189. } buttonListener;
  36190. int getBorderSize() const;
  36191. void repaintTitleBar();
  36192. DocumentWindow (const DocumentWindow&);
  36193. const DocumentWindow& operator= (const DocumentWindow&);
  36194. };
  36195. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36196. /********* End of inlined file: juce_DocumentWindow.h *********/
  36197. class MultiDocumentPanel;
  36198. class MDITabbedComponentInternal;
  36199. /**
  36200. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  36201. component.
  36202. It's like a normal DocumentWindow but has some extra functionality to make sure
  36203. everything works nicely inside a MultiDocumentPanel.
  36204. @see MultiDocumentPanel
  36205. */
  36206. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  36207. {
  36208. public:
  36209. /**
  36210. */
  36211. MultiDocumentPanelWindow (const Colour& backgroundColour);
  36212. /** Destructor. */
  36213. ~MultiDocumentPanelWindow();
  36214. /** @internal */
  36215. void maximiseButtonPressed();
  36216. /** @internal */
  36217. void closeButtonPressed();
  36218. /** @internal */
  36219. void activeWindowStatusChanged();
  36220. /** @internal */
  36221. void broughtToFront();
  36222. juce_UseDebuggingNewOperator
  36223. private:
  36224. void updateOrder();
  36225. MultiDocumentPanel* getOwner() const throw();
  36226. };
  36227. /**
  36228. A component that contains a set of other components either in floating windows
  36229. or tabs.
  36230. This acts as a panel that can be used to hold a set of open document windows, with
  36231. different layout modes.
  36232. Use addDocument() and closeDocument() to add or remove components from the
  36233. panel - never use any of the Component methods to access the panel's child
  36234. components directly, as these are managed internally.
  36235. */
  36236. class JUCE_API MultiDocumentPanel : public Component,
  36237. private ComponentListener
  36238. {
  36239. public:
  36240. /** Creates an empty panel.
  36241. Use addDocument() and closeDocument() to add or remove components from the
  36242. panel - never use any of the Component methods to access the panel's child
  36243. components directly, as these are managed internally.
  36244. */
  36245. MultiDocumentPanel();
  36246. /** Destructor.
  36247. When deleted, this will call closeAllDocuments (false) to make sure all its
  36248. components are deleted. If you need to make sure all documents are saved
  36249. before closing, then you should call closeAllDocuments (true) and check that
  36250. it returns true before deleting the panel.
  36251. */
  36252. ~MultiDocumentPanel();
  36253. /** Tries to close all the documents.
  36254. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36255. be called for each open document, and any of these calls fails, this method
  36256. will stop and return false, leaving some documents still open.
  36257. If checkItsOkToCloseFirst is false, then all documents will be closed
  36258. unconditionally.
  36259. @see closeDocument
  36260. */
  36261. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  36262. /** Adds a document component to the panel.
  36263. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  36264. this will fail and return false. (If it does fail, the component passed-in will not be
  36265. deleted, even if deleteWhenRemoved was set to true).
  36266. The MultiDocumentPanel will deal with creating a window border to go around your component,
  36267. so just pass in the bare content component here, no need to give it a ResizableWindow
  36268. or DocumentWindow.
  36269. @param component the component to add
  36270. @param backgroundColour the background colour to use to fill the component's
  36271. window or tab
  36272. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  36273. or closeAllDocuments(), then it will be deleted. If false, then
  36274. the caller must handle the component's deletion
  36275. */
  36276. bool addDocument (Component* const component,
  36277. const Colour& backgroundColour,
  36278. const bool deleteWhenRemoved);
  36279. /** Closes one of the documents.
  36280. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36281. be called, and if it fails, this method will return false without closing the
  36282. document.
  36283. If checkItsOkToCloseFirst is false, then the documents will be closed
  36284. unconditionally.
  36285. The component will be deleted if the deleteWhenRemoved parameter was set to
  36286. true when it was added with addDocument.
  36287. @see addDocument, closeAllDocuments
  36288. */
  36289. bool closeDocument (Component* component,
  36290. const bool checkItsOkToCloseFirst);
  36291. /** Returns the number of open document windows.
  36292. @see getDocument
  36293. */
  36294. int getNumDocuments() const throw();
  36295. /** Returns one of the open documents.
  36296. The order of the documents in this array may change when they are added, removed
  36297. or moved around.
  36298. @see getNumDocuments
  36299. */
  36300. Component* getDocument (const int index) const throw();
  36301. /** Returns the document component that is currently focused or on top.
  36302. If currently using floating windows, then this will be the component in the currently
  36303. active window, or the top component if none are active.
  36304. If it's currently in tabbed mode, then it'll return the component in the active tab.
  36305. @see setActiveDocument
  36306. */
  36307. Component* getActiveDocument() const throw();
  36308. /** Makes one of the components active and brings it to the top.
  36309. @see getActiveDocument
  36310. */
  36311. void setActiveDocument (Component* component);
  36312. /** Callback which gets invoked when the currently-active document changes. */
  36313. virtual void activeDocumentChanged();
  36314. /** Sets a limit on how many windows can be open at once.
  36315. If this is zero or less there's no limit (the default). addDocument() will fail
  36316. if this number is exceeded.
  36317. */
  36318. void setMaximumNumDocuments (const int maximumNumDocuments);
  36319. /** Sets an option to make the document fullscreen if there's only one document open.
  36320. If set to true, then if there's only one document, it'll fill the whole of this
  36321. component without tabs or a window border. If false, then tabs or a window
  36322. will always be shown, even if there's only one document. If there's more than
  36323. one document open, then this option makes no difference.
  36324. */
  36325. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  36326. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  36327. */
  36328. bool isFullscreenWhenOneDocument() const throw();
  36329. /** The different layout modes available. */
  36330. enum LayoutMode
  36331. {
  36332. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  36333. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  36334. };
  36335. /** Changes the panel's mode.
  36336. @see LayoutMode, getLayoutMode
  36337. */
  36338. void setLayoutMode (const LayoutMode newLayoutMode);
  36339. /** Returns the current layout mode. */
  36340. LayoutMode getLayoutMode() const throw() { return mode; }
  36341. /** Sets the background colour for the whole panel.
  36342. Each document has its own background colour, but this is the one used to fill the areas
  36343. behind them.
  36344. */
  36345. void setBackgroundColour (const Colour& newBackgroundColour);
  36346. /** Returns the current background colour.
  36347. @see setBackgroundColour
  36348. */
  36349. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  36350. /** A subclass must override this to say whether its currently ok for a document
  36351. to be closed.
  36352. This method is called by closeDocument() and closeAllDocuments() to indicate that
  36353. a document should be saved if possible, ready for it to be closed.
  36354. If this method returns true, then it means the document is ok and can be closed.
  36355. If it returns false, then it means that the closeDocument() method should stop
  36356. and not close.
  36357. Normally, you'd use this method to ask the user if they want to save any changes,
  36358. then return true if the save operation went ok. If the user cancelled the save
  36359. operation you could return false here to abort the close operation.
  36360. If your component is based on the FileBasedDocument class, then you'd probably want
  36361. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  36362. FileBasedDocument::savedOk
  36363. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  36364. */
  36365. virtual bool tryToCloseDocument (Component* component) = 0;
  36366. /** Creates a new window to be used for a document.
  36367. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  36368. but you might want to override it to return a custom component.
  36369. */
  36370. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  36371. /** @internal */
  36372. void paint (Graphics& g);
  36373. /** @internal */
  36374. void resized();
  36375. /** @internal */
  36376. void componentNameChanged (Component&);
  36377. juce_UseDebuggingNewOperator
  36378. private:
  36379. LayoutMode mode;
  36380. Array <Component*> components;
  36381. TabbedComponent* tabComponent;
  36382. Colour backgroundColour;
  36383. int maximumNumDocuments, numDocsBeforeTabsUsed;
  36384. friend class MultiDocumentPanelWindow;
  36385. friend class MDITabbedComponentInternal;
  36386. Component* getContainerComp (Component* c) const;
  36387. void updateOrder();
  36388. void addWindow (Component* component);
  36389. };
  36390. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36391. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  36392. #endif
  36393. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36394. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  36395. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36396. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36397. /** An object that watches for any movement of a component or any of its parent components.
  36398. This makes it easy to check when a component is moved relative to its top-level
  36399. peer window. The normal Component::moved() method is only called when a component
  36400. moves relative to its immediate parent, and sometimes you want to know if any of
  36401. components higher up the tree have moved (which of course will affect the overall
  36402. position of all their sub-components).
  36403. It also includes a callback that lets you know when the top-level peer is changed.
  36404. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  36405. because they need to keep their custom windows in the right place and respond to
  36406. changes in the peer.
  36407. */
  36408. class JUCE_API ComponentMovementWatcher : public ComponentListener
  36409. {
  36410. public:
  36411. /** Creates a ComponentMovementWatcher to watch a given target component. */
  36412. ComponentMovementWatcher (Component* const component);
  36413. /** Destructor. */
  36414. ~ComponentMovementWatcher();
  36415. /** This callback happens when the component that is being watched is moved
  36416. relative to its top-level peer window, or when it is resized.
  36417. */
  36418. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  36419. /** This callback happens when the component's top-level peer is changed.
  36420. */
  36421. virtual void componentPeerChanged() = 0;
  36422. juce_UseDebuggingNewOperator
  36423. /** @internal */
  36424. void componentParentHierarchyChanged (Component& component);
  36425. /** @internal */
  36426. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36427. private:
  36428. Component* const component;
  36429. ComponentPeer* lastPeer;
  36430. VoidArray registeredParentComps;
  36431. bool reentrant;
  36432. int lastX, lastY, lastWidth, lastHeight;
  36433. #ifdef JUCE_DEBUG
  36434. ComponentDeletionWatcher* deletionWatcher;
  36435. #endif
  36436. void unregister() throw();
  36437. void registerWithParentComps() throw();
  36438. ComponentMovementWatcher (const ComponentMovementWatcher&);
  36439. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  36440. };
  36441. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36442. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  36443. #endif
  36444. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36445. #endif
  36446. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  36447. #endif
  36448. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36449. #endif
  36450. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36451. #endif
  36452. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36453. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  36454. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36455. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36456. /**
  36457. For laying out a set of components, where the components have preferred sizes
  36458. and size limits, but where they are allowed to stretch to fill the available
  36459. space.
  36460. For example, if you have a component containing several other components, and
  36461. each one should be given a share of the total size, you could use one of these
  36462. to resize the child components when the parent component is resized. Then
  36463. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  36464. A StretchableLayoutManager operates only in one dimension, so if you have a set
  36465. of components stacked vertically on top of each other, you'd use one to manage their
  36466. heights. To build up complex arrangements of components, e.g. for applications
  36467. with multiple nested panels, you would use more than one StretchableLayoutManager.
  36468. E.g. by using two (one vertical, one horizontal), you could create a resizable
  36469. spreadsheet-style table.
  36470. E.g.
  36471. @code
  36472. class MyComp : public Component
  36473. {
  36474. StretchableLayoutManager myLayout;
  36475. MyComp()
  36476. {
  36477. myLayout.setItemLayout (0, // for item 0
  36478. 50, 100, // must be between 50 and 100 pixels in size
  36479. -0.6); // and its preferred size is 60% of the total available space
  36480. myLayout.setItemLayout (1, // for item 1
  36481. -0.2, -0.6, // size must be between 20% and 60% of the available space
  36482. 50); // and its preferred size is 50 pixels
  36483. }
  36484. void resized()
  36485. {
  36486. // make a list of two of our child components that we want to reposition
  36487. Component* comps[] = { myComp1, myComp2 };
  36488. // this will position the 2 components, one above the other, to fit
  36489. // vertically into the rectangle provided.
  36490. myLayout.layOutComponents (comps, 2,
  36491. 0, 0, getWidth(), getHeight(),
  36492. true);
  36493. }
  36494. };
  36495. @endcode
  36496. @see StretchableLayoutResizerBar
  36497. */
  36498. class JUCE_API StretchableLayoutManager
  36499. {
  36500. public:
  36501. /** Creates an empty layout.
  36502. You'll need to add some item properties to the layout before it can be used
  36503. to resize things - see setItemLayout().
  36504. */
  36505. StretchableLayoutManager();
  36506. /** Destructor. */
  36507. ~StretchableLayoutManager();
  36508. /** For a numbered item, this sets its size limits and preferred size.
  36509. @param itemIndex the index of the item to change.
  36510. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36511. indicates an absolute size in pixels. A negative number indicates a
  36512. proportion of the available space (e.g -0.5 is 50%)
  36513. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36514. indicates an absolute size in pixels. A negative number indicates a
  36515. proportion of the available space
  36516. @param preferredSize the size that this item would like to be, if there's enough room. A
  36517. positive number indicates an absolute size in pixels. A negative number
  36518. indicates a proportion of the available space
  36519. @see getItemLayout
  36520. */
  36521. void setItemLayout (const int itemIndex,
  36522. const double minimumSize,
  36523. const double maximumSize,
  36524. const double preferredSize);
  36525. /** For a numbered item, this returns its size limits and preferred size.
  36526. @param itemIndex the index of the item.
  36527. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36528. indicates an absolute size in pixels. A negative number indicates a
  36529. proportion of the available space (e.g -0.5 is 50%)
  36530. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36531. indicates an absolute size in pixels. A negative number indicates a
  36532. proportion of the available space
  36533. @param preferredSize the size that this item would like to be, if there's enough room. A
  36534. positive number indicates an absolute size in pixels. A negative number
  36535. indicates a proportion of the available space
  36536. @returns false if the item's properties hadn't been set
  36537. @see setItemLayout
  36538. */
  36539. bool getItemLayout (const int itemIndex,
  36540. double& minimumSize,
  36541. double& maximumSize,
  36542. double& preferredSize) const;
  36543. /** Clears all the properties that have been set with setItemLayout() and resets
  36544. this object to its initial state.
  36545. */
  36546. void clearAllItems();
  36547. /** Takes a set of components that correspond to the layout's items, and positions
  36548. them to fill a space.
  36549. This will try to give each item its preferred size, whether that's a relative size
  36550. or an absolute one.
  36551. @param components an array of components that correspond to each of the
  36552. numbered items that the StretchableLayoutManager object
  36553. has been told about with setItemLayout()
  36554. @param numComponents the number of components in the array that is passed-in. This
  36555. should be the same as the number of items this object has been
  36556. told about.
  36557. @param x the left of the rectangle in which the components should
  36558. be laid out
  36559. @param y the top of the rectangle in which the components should
  36560. be laid out
  36561. @param width the width of the rectangle in which the components should
  36562. be laid out
  36563. @param height the height of the rectangle in which the components should
  36564. be laid out
  36565. @param vertically if true, the components will be positioned in a vertical stack,
  36566. so that they fill the height of the rectangle. If false, they
  36567. will be placed side-by-side in a horizontal line, filling the
  36568. available width
  36569. @param resizeOtherDimension if true, this means that the components will have their
  36570. other dimension resized to fit the space - i.e. if the 'vertically'
  36571. parameter is true, their x-positions and widths are adjusted to fit
  36572. the x and width parameters; if 'vertically' is false, their y-positions
  36573. and heights are adjusted to fit the y and height parameters.
  36574. */
  36575. void layOutComponents (Component** const components,
  36576. int numComponents,
  36577. int x, int y, int width, int height,
  36578. const bool vertically,
  36579. const bool resizeOtherDimension);
  36580. /** Returns the current position of one of the items.
  36581. This is only a valid call after layOutComponents() has been called, as it
  36582. returns the last position that this item was placed at. If the layout was
  36583. vertical, the value returned will be the y position of the top of the item,
  36584. relative to the top of the rectangle in which the items were placed (so for
  36585. example, item 0 will always have position of 0, even in the rectangle passed
  36586. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  36587. the position returned is the item's left-hand position, again relative to the
  36588. x position of the rectangle used.
  36589. @see getItemCurrentSize, setItemPosition
  36590. */
  36591. int getItemCurrentPosition (const int itemIndex) const;
  36592. /** Returns the current size of one of the items.
  36593. This is only meaningful after layOutComponents() has been called, as it
  36594. returns the last size that this item was given. If the layout was done
  36595. vertically, it'll return the item's height in pixels; if it was horizontal,
  36596. it'll return its width.
  36597. @see getItemCurrentRelativeSize
  36598. */
  36599. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36600. /** Returns the current size of one of the items.
  36601. This is only meaningful after layOutComponents() has been called, as it
  36602. returns the last size that this item was given. If the layout was done
  36603. vertically, it'll return a negative value representing the item's height relative
  36604. to the last size used for laying the components out; if the layout was done
  36605. horizontally it'll be the proportion of its width.
  36606. @see getItemCurrentAbsoluteSize
  36607. */
  36608. double getItemCurrentRelativeSize (const int itemIndex) const;
  36609. /** Moves one of the items, shifting along any other items as necessary in
  36610. order to get it to the desired position.
  36611. Calling this method will also update the preferred sizes of the items it
  36612. shuffles along, so that they reflect their new positions.
  36613. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36614. about when it's dragged).
  36615. @param itemIndex the item to move
  36616. @param newPosition the absolute position that you'd like this item to move
  36617. to. The item might not be able to always reach exactly this position,
  36618. because other items may have minimum sizes that constrain how
  36619. far it can go
  36620. */
  36621. void setItemPosition (const int itemIndex,
  36622. int newPosition);
  36623. juce_UseDebuggingNewOperator
  36624. private:
  36625. struct ItemLayoutProperties
  36626. {
  36627. int itemIndex;
  36628. int currentSize;
  36629. double minSize, maxSize, preferredSize;
  36630. };
  36631. OwnedArray <ItemLayoutProperties> items;
  36632. int totalSize;
  36633. static int sizeToRealSize (double size, int totalSpace);
  36634. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36635. void setTotalSize (const int newTotalSize);
  36636. int fitComponentsIntoSpace (const int startIndex,
  36637. const int endIndex,
  36638. const int availableSpace,
  36639. int startPos);
  36640. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36641. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36642. void updatePrefSizesToMatchCurrentPositions();
  36643. StretchableLayoutManager (const StretchableLayoutManager&);
  36644. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36645. };
  36646. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36647. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36648. #endif
  36649. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36650. #endif
  36651. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36652. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36653. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36654. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36655. /**
  36656. A component that acts as one of the vertical or horizontal bars you see being
  36657. used to resize panels in a window.
  36658. One of these acts with a StretchableLayoutManager to resize the other components.
  36659. @see StretchableLayoutManager
  36660. */
  36661. class JUCE_API StretchableLayoutResizerBar : public Component
  36662. {
  36663. public:
  36664. /** Creates a resizer bar for use on a specified layout.
  36665. @param layoutToUse the layout that will be affected when this bar
  36666. is dragged
  36667. @param itemIndexInLayout the item index in the layout that corresponds to
  36668. this bar component. You'll need to set up the item
  36669. properties in a suitable way for a divider bar, e.g.
  36670. for an 8-pixel wide bar which, you could call
  36671. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36672. @param isBarVertical true if it's an upright bar that you drag left and
  36673. right; false for a horizontal one that you drag up and
  36674. down
  36675. */
  36676. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36677. const int itemIndexInLayout,
  36678. const bool isBarVertical);
  36679. /** Destructor. */
  36680. ~StretchableLayoutResizerBar();
  36681. /** This is called when the bar is dragged.
  36682. This method must update the positions of any components whose position is
  36683. determined by the StretchableLayoutManager, because they might have just
  36684. moved.
  36685. The default implementation calls the resized() method of this component's
  36686. parent component, because that's often where you're likely to apply the
  36687. layout, but it can be overridden for more specific needs.
  36688. */
  36689. virtual void hasBeenMoved();
  36690. /** @internal */
  36691. void paint (Graphics& g);
  36692. /** @internal */
  36693. void mouseDown (const MouseEvent& e);
  36694. /** @internal */
  36695. void mouseDrag (const MouseEvent& e);
  36696. juce_UseDebuggingNewOperator
  36697. private:
  36698. StretchableLayoutManager* layout;
  36699. int itemIndex, mouseDownPos;
  36700. bool isVertical;
  36701. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36702. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36703. };
  36704. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36705. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36706. #endif
  36707. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36708. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36709. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36710. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36711. /**
  36712. A utility class for fitting a set of objects whose sizes can vary between
  36713. a minimum and maximum size, into a space.
  36714. This is a trickier algorithm than it would first seem, so I've put it in this
  36715. class to allow it to be shared by various bits of code.
  36716. To use it, create one of these objects, call addItem() to add the list of items
  36717. you need, then call resizeToFit(), which will change all their sizes. You can
  36718. then retrieve the new sizes with getItemSize() and getNumItems().
  36719. It's currently used by the TableHeaderComponent for stretching out the table
  36720. headings to fill the table's width.
  36721. */
  36722. class StretchableObjectResizer
  36723. {
  36724. public:
  36725. /** Creates an empty object resizer. */
  36726. StretchableObjectResizer();
  36727. /** Destructor. */
  36728. ~StretchableObjectResizer();
  36729. /** Adds an item to the list.
  36730. The order parameter lets you specify groups of items that are resized first when some
  36731. space needs to be found. Those items with an order of 0 will be the first ones to be
  36732. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36733. will then try resizing the items with an order of 1, then 2, and so on.
  36734. */
  36735. void addItem (const double currentSize,
  36736. const double minSize,
  36737. const double maxSize,
  36738. const int order = 0);
  36739. /** Resizes all the items to fit this amount of space.
  36740. This will attempt to fit them in without exceeding each item's miniumum and
  36741. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36742. further, the final size may be greater or less than the size passed in.
  36743. After calling this method, you can retrieve the new sizes with the getItemSize()
  36744. method.
  36745. */
  36746. void resizeToFit (const double targetSize);
  36747. /** Returns the number of items that have been added. */
  36748. int getNumItems() const throw() { return items.size(); }
  36749. /** Returns the size of one of the items. */
  36750. double getItemSize (const int index) const throw();
  36751. juce_UseDebuggingNewOperator
  36752. private:
  36753. struct Item
  36754. {
  36755. double size;
  36756. double minSize;
  36757. double maxSize;
  36758. int order;
  36759. };
  36760. OwnedArray <Item> items;
  36761. StretchableObjectResizer (const StretchableObjectResizer&);
  36762. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36763. };
  36764. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36765. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36766. #endif
  36767. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36768. #endif
  36769. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  36770. #endif
  36771. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36772. #endif
  36773. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36774. /********* Start of inlined file: juce_GroupComponent.h *********/
  36775. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36776. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36777. /**
  36778. A component that draws an outline around itself and has an optional title at
  36779. the top, for drawing an outline around a group of controls.
  36780. */
  36781. class JUCE_API GroupComponent : public Component
  36782. {
  36783. public:
  36784. /** Creates a GroupComponent.
  36785. @param componentName the name to give the component
  36786. @param labelText the text to show at the top of the outline
  36787. */
  36788. GroupComponent (const String& componentName,
  36789. const String& labelText);
  36790. /** Destructor. */
  36791. ~GroupComponent();
  36792. /** Changes the text that's shown at the top of the component. */
  36793. void setText (const String& newText) throw();
  36794. /** Returns the currently displayed text label. */
  36795. const String getText() const throw();
  36796. /** Sets the positioning of the text label.
  36797. (The default is Justification::left)
  36798. @see getTextLabelPosition
  36799. */
  36800. void setTextLabelPosition (const Justification& justification);
  36801. /** Returns the current text label position.
  36802. @see setTextLabelPosition
  36803. */
  36804. const Justification getTextLabelPosition() const throw() { return justification; }
  36805. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36806. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36807. methods.
  36808. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36809. */
  36810. enum ColourIds
  36811. {
  36812. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  36813. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  36814. };
  36815. /** @internal */
  36816. void paint (Graphics& g);
  36817. /** @internal */
  36818. void enablementChanged();
  36819. /** @internal */
  36820. void colourChanged();
  36821. private:
  36822. String text;
  36823. Justification justification;
  36824. GroupComponent (const GroupComponent&);
  36825. const GroupComponent& operator= (const GroupComponent&);
  36826. };
  36827. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36828. /********* End of inlined file: juce_GroupComponent.h *********/
  36829. #endif
  36830. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36831. /********* Start of inlined file: juce_FilenameComponent.h *********/
  36832. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36833. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36834. class FilenameComponent;
  36835. /**
  36836. Listens for events happening to a FilenameComponent.
  36837. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  36838. register one of these objects for event callbacks when the filename is changed.
  36839. @See FilenameComponent
  36840. */
  36841. class JUCE_API FilenameComponentListener
  36842. {
  36843. public:
  36844. /** Destructor. */
  36845. virtual ~FilenameComponentListener() {}
  36846. /** This method is called after the FilenameComponent's file has been changed. */
  36847. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  36848. };
  36849. /**
  36850. Shows a filename as an editable text box, with a 'browse' button and a
  36851. drop-down list for recently selected files.
  36852. A handy component for dialogue boxes where you want the user to be able to
  36853. select a file or directory.
  36854. Attach an FilenameComponentListener using the addListener() method, and it will
  36855. get called each time the user changes the filename, either by browsing for a file
  36856. and clicking 'ok', or by typing a new filename into the box and pressing return.
  36857. @see FileChooser, ComboBox
  36858. */
  36859. class JUCE_API FilenameComponent : public Component,
  36860. public SettableTooltipClient,
  36861. public FileDragAndDropTarget,
  36862. private AsyncUpdater,
  36863. private ButtonListener,
  36864. private ComboBoxListener
  36865. {
  36866. public:
  36867. /** Creates a FilenameComponent.
  36868. @param name the name for this component.
  36869. @param currentFile the file to initially show in the box
  36870. @param canEditFilename if true, the user can manually edit the filename; if false,
  36871. they can only change it by browsing for a new file
  36872. @param isDirectory if true, the file will be treated as a directory, and
  36873. an appropriate directory browser used
  36874. @param isForSaving if true, the file browser will allow non-existent files to
  36875. be picked, as the file is assumed to be used for saving rather
  36876. than loading
  36877. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  36878. If an empty string is passed in, then the pattern is assumed to be "*"
  36879. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  36880. to any filenames that are entered or chosen
  36881. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  36882. will only appear if the initial file isn't valid)
  36883. */
  36884. FilenameComponent (const String& name,
  36885. const File& currentFile,
  36886. const bool canEditFilename,
  36887. const bool isDirectory,
  36888. const bool isForSaving,
  36889. const String& fileBrowserWildcard,
  36890. const String& enforcedSuffix,
  36891. const String& textWhenNothingSelected);
  36892. /** Destructor. */
  36893. ~FilenameComponent();
  36894. /** Returns the currently displayed filename. */
  36895. const File getCurrentFile() const;
  36896. /** Changes the current filename.
  36897. If addToRecentlyUsedList is true, the filename will also be added to the
  36898. drop-down list of recent files.
  36899. If sendChangeNotification is false, then the listeners won't be told of the
  36900. change.
  36901. */
  36902. void setCurrentFile (File newFile,
  36903. const bool addToRecentlyUsedList,
  36904. const bool sendChangeNotification = true);
  36905. /** Changes whether the use can type into the filename box.
  36906. */
  36907. void setFilenameIsEditable (const bool shouldBeEditable);
  36908. /** Sets a file or directory to be the default starting point for the browser to show.
  36909. This is only used if the current file hasn't been set.
  36910. */
  36911. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  36912. /** Returns all the entries on the recent files list.
  36913. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  36914. state of this list.
  36915. @see setRecentlyUsedFilenames
  36916. */
  36917. const StringArray getRecentlyUsedFilenames() const;
  36918. /** Sets all the entries on the recent files list.
  36919. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  36920. state of this list.
  36921. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  36922. */
  36923. void setRecentlyUsedFilenames (const StringArray& filenames);
  36924. /** Adds an entry to the recently-used files dropdown list.
  36925. If the file is already in the list, it will be moved to the top. A limit
  36926. is also placed on the number of items that are kept in the list.
  36927. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  36928. */
  36929. void addRecentlyUsedFile (const File& file);
  36930. /** Changes the limit for the number of files that will be stored in the recent-file list.
  36931. */
  36932. void setMaxNumberOfRecentFiles (const int newMaximum);
  36933. /** Changes the text shown on the 'browse' button.
  36934. By default this button just says "..." but you can change it. The button itself
  36935. can be changed using the look-and-feel classes, so it might not actually have any
  36936. text on it.
  36937. */
  36938. void setBrowseButtonText (const String& browseButtonText);
  36939. /** Adds a listener that will be called when the selected file is changed. */
  36940. void addListener (FilenameComponentListener* const listener) throw();
  36941. /** Removes a previously-registered listener. */
  36942. void removeListener (FilenameComponentListener* const listener) throw();
  36943. /** Gives the component a tooltip. */
  36944. void setTooltip (const String& newTooltip);
  36945. /** @internal */
  36946. void paintOverChildren (Graphics& g);
  36947. /** @internal */
  36948. void resized();
  36949. /** @internal */
  36950. void lookAndFeelChanged();
  36951. /** @internal */
  36952. bool isInterestedInFileDrag (const StringArray& files);
  36953. /** @internal */
  36954. void filesDropped (const StringArray& files, int, int);
  36955. /** @internal */
  36956. void fileDragEnter (const StringArray& files, int, int);
  36957. /** @internal */
  36958. void fileDragExit (const StringArray& files);
  36959. juce_UseDebuggingNewOperator
  36960. private:
  36961. ComboBox* filenameBox;
  36962. String lastFilename;
  36963. Button* browseButton;
  36964. int maxRecentFiles;
  36965. bool isDir, isSaving, isFileDragOver;
  36966. String wildcard, enforcedSuffix, browseButtonText;
  36967. SortedSet <void*> listeners;
  36968. File defaultBrowseFile;
  36969. void comboBoxChanged (ComboBox*);
  36970. void buttonClicked (Button* button);
  36971. void handleAsyncUpdate();
  36972. FilenameComponent (const FilenameComponent&);
  36973. const FilenameComponent& operator= (const FilenameComponent&);
  36974. };
  36975. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  36976. /********* End of inlined file: juce_FilenameComponent.h *********/
  36977. #endif
  36978. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36979. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  36980. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36981. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36982. /**
  36983. Base class for components that live inside a file chooser dialog box and
  36984. show previews of the files that get selected.
  36985. One of these allows special extra information to be displayed for files
  36986. in a dialog box as the user selects them. Each time the current file or
  36987. directory is changed, the selectedFileChanged() method will be called
  36988. to allow it to update itself appropriately.
  36989. @see FileChooser, ImagePreviewComponent
  36990. */
  36991. class JUCE_API FilePreviewComponent : public Component
  36992. {
  36993. public:
  36994. /** Creates a FilePreviewComponent. */
  36995. FilePreviewComponent();
  36996. /** Destructor. */
  36997. ~FilePreviewComponent();
  36998. /** Called to indicate that the user's currently selected file has changed.
  36999. @param newSelectedFile the newly selected file or directory, which may be
  37000. File::nonexistent if none is selected.
  37001. */
  37002. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  37003. juce_UseDebuggingNewOperator
  37004. private:
  37005. FilePreviewComponent (const FilePreviewComponent&);
  37006. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  37007. };
  37008. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37009. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  37010. #endif
  37011. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37012. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37013. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37014. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37015. /**
  37016. Shows a set of file paths in a list, allowing them to be added, removed or
  37017. re-ordered.
  37018. @see FileSearchPath
  37019. */
  37020. class JUCE_API FileSearchPathListComponent : public Component,
  37021. public SettableTooltipClient,
  37022. public FileDragAndDropTarget,
  37023. private ButtonListener,
  37024. private ListBoxModel
  37025. {
  37026. public:
  37027. /** Creates an empty FileSearchPathListComponent.
  37028. */
  37029. FileSearchPathListComponent();
  37030. /** Destructor. */
  37031. ~FileSearchPathListComponent();
  37032. /** Returns the path as it is currently shown. */
  37033. const FileSearchPath& getPath() const throw() { return path; }
  37034. /** Changes the current path. */
  37035. void setPath (const FileSearchPath& newPath);
  37036. /** Sets a file or directory to be the default starting point for the browser to show.
  37037. This is only used if the current file hasn't been set.
  37038. */
  37039. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37040. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37041. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37042. methods.
  37043. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37044. */
  37045. enum ColourIds
  37046. {
  37047. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37048. Make this transparent if you don't want the background to be filled. */
  37049. };
  37050. /** @internal */
  37051. int getNumRows();
  37052. /** @internal */
  37053. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37054. /** @internal */
  37055. void deleteKeyPressed (int lastRowSelected);
  37056. /** @internal */
  37057. void returnKeyPressed (int lastRowSelected);
  37058. /** @internal */
  37059. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37060. /** @internal */
  37061. void selectedRowsChanged (int lastRowSelected);
  37062. /** @internal */
  37063. void resized();
  37064. /** @internal */
  37065. void paint (Graphics& g);
  37066. /** @internal */
  37067. bool isInterestedInFileDrag (const StringArray& files);
  37068. /** @internal */
  37069. void filesDropped (const StringArray& files, int, int);
  37070. /** @internal */
  37071. void buttonClicked (Button* button);
  37072. juce_UseDebuggingNewOperator
  37073. private:
  37074. FileSearchPath path;
  37075. File defaultBrowseTarget;
  37076. ListBox* listBox;
  37077. Button* addButton;
  37078. Button* removeButton;
  37079. Button* changeButton;
  37080. Button* upButton;
  37081. Button* downButton;
  37082. void changed() throw();
  37083. void updateButtons() throw();
  37084. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37085. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37086. };
  37087. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37088. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37089. #endif
  37090. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37091. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37092. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37093. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37094. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37095. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37096. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37097. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  37098. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37099. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37100. /********* Start of inlined file: juce_FileFilter.h *********/
  37101. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37102. #define __JUCE_FILEFILTER_JUCEHEADER__
  37103. /**
  37104. Interface for deciding which files are suitable for something.
  37105. For example, this is used by DirectoryContentsList to select which files
  37106. go into the list.
  37107. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37108. */
  37109. class JUCE_API FileFilter
  37110. {
  37111. public:
  37112. /** Creates a filter with the given description.
  37113. The description can be returned later with the getDescription() method.
  37114. */
  37115. FileFilter (const String& filterDescription);
  37116. /** Destructor. */
  37117. virtual ~FileFilter();
  37118. /** Returns the description that the filter was created with. */
  37119. const String& getDescription() const throw();
  37120. /** Should return true if this file is suitable for inclusion in whatever context
  37121. the object is being used.
  37122. */
  37123. virtual bool isFileSuitable (const File& file) const = 0;
  37124. /** Should return true if this directory is suitable for inclusion in whatever context
  37125. the object is being used.
  37126. */
  37127. virtual bool isDirectorySuitable (const File& file) const = 0;
  37128. protected:
  37129. String description;
  37130. };
  37131. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  37132. /********* End of inlined file: juce_FileFilter.h *********/
  37133. /**
  37134. A class to asynchronously scan for details about the files in a directory.
  37135. This keeps a list of files and some information about them, using a background
  37136. thread to scan for more files. As files are found, it broadcasts change messages
  37137. to tell any listeners.
  37138. @see FileListComponent, FileBrowserComponent
  37139. */
  37140. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  37141. public TimeSliceClient
  37142. {
  37143. public:
  37144. /** Creates a directory list.
  37145. To set the directory it should point to, use setDirectory(), which will
  37146. also start it scanning for files on the background thread.
  37147. When the background thread finds and adds new files to this list, the
  37148. ChangeBroadcaster class will send a change message, so you can register
  37149. listeners and update them when the list changes.
  37150. @param fileFilter an optional filter to select which files are
  37151. included in the list. If this is 0, then all files
  37152. and directories are included. Make sure that the
  37153. filter doesn't get deleted during the lifetime of this
  37154. object
  37155. @param threadToUse a thread object that this list can use
  37156. to scan for files as a background task. Make sure
  37157. that the thread you give it has been started, or you
  37158. won't get any files!
  37159. */
  37160. DirectoryContentsList (const FileFilter* const fileFilter,
  37161. TimeSliceThread& threadToUse);
  37162. /** Destructor. */
  37163. ~DirectoryContentsList();
  37164. /** Sets the directory to look in for files.
  37165. If the directory that's passed in is different to the current one, this will
  37166. also start the background thread scanning it for files.
  37167. */
  37168. void setDirectory (const File& directory,
  37169. const bool includeDirectories,
  37170. const bool includeFiles);
  37171. /** Returns the directory that's currently being used. */
  37172. const File& getDirectory() const throw();
  37173. /** Clears the list, and stops the thread scanning for files. */
  37174. void clear();
  37175. /** Clears the list and restarts scanning the directory for files. */
  37176. void refresh();
  37177. /** True if the background thread hasn't yet finished scanning for files. */
  37178. bool isStillLoading() const;
  37179. /** Tells the list whether or not to ignore hidden files.
  37180. By default these are ignored.
  37181. */
  37182. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  37183. /** Contains cached information about one of the files in a DirectoryContentsList.
  37184. */
  37185. struct FileInfo
  37186. {
  37187. /** The filename.
  37188. This isn't a full pathname, it's just the last part of the path, same as you'd
  37189. get from File::getFileName().
  37190. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  37191. */
  37192. String filename;
  37193. /** File size in bytes. */
  37194. int64 fileSize;
  37195. /** File modification time.
  37196. As supplied by File::getLastModificationTime().
  37197. */
  37198. Time modificationTime;
  37199. /** File creation time.
  37200. As supplied by File::getCreationTime().
  37201. */
  37202. Time creationTime;
  37203. /** True if the file is a directory. */
  37204. bool isDirectory;
  37205. /** True if the file is read-only. */
  37206. bool isReadOnly;
  37207. };
  37208. /** Returns the number of files currently available in the list.
  37209. The info about one of these files can be retrieved with getFileInfo() or
  37210. getFile().
  37211. Obviously as the background thread runs and scans the directory for files, this
  37212. number will change.
  37213. @see getFileInfo, getFile
  37214. */
  37215. int getNumFiles() const;
  37216. /** Returns the cached information about one of the files in the list.
  37217. If the index is in-range, this will return true and will copy the file's details
  37218. to the structure that is passed-in.
  37219. If it returns false, then the index wasn't in range, and the structure won't
  37220. be affected.
  37221. @see getNumFiles, getFile
  37222. */
  37223. bool getFileInfo (const int index,
  37224. FileInfo& resultInfo) const;
  37225. /** Returns one of the files in the list.
  37226. @param index should be less than getNumFiles(). If this is out-of-range, the
  37227. return value will be File::nonexistent
  37228. @see getNumFiles, getFileInfo
  37229. */
  37230. const File getFile (const int index) const;
  37231. /** Returns the file filter being used.
  37232. The filter is specified in the constructor.
  37233. */
  37234. const FileFilter* getFilter() const throw() { return fileFilter; }
  37235. /** @internal */
  37236. bool useTimeSlice();
  37237. /** @internal */
  37238. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  37239. /** @internal */
  37240. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  37241. const DirectoryContentsList::FileInfo* const second) throw();
  37242. juce_UseDebuggingNewOperator
  37243. private:
  37244. File root;
  37245. const FileFilter* fileFilter;
  37246. TimeSliceThread& thread;
  37247. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  37248. CriticalSection fileListLock;
  37249. OwnedArray <FileInfo> files;
  37250. void* volatile fileFindHandle;
  37251. bool volatile shouldStop;
  37252. void changed();
  37253. bool checkNextFile (bool& hasChanged);
  37254. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  37255. const int64 fileSize, const Time& modTime,
  37256. const Time& creationTime, const bool isReadOnly);
  37257. DirectoryContentsList (const DirectoryContentsList&);
  37258. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  37259. };
  37260. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37261. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  37262. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  37263. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37264. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37265. /**
  37266. A listener for user selection events in a file browser.
  37267. This is used by a FileBrowserComponent or FileListComponent.
  37268. */
  37269. class JUCE_API FileBrowserListener
  37270. {
  37271. public:
  37272. /** Destructor. */
  37273. virtual ~FileBrowserListener();
  37274. /** Callback when the user selects a different file in the browser. */
  37275. virtual void selectionChanged() = 0;
  37276. /** Callback when the user clicks on a file in the browser. */
  37277. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  37278. /** Callback when the user double-clicks on a file in the browser. */
  37279. virtual void fileDoubleClicked (const File& file) = 0;
  37280. };
  37281. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37282. /********* End of inlined file: juce_FileBrowserListener.h *********/
  37283. /**
  37284. A base class for components that display a list of the files in a directory.
  37285. @see DirectoryContentsList
  37286. */
  37287. class JUCE_API DirectoryContentsDisplayComponent
  37288. {
  37289. public:
  37290. /**
  37291. */
  37292. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  37293. /** Destructor. */
  37294. virtual ~DirectoryContentsDisplayComponent();
  37295. /** Returns the file that the user has currently selected.
  37296. Returns File::nonexistent if none is selected.
  37297. */
  37298. virtual const File getSelectedFile() const = 0;
  37299. /** Scrolls this view to the top. */
  37300. virtual void scrollToTop() = 0;
  37301. /** Adds a listener to be told when files are selected or clicked.
  37302. @see removeListener
  37303. */
  37304. void addListener (FileBrowserListener* const listener) throw();
  37305. /** Removes a listener.
  37306. @see addListener
  37307. */
  37308. void removeListener (FileBrowserListener* const listener) throw();
  37309. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37310. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37311. methods.
  37312. Note that you can also use the constants from TextEditor::ColourIds to change the
  37313. colour of the text editor that is opened when a label is editable.
  37314. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37315. */
  37316. enum ColourIds
  37317. {
  37318. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  37319. textColourId = 0x1000541, /**< The colour for the text. */
  37320. };
  37321. /** @internal */
  37322. void sendSelectionChangeMessage();
  37323. /** @internal */
  37324. void sendDoubleClickMessage (const File& file);
  37325. /** @internal */
  37326. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  37327. juce_UseDebuggingNewOperator
  37328. protected:
  37329. DirectoryContentsList& fileList;
  37330. SortedSet <void*> listeners;
  37331. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  37332. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  37333. };
  37334. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37335. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37336. /**
  37337. A component that displays the files in a directory as a treeview.
  37338. This implements the DirectoryContentsDisplayComponent base class so that
  37339. it can be used in a FileBrowserComponent.
  37340. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37341. class and the FileBrowserListener class.
  37342. @see DirectoryContentsList, FileListComponent
  37343. */
  37344. class JUCE_API FileTreeComponent : public TreeView,
  37345. public DirectoryContentsDisplayComponent
  37346. {
  37347. public:
  37348. /** Creates a listbox to show the contents of a specified directory.
  37349. */
  37350. FileTreeComponent (DirectoryContentsList& listToShow);
  37351. /** Destructor. */
  37352. ~FileTreeComponent();
  37353. /** Returns the number of selected files in the tree.
  37354. */
  37355. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37356. /** Returns one of the files that the user has currently selected.
  37357. Returns File::nonexistent if none is selected.
  37358. */
  37359. const File getSelectedFile (int index) const throw();
  37360. /** Returns the first of the files that the user has currently selected.
  37361. Returns File::nonexistent if none is selected.
  37362. */
  37363. const File getSelectedFile() const;
  37364. /** Scrolls the list to the top. */
  37365. void scrollToTop();
  37366. /** Setting a name for this allows tree items to be dragged.
  37367. The string that you pass in here will be returned by the getDragSourceDescription()
  37368. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37369. */
  37370. void setDragAndDropDescription (const String& description) throw();
  37371. /** Returns the last value that was set by setDragAndDropDescription().
  37372. */
  37373. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37374. juce_UseDebuggingNewOperator
  37375. private:
  37376. String dragAndDropDescription;
  37377. FileTreeComponent (const FileTreeComponent&);
  37378. const FileTreeComponent& operator= (const FileTreeComponent&);
  37379. };
  37380. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37381. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37382. #endif
  37383. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37384. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37385. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37386. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37387. /**
  37388. A type of FileFilter that works by wildcard pattern matching.
  37389. This filter only allows files that match one of the specified patterns, but
  37390. allows all directories through.
  37391. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37392. */
  37393. class JUCE_API WildcardFileFilter : public FileFilter
  37394. {
  37395. public:
  37396. /**
  37397. Creates a wildcard filter for one or more patterns.
  37398. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37399. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37400. or .aiff.
  37401. The description is a name to show the user in a list of possible patterns, so
  37402. for the wav/aiff example, your description might be "audio files".
  37403. */
  37404. WildcardFileFilter (const String& wildcardPatterns,
  37405. const String& description);
  37406. /** Destructor. */
  37407. ~WildcardFileFilter();
  37408. /** Returns true if the filename matches one of the patterns specified. */
  37409. bool isFileSuitable (const File& file) const;
  37410. /** This always returns true. */
  37411. bool isDirectorySuitable (const File& file) const;
  37412. juce_UseDebuggingNewOperator
  37413. private:
  37414. StringArray wildcards;
  37415. };
  37416. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37417. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37418. #endif
  37419. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37420. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37421. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37422. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37423. /**
  37424. A simple preview component that shows thumbnails of image files.
  37425. @see FileChooserDialogBox, FilePreviewComponent
  37426. */
  37427. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37428. private Timer
  37429. {
  37430. public:
  37431. /** Creates an ImagePreviewComponent. */
  37432. ImagePreviewComponent();
  37433. /** Destructor. */
  37434. ~ImagePreviewComponent();
  37435. /** @internal */
  37436. void selectedFileChanged (const File& newSelectedFile);
  37437. /** @internal */
  37438. void paint (Graphics& g);
  37439. /** @internal */
  37440. void timerCallback();
  37441. juce_UseDebuggingNewOperator
  37442. private:
  37443. File fileToLoad;
  37444. Image* currentThumbnail;
  37445. String currentDetails;
  37446. void getThumbSize (int& w, int& h) const;
  37447. ImagePreviewComponent (const ImagePreviewComponent&);
  37448. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37449. };
  37450. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37451. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37452. #endif
  37453. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37454. #endif
  37455. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37456. #endif
  37457. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37458. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  37459. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37460. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37461. /**
  37462. A component for browsing and selecting a file or directory to open or save.
  37463. This contains a FileListComponent and adds various boxes and controls for
  37464. navigating and selecting a file. It can work in different modes so that it can
  37465. be used for loading or saving a file, or for choosing a directory.
  37466. @see FileChooserDialogBox, FileChooser, FileListComponent
  37467. */
  37468. class JUCE_API FileBrowserComponent : public Component,
  37469. public ChangeBroadcaster,
  37470. private FileBrowserListener,
  37471. private TextEditorListener,
  37472. private ButtonListener,
  37473. private ComboBoxListener
  37474. {
  37475. public:
  37476. /** Various modes that the browser can be used in.
  37477. One of these is passed into the constructor.
  37478. */
  37479. enum FileChooserMode
  37480. {
  37481. loadFileMode, /**< the component should allow the user to choose an existing
  37482. file with the intention of opening it. */
  37483. saveFileMode, /**< the component should allow the user to specify the name of
  37484. a file that will be used to save something. */
  37485. chooseDirectoryMode /**< the component should allow the user to select an existing
  37486. directory. */
  37487. };
  37488. /** Creates a FileBrowserComponent.
  37489. @param browserMode The intended purpose for the browser - see the
  37490. FileChooserMode enum for the various options
  37491. @param initialFileOrDirectory The file or directory that should be selected when
  37492. the component begins. If this is File::nonexistent,
  37493. a default directory will be chosen.
  37494. @param fileFilter an optional filter to use to determine which files
  37495. are shown. If this is 0 then all files are displayed. Note
  37496. that a pointer is kept internally to this object, so
  37497. make sure that it is not deleted before the browser object
  37498. is deleted.
  37499. @param previewComp an optional preview component that will be used to
  37500. show previews of files that the user selects
  37501. @param useTreeView if this is false, the files are shown in a list; if true,
  37502. they are shown in a treeview
  37503. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  37504. text into the filename box.
  37505. */
  37506. FileBrowserComponent (FileChooserMode browserMode,
  37507. const File& initialFileOrDirectory,
  37508. const FileFilter* fileFilter,
  37509. FilePreviewComponent* previewComp,
  37510. const bool useTreeView = false,
  37511. const bool filenameTextBoxIsReadOnly = false);
  37512. /** Destructor. */
  37513. ~FileBrowserComponent();
  37514. /**
  37515. */
  37516. const File getCurrentFile() const throw();
  37517. /** Returns true if the current file is usable.
  37518. This can be used to decide whether the user can press "ok" for the
  37519. current file. What it does depends on the mode, so for example in an "open"
  37520. mode, the current file is only valid if one has been selected and if the file
  37521. exists. In a "save" mode, a non-existent file would also be valid.
  37522. */
  37523. bool currentFileIsValid() const;
  37524. /** Returns the directory whose contents are currently being shown in the listbox. */
  37525. const File getRoot() const;
  37526. /** Changes the directory that's being shown in the listbox. */
  37527. void setRoot (const File& newRootDirectory);
  37528. /** Equivalent to pressing the "up" button to browse the parent directory. */
  37529. void goUp();
  37530. /** Refreshes the directory that's currently being listed. */
  37531. void refresh();
  37532. /** Returns the browser's current mode. */
  37533. FileChooserMode getMode() const throw() { return mode; }
  37534. /** Returns a verb to describe what should happen when the file is accepted.
  37535. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  37536. mode, it'll be "Save", etc.
  37537. */
  37538. virtual const String getActionVerb() const;
  37539. /** Adds a listener to be told when the user selects and clicks on files.
  37540. @see removeListener
  37541. */
  37542. void addListener (FileBrowserListener* const listener) throw();
  37543. /** Removes a listener.
  37544. @see addListener
  37545. */
  37546. void removeListener (FileBrowserListener* const listener) throw();
  37547. /** @internal */
  37548. void resized();
  37549. /** @internal */
  37550. void buttonClicked (Button* b);
  37551. /** @internal */
  37552. void comboBoxChanged (ComboBox*);
  37553. /** @internal */
  37554. void textEditorTextChanged (TextEditor& editor);
  37555. /** @internal */
  37556. void textEditorReturnKeyPressed (TextEditor& editor);
  37557. /** @internal */
  37558. void textEditorEscapeKeyPressed (TextEditor& editor);
  37559. /** @internal */
  37560. void textEditorFocusLost (TextEditor& editor);
  37561. /** @internal */
  37562. void selectionChanged();
  37563. /** @internal */
  37564. void fileClicked (const File& f, const MouseEvent& e);
  37565. /** @internal */
  37566. void fileDoubleClicked (const File& f);
  37567. /** @internal */
  37568. FilePreviewComponent* getPreviewComponent() const throw();
  37569. juce_UseDebuggingNewOperator
  37570. protected:
  37571. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  37572. private:
  37573. DirectoryContentsList* fileList;
  37574. FileFilter* directoriesOnlyFilter;
  37575. FileChooserMode mode;
  37576. File currentRoot;
  37577. SortedSet <void*> listeners;
  37578. DirectoryContentsDisplayComponent* fileListComponent;
  37579. FilePreviewComponent* previewComp;
  37580. ComboBox* currentPathBox;
  37581. TextEditor* filenameBox;
  37582. Button* goUpButton;
  37583. TimeSliceThread thread;
  37584. void sendListenerChangeMessage();
  37585. FileBrowserComponent (const FileBrowserComponent&);
  37586. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  37587. };
  37588. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37589. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  37590. #endif
  37591. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37592. #endif
  37593. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37594. /********* Start of inlined file: juce_FileChooser.h *********/
  37595. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37596. #define __JUCE_FILECHOOSER_JUCEHEADER__
  37597. /**
  37598. Creates a dialog box to choose a file or directory to load or save.
  37599. To use a FileChooser:
  37600. - create one (as a local stack variable is the neatest way)
  37601. - call one of its browseFor.. methods
  37602. - if this returns true, the user has selected a file, so you can retrieve it
  37603. with the getResult() method.
  37604. e.g. @code
  37605. void loadMooseFile()
  37606. {
  37607. FileChooser myChooser ("Please select the moose you want to load...",
  37608. File::getSpecialLocation (File::userHomeDirectory),
  37609. "*.moose");
  37610. if (myChooser.browseForFileToOpen())
  37611. {
  37612. File mooseFile (myChooser.getResult());
  37613. loadMoose (mooseFile);
  37614. }
  37615. }
  37616. @endcode
  37617. */
  37618. class JUCE_API FileChooser
  37619. {
  37620. public:
  37621. /** Creates a FileChooser.
  37622. After creating one of these, use one of the browseFor... methods to display it.
  37623. @param dialogBoxTitle a text string to display in the dialog box to
  37624. tell the user what's going on
  37625. @param initialFileOrDirectory the file or directory that should be selected when
  37626. the dialog box opens. If this parameter is set to
  37627. File::nonexistent, a sensible default directory
  37628. will be used instead.
  37629. @param filePatternsAllowed a set of file patterns to specify which files can be
  37630. selected - each pattern should be separated by a
  37631. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  37632. empty string means that all files are allowed
  37633. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  37634. possible; if false, then a Juce-based browser dialog
  37635. box will always be used
  37636. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  37637. */
  37638. FileChooser (const String& dialogBoxTitle,
  37639. const File& initialFileOrDirectory = File::nonexistent,
  37640. const String& filePatternsAllowed = String::empty,
  37641. const bool useOSNativeDialogBox = true);
  37642. /** Destructor. */
  37643. ~FileChooser();
  37644. /** Shows a dialog box to choose a file to open.
  37645. This will display the dialog box modally, using an "open file" mode, so that
  37646. it won't allow non-existent files or directories to be chosen.
  37647. @param previewComponent an optional component to display inside the dialog
  37648. box to show special info about the files that the user
  37649. is browsing. The component will not be deleted by this
  37650. object, so the caller must take care of it.
  37651. @returns true if the user selected a file, in which case, use the getResult()
  37652. method to find out what it was. Returns false if they cancelled instead.
  37653. @see browseForFileToSave, browseForDirectory
  37654. */
  37655. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  37656. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  37657. The files that are returned can be obtained by calling getResults(). See
  37658. browseForFileToOpen() for more info about the behaviour of this method.
  37659. */
  37660. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  37661. /** Shows a dialog box to choose a file to save.
  37662. This will display the dialog box modally, using an "save file" mode, so it
  37663. will allow non-existent files to be chosen, but not directories.
  37664. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  37665. the user if they're sure they want to overwrite a file that already
  37666. exists
  37667. @returns true if the user chose a file and pressed 'ok', in which case, use
  37668. the getResult() method to find out what the file was. Returns false
  37669. if they cancelled instead.
  37670. @see browseForFileToOpen, browseForDirectory
  37671. */
  37672. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  37673. /** Shows a dialog box to choose a directory.
  37674. This will display the dialog box modally, using an "open directory" mode, so it
  37675. will only allow directories to be returned, not files.
  37676. @returns true if the user chose a directory and pressed 'ok', in which case, use
  37677. the getResult() method to find out what they chose. Returns false
  37678. if they cancelled instead.
  37679. @see browseForFileToOpen, browseForFileToSave
  37680. */
  37681. bool browseForDirectory();
  37682. /** Returns the last file that was chosen by one of the browseFor methods.
  37683. After calling the appropriate browseFor... method, this method lets you
  37684. find out what file or directory they chose.
  37685. Note that the file returned is only valid if the browse method returned true (i.e.
  37686. if the user pressed 'ok' rather than cancelling).
  37687. If you're using a multiple-file select, then use the getResults() method instead,
  37688. to obtain the list of all files chosen.
  37689. @see getResults
  37690. */
  37691. const File getResult() const;
  37692. /** Returns a list of all the files that were chosen during the last call to a
  37693. browse method.
  37694. This array may be empty if no files were chosen, or can contain multiple entries
  37695. if multiple files were chosen.
  37696. @see getResult
  37697. */
  37698. const OwnedArray <File>& getResults() const;
  37699. juce_UseDebuggingNewOperator
  37700. private:
  37701. String title, filters;
  37702. File startingFile;
  37703. OwnedArray <File> results;
  37704. bool useNativeDialogBox;
  37705. bool showDialog (const bool isDirectory,
  37706. const bool isSave,
  37707. const bool warnAboutOverwritingExistingFiles,
  37708. const bool selectMultipleFiles,
  37709. FilePreviewComponent* const previewComponent);
  37710. static void showPlatformDialog (OwnedArray<File>& results,
  37711. const String& title,
  37712. const File& file,
  37713. const String& filters,
  37714. bool isDirectory,
  37715. bool isSave,
  37716. bool warnAboutOverwritingExistingFiles,
  37717. bool selectMultipleFiles,
  37718. FilePreviewComponent* previewComponent);
  37719. };
  37720. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  37721. /********* End of inlined file: juce_FileChooser.h *********/
  37722. #endif
  37723. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37724. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  37725. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37726. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37727. /**
  37728. A file open/save dialog box.
  37729. This is a Juce-based file dialog box; to use a native file chooser, see the
  37730. FileChooser class.
  37731. To use one of these, create it and call its show() method. e.g.
  37732. @code
  37733. {
  37734. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  37735. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37736. File::nonexistent,
  37737. &wildcardFilter,
  37738. 0);
  37739. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  37740. T("Please choose some kind of file that you want to open..."),
  37741. browser,
  37742. getLookAndFeel().alertWindowBackground);
  37743. if (dialogBox.show())
  37744. {
  37745. File selectedFile = browser.getCurrentFile();
  37746. ...
  37747. }
  37748. }
  37749. @endcode
  37750. @see FileChooser
  37751. */
  37752. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37753. public ButtonListener,
  37754. public FileBrowserListener
  37755. {
  37756. public:
  37757. /** Creates a file chooser box.
  37758. @param title the main title to show at the top of the box
  37759. @param instructions an optional longer piece of text to show below the title in
  37760. a smaller font, describing in more detail what's required.
  37761. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37762. box. Make sure you delete this after (but not before!) the
  37763. dialog box has been deleted.
  37764. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37765. if they try to select a file that already exists. (This
  37766. flag is only used when saving files)
  37767. @param backgroundColour the background colour for the top level window
  37768. @see FileBrowserComponent, FilePreviewComponent
  37769. */
  37770. FileChooserDialogBox (const String& title,
  37771. const String& instructions,
  37772. FileBrowserComponent& browserComponent,
  37773. const bool warnAboutOverwritingExistingFiles,
  37774. const Colour& backgroundColour);
  37775. /** Destructor. */
  37776. ~FileChooserDialogBox();
  37777. /** Displays and runs the dialog box modally.
  37778. This will show the box with the specified size, returning true if the user
  37779. pressed 'ok', or false if they cancelled.
  37780. Leave the width or height as 0 to use the default size
  37781. */
  37782. bool show (int width = 0,int height = 0);
  37783. /** @internal */
  37784. void buttonClicked (Button* button);
  37785. /** @internal */
  37786. void closeButtonPressed();
  37787. /** @internal */
  37788. void selectionChanged();
  37789. /** @internal */
  37790. void fileClicked (const File& file, const MouseEvent& e);
  37791. /** @internal */
  37792. void fileDoubleClicked (const File& file);
  37793. juce_UseDebuggingNewOperator
  37794. private:
  37795. class ContentComponent : public Component
  37796. {
  37797. public:
  37798. ContentComponent();
  37799. ~ContentComponent();
  37800. void paint (Graphics& g);
  37801. void resized();
  37802. String instructions;
  37803. GlyphArrangement text;
  37804. FileBrowserComponent* chooserComponent;
  37805. FilePreviewComponent* previewComponent;
  37806. TextButton* okButton;
  37807. TextButton* cancelButton;
  37808. };
  37809. ContentComponent* content;
  37810. const bool warnAboutOverwritingExistingFiles;
  37811. FileChooserDialogBox (const FileChooserDialogBox&);
  37812. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37813. };
  37814. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37815. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  37816. #endif
  37817. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37818. #endif
  37819. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37820. /********* Start of inlined file: juce_FileListComponent.h *********/
  37821. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37822. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37823. /**
  37824. A component that displays the files in a directory as a listbox.
  37825. This implements the DirectoryContentsDisplayComponent base class so that
  37826. it can be used in a FileBrowserComponent.
  37827. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37828. class and the FileBrowserListener class.
  37829. @see DirectoryContentsList, FileTreeComponent
  37830. */
  37831. class JUCE_API FileListComponent : public ListBox,
  37832. public DirectoryContentsDisplayComponent,
  37833. private ListBoxModel,
  37834. private ChangeListener
  37835. {
  37836. public:
  37837. /** Creates a listbox to show the contents of a specified directory.
  37838. */
  37839. FileListComponent (DirectoryContentsList& listToShow);
  37840. /** Destructor. */
  37841. ~FileListComponent();
  37842. /** Returns the file that the user has currently selected.
  37843. Returns File::nonexistent if none is selected.
  37844. */
  37845. const File getSelectedFile() const;
  37846. /** Scrolls to the top of the list. */
  37847. void scrollToTop();
  37848. /** @internal */
  37849. void changeListenerCallback (void*);
  37850. /** @internal */
  37851. int getNumRows();
  37852. /** @internal */
  37853. void paintListBoxItem (int, Graphics&, int, int, bool);
  37854. /** @internal */
  37855. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37856. /** @internal */
  37857. void selectedRowsChanged (int lastRowSelected);
  37858. /** @internal */
  37859. void deleteKeyPressed (int currentSelectedRow);
  37860. /** @internal */
  37861. void returnKeyPressed (int currentSelectedRow);
  37862. juce_UseDebuggingNewOperator
  37863. private:
  37864. FileListComponent (const FileListComponent&);
  37865. const FileListComponent& operator= (const FileListComponent&);
  37866. File lastDirectory;
  37867. };
  37868. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37869. /********* End of inlined file: juce_FileListComponent.h *********/
  37870. #endif
  37871. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37872. /********* Start of inlined file: juce_AlertWindow.h *********/
  37873. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37874. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37875. /** A window that displays a message and has buttons for the user to react to it.
  37876. For simple dialog boxes with just a couple of buttons on them, there are
  37877. some static methods for running these.
  37878. For more complex dialogs, an AlertWindow can be created, then it can have some
  37879. buttons and components added to it, and its runModalLoop() method is then used to
  37880. show it. The value returned by runModalLoop() shows which button the
  37881. user pressed to dismiss the box.
  37882. @see ThreadWithProgressWindow
  37883. */
  37884. class JUCE_API AlertWindow : public TopLevelWindow,
  37885. private ButtonListener
  37886. {
  37887. public:
  37888. /** The type of icon to show in the dialog box. */
  37889. enum AlertIconType
  37890. {
  37891. NoIcon, /**< No icon will be shown on the dialog box. */
  37892. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37893. user to answer a question. */
  37894. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37895. warning about something and shouldn't be ignored. */
  37896. InfoIcon /**< An icon that indicates that the dialog box is just
  37897. giving the user some information, which doesn't require
  37898. a response from them. */
  37899. };
  37900. /** Creates an AlertWindow.
  37901. @param title the headline to show at the top of the dialog box
  37902. @param message a longer, more descriptive message to show underneath the
  37903. headline
  37904. @param iconType the type of icon to display
  37905. @param associatedComponent if this is non-zero, it specifies the component that the
  37906. alert window should be associated with. Depending on the look
  37907. and feel, this might be used for positioning of the alert window.
  37908. */
  37909. AlertWindow (const String& title,
  37910. const String& message,
  37911. AlertIconType iconType,
  37912. Component* associatedComponent = 0);
  37913. /** Destroys the AlertWindow */
  37914. ~AlertWindow();
  37915. /** Returns the type of alert icon that was specified when the window
  37916. was created. */
  37917. AlertIconType getAlertType() const throw() { return alertIconType; }
  37918. /** Changes the dialog box's message.
  37919. This will also resize the window to fit the new message if required.
  37920. */
  37921. void setMessage (const String& message);
  37922. /** Adds a button to the window.
  37923. @param name the text to show on the button
  37924. @param returnValue the value that should be returned from runModalLoop()
  37925. if this is the button that the user presses.
  37926. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37927. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37928. */
  37929. void addButton (const String& name,
  37930. const int returnValue,
  37931. const KeyPress& shortcutKey1 = KeyPress(),
  37932. const KeyPress& shortcutKey2 = KeyPress());
  37933. /** Returns the number of buttons that the window currently has. */
  37934. int getNumButtons() const;
  37935. /** Adds a textbox to the window for entering strings.
  37936. @param name an internal name for the text-box. This is the name to pass to
  37937. the getTextEditorContents() method to find out what the
  37938. user typed-in.
  37939. @param initialContents a string to show in the text box when it's first shown
  37940. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37941. text-box to label it.
  37942. @param isPasswordBox if true, the text editor will display asterisks instead of
  37943. the actual text
  37944. @see getTextEditorContents
  37945. */
  37946. void addTextEditor (const String& name,
  37947. const String& initialContents,
  37948. const String& onScreenLabel = String::empty,
  37949. const bool isPasswordBox = false);
  37950. /** Returns the contents of a named textbox.
  37951. After showing an AlertWindow that contains a text editor, this can be
  37952. used to find out what the user has typed into it.
  37953. @param nameOfTextEditor the name of the text box that you're interested in
  37954. @see addTextEditor
  37955. */
  37956. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37957. /** Adds a drop-down list of choices to the box.
  37958. After the box has been shown, the getComboBoxComponent() method can
  37959. be used to find out which item the user picked.
  37960. @param name the label to use for the drop-down list
  37961. @param items the list of items to show in it
  37962. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37963. combo-box to label it.
  37964. @see getComboBoxComponent
  37965. */
  37966. void addComboBox (const String& name,
  37967. const StringArray& items,
  37968. const String& onScreenLabel = String::empty);
  37969. /** Returns a drop-down list that was added to the AlertWindow.
  37970. @param nameOfList the name that was passed into the addComboBox() method
  37971. when creating the drop-down
  37972. @returns the ComboBox component, or 0 if none was found for the given name.
  37973. */
  37974. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37975. /** Adds a block of text.
  37976. This is handy for adding a multi-line note next to a textbox or combo-box,
  37977. to provide more details about what's going on.
  37978. */
  37979. void addTextBlock (const String& text);
  37980. /** Adds a progress-bar to the window.
  37981. @param progressValue a variable that will be repeatedly checked while the
  37982. dialog box is visible, to see how far the process has
  37983. got. The value should be in the range 0 to 1.0
  37984. */
  37985. void addProgressBarComponent (double& progressValue);
  37986. /** Adds a user-defined component to the dialog box.
  37987. @param component the component to add - its size should be set up correctly
  37988. before it is passed in. The caller is responsible for deleting
  37989. the component later on - the AlertWindow won't delete it.
  37990. */
  37991. void addCustomComponent (Component* const component);
  37992. /** Returns the number of custom components in the dialog box.
  37993. @see getCustomComponent, addCustomComponent
  37994. */
  37995. int getNumCustomComponents() const;
  37996. /** Returns one of the custom components in the dialog box.
  37997. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37998. will return 0
  37999. @see getNumCustomComponents, addCustomComponent
  38000. */
  38001. Component* getCustomComponent (const int index) const;
  38002. /** Removes one of the custom components in the dialog box.
  38003. Note that this won't delete it, it just removes the component from the window
  38004. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38005. will return 0
  38006. @returns the component that was removed (or zero)
  38007. @see getNumCustomComponents, addCustomComponent
  38008. */
  38009. Component* removeCustomComponent (const int index);
  38010. /** Returns true if the window contains any components other than just buttons.*/
  38011. bool containsAnyExtraComponents() const;
  38012. // easy-to-use message box functions:
  38013. /** Shows a dialog box that just has a message and a single button to get rid of it.
  38014. The box is shown modally, and the method returns after the user
  38015. has clicked the button (or pressed the escape or return keys).
  38016. @param iconType the type of icon to show
  38017. @param title the headline to show at the top of the box
  38018. @param message a longer, more descriptive message to show underneath the
  38019. headline
  38020. @param buttonText the text to show in the button - if this string is empty, the
  38021. default string "ok" (or a localised version) will be used.
  38022. @param associatedComponent if this is non-zero, it specifies the component that the
  38023. alert window should be associated with. Depending on the look
  38024. and feel, this might be used for positioning of the alert window.
  38025. */
  38026. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  38027. const String& title,
  38028. const String& message,
  38029. const String& buttonText = String::empty,
  38030. Component* associatedComponent = 0);
  38031. /** Shows a dialog box with two buttons.
  38032. Ideal for ok/cancel or yes/no choices. The return key can also be used
  38033. to trigger the first button, and the escape key for the second button.
  38034. @param iconType the type of icon to show
  38035. @param title the headline to show at the top of the box
  38036. @param message a longer, more descriptive message to show underneath the
  38037. headline
  38038. @param button1Text the text to show in the first button - if this string is
  38039. empty, the default string "ok" (or a localised version of it)
  38040. will be used.
  38041. @param button2Text the text to show in the second button - if this string is
  38042. empty, the default string "cancel" (or a localised version of it)
  38043. will be used.
  38044. @param associatedComponent if this is non-zero, it specifies the component that the
  38045. alert window should be associated with. Depending on the look
  38046. and feel, this might be used for positioning of the alert window.
  38047. @returns true if button 1 was clicked, false if it was button 2
  38048. */
  38049. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  38050. const String& title,
  38051. const String& message,
  38052. const String& button1Text = String::empty,
  38053. const String& button2Text = String::empty,
  38054. Component* associatedComponent = 0);
  38055. /** Shows a dialog box with three buttons.
  38056. Ideal for yes/no/cancel boxes.
  38057. The escape key can be used to trigger the third button.
  38058. @param iconType the type of icon to show
  38059. @param title the headline to show at the top of the box
  38060. @param message a longer, more descriptive message to show underneath the
  38061. headline
  38062. @param button1Text the text to show in the first button - if an empty string, then
  38063. "yes" will be used (or a localised version of it)
  38064. @param button2Text the text to show in the first button - if an empty string, then
  38065. "no" will be used (or a localised version of it)
  38066. @param button3Text the text to show in the first button - if an empty string, then
  38067. "cancel" will be used (or a localised version of it)
  38068. @param associatedComponent if this is non-zero, it specifies the component that the
  38069. alert window should be associated with. Depending on the look
  38070. and feel, this might be used for positioning of the alert window.
  38071. @returns one of the following values:
  38072. - 0 if the third button was pressed (normally used for 'cancel')
  38073. - 1 if the first button was pressed (normally used for 'yes')
  38074. - 2 if the middle button was pressed (normally used for 'no')
  38075. */
  38076. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  38077. const String& title,
  38078. const String& message,
  38079. const String& button1Text = String::empty,
  38080. const String& button2Text = String::empty,
  38081. const String& button3Text = String::empty,
  38082. Component* associatedComponent = 0);
  38083. /** Shows an operating-system native dialog box.
  38084. @param title the title to use at the top
  38085. @param bodyText the longer message to show
  38086. @param isOkCancel if true, this will show an ok/cancel box, if false,
  38087. it'll show a box with just an ok button
  38088. @returns true if the ok button was pressed, false if they pressed cancel.
  38089. */
  38090. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  38091. const String& bodyText,
  38092. bool isOkCancel);
  38093. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  38094. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38095. methods.
  38096. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38097. */
  38098. enum ColourIds
  38099. {
  38100. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  38101. textColourId = 0x1001810, /**< The colour for the text. */
  38102. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  38103. };
  38104. juce_UseDebuggingNewOperator
  38105. protected:
  38106. /** @internal */
  38107. void paint (Graphics& g);
  38108. /** @internal */
  38109. void mouseDown (const MouseEvent& e);
  38110. /** @internal */
  38111. void mouseDrag (const MouseEvent& e);
  38112. /** @internal */
  38113. bool keyPressed (const KeyPress& key);
  38114. /** @internal */
  38115. void buttonClicked (Button* button);
  38116. /** @internal */
  38117. void lookAndFeelChanged();
  38118. /** @internal */
  38119. void userTriedToCloseWindow();
  38120. /** @internal */
  38121. int getDesktopWindowStyleFlags() const;
  38122. private:
  38123. String text;
  38124. TextLayout textLayout;
  38125. AlertIconType alertIconType;
  38126. ComponentBoundsConstrainer constrainer;
  38127. ComponentDragger dragger;
  38128. Rectangle textArea;
  38129. VoidArray buttons, textBoxes, comboBoxes;
  38130. VoidArray progressBars, customComps, textBlocks, allComps;
  38131. StringArray textboxNames, comboBoxNames;
  38132. Font font;
  38133. Component* associatedComponent;
  38134. void updateLayout (const bool onlyIncreaseSize);
  38135. // disable copy constructor
  38136. AlertWindow (const AlertWindow&);
  38137. const AlertWindow& operator= (const AlertWindow&);
  38138. };
  38139. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  38140. /********* End of inlined file: juce_AlertWindow.h *********/
  38141. #endif
  38142. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  38143. #endif
  38144. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38145. /********* Start of inlined file: juce_DialogWindow.h *********/
  38146. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38147. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  38148. /**
  38149. A dialog-box style window.
  38150. This class is a convenient way of creating a DocumentWindow with a close button
  38151. that can be triggered by pressing the escape key.
  38152. Any of the methods available to a DocumentWindow or ResizableWindow are also
  38153. available to this, so it can be made resizable, have a menu bar, etc.
  38154. To add items to the box, see the ResizableWindow::setContentComponent() method.
  38155. Don't add components directly to this class - always put them in a content component!
  38156. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  38157. the user clicking the close button - for more info, see the DocumentWindow
  38158. help.
  38159. @see DocumentWindow, ResizableWindow
  38160. */
  38161. class JUCE_API DialogWindow : public DocumentWindow
  38162. {
  38163. public:
  38164. /** Creates a DialogWindow.
  38165. @param name the name to give the component - this is also
  38166. the title shown at the top of the window. To change
  38167. this later, use setName()
  38168. @param backgroundColour the colour to use for filling the window's background.
  38169. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38170. close button to be triggered
  38171. @param addToDesktop if true, the window will be automatically added to the
  38172. desktop; if false, you can use it as a child component
  38173. */
  38174. DialogWindow (const String& name,
  38175. const Colour& backgroundColour,
  38176. const bool escapeKeyTriggersCloseButton,
  38177. const bool addToDesktop = true);
  38178. /** Destructor.
  38179. If a content component has been set with setContentComponent(), it
  38180. will be deleted.
  38181. */
  38182. ~DialogWindow();
  38183. /** Easy way of quickly showing a dialog box containing a given component.
  38184. This will open and display a DialogWindow containing a given component, returning
  38185. when the user clicks its close button.
  38186. It returns the value that was returned by the dialog box's runModalLoop() call.
  38187. To close the dialog programatically, you should call exitModalState (returnValue) on
  38188. the DialogWindow that is created. To find a pointer to this window from your
  38189. contentComponent, you can do something like this:
  38190. @code
  38191. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  38192. if (dw != 0)
  38193. dw->exitModalState (1234);
  38194. @endcode
  38195. @param dialogTitle the dialog box's title
  38196. @param contentComponent the content component for the dialog box. Make sure
  38197. that this has been set to the size you want it to
  38198. be before calling this method. The component won't
  38199. be deleted by this call, so you can re-use it or delete
  38200. it afterwards
  38201. @param componentToCentreAround if this is non-zero, it indicates a component that
  38202. you'd like to show this dialog box in front of. See the
  38203. DocumentWindow::centreAroundComponent() method for more
  38204. info on this parameter
  38205. @param backgroundColour a colour to use for the dialog box's background colour
  38206. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38207. close button to be triggered
  38208. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  38209. a corner resizer
  38210. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  38211. to use a border or corner resizer component. See ResizableWindow::setResizable()
  38212. */
  38213. static int showModalDialog (const String& dialogTitle,
  38214. Component* contentComponent,
  38215. Component* componentToCentreAround,
  38216. const Colour& backgroundColour,
  38217. const bool escapeKeyTriggersCloseButton,
  38218. const bool shouldBeResizable = false,
  38219. const bool useBottomRightCornerResizer = false);
  38220. juce_UseDebuggingNewOperator
  38221. protected:
  38222. /** @internal */
  38223. void resized();
  38224. private:
  38225. bool escapeKeyTriggersCloseButton;
  38226. DialogWindow (const DialogWindow&);
  38227. const DialogWindow& operator= (const DialogWindow&);
  38228. };
  38229. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  38230. /********* End of inlined file: juce_DialogWindow.h *********/
  38231. #endif
  38232. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38233. #endif
  38234. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  38235. #endif
  38236. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38237. /********* Start of inlined file: juce_SplashScreen.h *********/
  38238. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38239. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  38240. /** A component for showing a splash screen while your app starts up.
  38241. This will automatically position itself, and delete itself when the app has
  38242. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  38243. this).
  38244. To use it, just create one of these in your JUCEApplication::initialise() method,
  38245. call its show() method and let the object delete itself later.
  38246. E.g. @code
  38247. void MyApp::initialise (const String& commandLine)
  38248. {
  38249. SplashScreen* splash = new SplashScreen();
  38250. splash->show (T("welcome to my app"),
  38251. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  38252. 4000, false);
  38253. .. no need to delete the splash screen - it'll do that itself.
  38254. }
  38255. @endcode
  38256. */
  38257. class JUCE_API SplashScreen : public Component,
  38258. public Timer,
  38259. private DeletedAtShutdown
  38260. {
  38261. public:
  38262. /** Creates a SplashScreen object.
  38263. After creating one of these (or your subclass of it), call one of the show()
  38264. methods to display it.
  38265. */
  38266. SplashScreen();
  38267. /** Destructor. */
  38268. ~SplashScreen();
  38269. /** Creates a SplashScreen object that will display an image.
  38270. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38271. screen. This method will also dispatch any pending messages to make sure that when
  38272. it returns, the splash screen has been completely drawn, and your initialisation
  38273. code can carry on.
  38274. @param title the name to give the component
  38275. @param backgroundImage an image to draw on the component. The component's size
  38276. will be set to the size of this image, and if the image is
  38277. semi-transparent, the component will be made semi-transparent
  38278. too. This image will be deleted (or released from the ImageCache
  38279. if that's how it was created) by the splash screen object when
  38280. it is itself deleted.
  38281. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38282. should stay visible for. If the initialisation takes longer than
  38283. this time, the splash screen will wait for it to finish before
  38284. disappearing, but if initialisation is very quick, this lets
  38285. you make sure that people get a good look at your splash.
  38286. @param useDropShadow if true, the window will have a drop shadow
  38287. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38288. the mouse (anywhere)
  38289. */
  38290. void show (const String& title,
  38291. Image* const backgroundImage,
  38292. const int minimumTimeToDisplayFor,
  38293. const bool useDropShadow,
  38294. const bool removeOnMouseClick = true);
  38295. /** Creates a SplashScreen object with a specified size.
  38296. For a custom splash screen, you can use this method to display it at a certain size
  38297. and then override the paint() method yourself to do whatever's necessary.
  38298. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38299. screen. This method will also dispatch any pending messages to make sure that when
  38300. it returns, the splash screen has been completely drawn, and your initialisation
  38301. code can carry on.
  38302. @param title the name to give the component
  38303. @param width the width to use
  38304. @param height the height to use
  38305. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38306. should stay visible for. If the initialisation takes longer than
  38307. this time, the splash screen will wait for it to finish before
  38308. disappearing, but if initialisation is very quick, this lets
  38309. you make sure that people get a good look at your splash.
  38310. @param useDropShadow if true, the window will have a drop shadow
  38311. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38312. the mouse (anywhere)
  38313. */
  38314. void show (const String& title,
  38315. const int width,
  38316. const int height,
  38317. const int minimumTimeToDisplayFor,
  38318. const bool useDropShadow,
  38319. const bool removeOnMouseClick = true);
  38320. /** @internal */
  38321. void paint (Graphics& g);
  38322. /** @internal */
  38323. void timerCallback();
  38324. juce_UseDebuggingNewOperator
  38325. private:
  38326. Image* backgroundImage;
  38327. Time earliestTimeToDelete;
  38328. int originalClickCounter;
  38329. bool isImageInCache;
  38330. SplashScreen (const SplashScreen&);
  38331. const SplashScreen& operator= (const SplashScreen&);
  38332. };
  38333. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  38334. /********* End of inlined file: juce_SplashScreen.h *********/
  38335. #endif
  38336. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  38337. #endif
  38338. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38339. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  38340. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38341. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38342. /**
  38343. A thread that automatically pops up a modal dialog box with a progress bar
  38344. and cancel button while it's busy running.
  38345. These are handy for performing some sort of task while giving the user feedback
  38346. about how long there is to go, etc.
  38347. E.g. @code
  38348. class MyTask : public ThreadWithProgressWindow
  38349. {
  38350. public:
  38351. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  38352. {
  38353. }
  38354. ~MyTask()
  38355. {
  38356. }
  38357. void run()
  38358. {
  38359. for (int i = 0; i < thingsToDo; ++i)
  38360. {
  38361. // must check this as often as possible, because this is
  38362. // how we know if the user's pressed 'cancel'
  38363. if (threadShouldExit())
  38364. break;
  38365. // this will update the progress bar on the dialog box
  38366. setProgress (i / (double) thingsToDo);
  38367. // ... do the business here...
  38368. }
  38369. }
  38370. };
  38371. void doTheTask()
  38372. {
  38373. MyTask m;
  38374. if (m.runThread())
  38375. {
  38376. // thread finished normally..
  38377. }
  38378. else
  38379. {
  38380. // user pressed the cancel button..
  38381. }
  38382. }
  38383. @endcode
  38384. @see Thread, AlertWindow
  38385. */
  38386. class JUCE_API ThreadWithProgressWindow : public Thread,
  38387. private Timer
  38388. {
  38389. public:
  38390. /** Creates the thread.
  38391. Initially, the dialog box won't be visible, it'll only appear when the
  38392. runThread() method is called.
  38393. @param windowTitle the title to go at the top of the dialog box
  38394. @param hasProgressBar whether the dialog box should have a progress bar (see
  38395. setProgress() )
  38396. @param hasCancelButton whether the dialog box should have a cancel button
  38397. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  38398. the thread to stop before killing it forcibly (see
  38399. Thread::stopThread() )
  38400. @param cancelButtonText the text that should be shown in the cancel button
  38401. (if it has one)
  38402. */
  38403. ThreadWithProgressWindow (const String& windowTitle,
  38404. const bool hasProgressBar,
  38405. const bool hasCancelButton,
  38406. const int timeOutMsWhenCancelling = 10000,
  38407. const String& cancelButtonText = JUCE_T("Cancel"));
  38408. /** Destructor. */
  38409. ~ThreadWithProgressWindow();
  38410. /** Starts the thread and waits for it to finish.
  38411. This will start the thread, make the dialog box appear, and wait until either
  38412. the thread finishes normally, or until the cancel button is pressed.
  38413. Before returning, the dialog box will be hidden.
  38414. @param threadPriority the priority to use when starting the thread - see
  38415. Thread::startThread() for values
  38416. @returns true if the thread finished normally; false if the user pressed cancel
  38417. */
  38418. bool runThread (const int threadPriority = 5);
  38419. /** The thread should call this periodically to update the position of the progress bar.
  38420. @param newProgress the progress, from 0.0 to 1.0
  38421. @see setStatusMessage
  38422. */
  38423. void setProgress (const double newProgress);
  38424. /** The thread can call this to change the message that's displayed in the dialog box.
  38425. */
  38426. void setStatusMessage (const String& newStatusMessage);
  38427. juce_UseDebuggingNewOperator
  38428. private:
  38429. void timerCallback();
  38430. double progress;
  38431. AlertWindow* alertWindow;
  38432. String message;
  38433. CriticalSection messageLock;
  38434. const int timeOutMsWhenCancelling;
  38435. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  38436. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  38437. };
  38438. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38439. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  38440. #endif
  38441. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  38442. #endif
  38443. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  38444. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  38445. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  38446. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  38447. #if JUCE_WIN32 || JUCE_LINUX
  38448. /**
  38449. On Windows only, this component sits in the taskbar tray as a small icon.
  38450. To use it, just create one of these components, but don't attempt to make it
  38451. visible, add it to a parent, or put it on the desktop.
  38452. You can then call setIconImage() to create an icon for it in the taskbar.
  38453. To change the icon's tooltip, you can use setIconTooltip().
  38454. To respond to mouse-events, you can override the normal mouseDown(),
  38455. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  38456. position will not be valid, you can use this to respond to clicks. Traditionally
  38457. you'd use a left-click to show your application's window, and a right-click
  38458. to show a pop-up menu.
  38459. */
  38460. class JUCE_API SystemTrayIconComponent : public Component
  38461. {
  38462. public:
  38463. SystemTrayIconComponent();
  38464. /** Destructor. */
  38465. ~SystemTrayIconComponent();
  38466. /** Changes the image shown in the taskbar.
  38467. */
  38468. void setIconImage (const Image& newImage);
  38469. /** Changes the tooltip that Windows shows above the icon. */
  38470. void setIconTooltip (const String& tooltip);
  38471. #if JUCE_LINUX
  38472. /** @internal */
  38473. void paint (Graphics& g);
  38474. #endif
  38475. juce_UseDebuggingNewOperator
  38476. private:
  38477. SystemTrayIconComponent (const SystemTrayIconComponent&);
  38478. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  38479. };
  38480. #endif
  38481. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  38482. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  38483. #endif
  38484. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  38485. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  38486. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  38487. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  38488. #if JUCE_WEB_BROWSER
  38489. class WebBrowserComponentInternal;
  38490. /**
  38491. A component that displays an embedded web browser.
  38492. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  38493. Windows, probably IE.
  38494. */
  38495. class WebBrowserComponent : public Component
  38496. {
  38497. public:
  38498. /** Creates a WebBrowserComponent.
  38499. Once it's created and visible, send the browser to a URL using goToURL().
  38500. */
  38501. WebBrowserComponent();
  38502. /** Destructor. */
  38503. ~WebBrowserComponent();
  38504. /** Sends the browser to a particular URL.
  38505. @param url the URL to go to.
  38506. @param headers an optional set of parameters to put in the HTTP header. If
  38507. you supply this, it should be a set of string in the form
  38508. "HeaderKey: HeaderValue"
  38509. @param postData an optional block of data that will be attached to the HTTP
  38510. POST request
  38511. */
  38512. void goToURL (const String& url,
  38513. const StringArray* headers = 0,
  38514. const MemoryBlock* postData = 0);
  38515. /** Stops the current page loading.
  38516. */
  38517. void stop();
  38518. /** Sends the browser back one page.
  38519. */
  38520. void goBack();
  38521. /** Sends the browser forward one page.
  38522. */
  38523. void goForward();
  38524. /** Refreshes the browser.
  38525. */
  38526. void refresh();
  38527. /** This callback is called when the browser is about to navigate
  38528. to a new location.
  38529. You can override this method to perform some action when the user
  38530. tries to go to a particular URL. To allow the operation to carry on,
  38531. return true, or return false to stop the navigation happening.
  38532. */
  38533. virtual bool pageAboutToLoad (const String& newURL);
  38534. /** @internal */
  38535. void paint (Graphics& g);
  38536. /** @internal */
  38537. void resized();
  38538. /** @internal */
  38539. void parentHierarchyChanged();
  38540. /** @internal */
  38541. void visibilityChanged();
  38542. juce_UseDebuggingNewOperator
  38543. private:
  38544. WebBrowserComponentInternal* browser;
  38545. bool blankPageShown;
  38546. String lastURL;
  38547. StringArray lastHeaders;
  38548. MemoryBlock lastPostData;
  38549. void reloadLastURL();
  38550. void checkWindowAssociation();
  38551. WebBrowserComponent (const WebBrowserComponent&);
  38552. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  38553. };
  38554. #endif
  38555. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  38556. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  38557. #endif
  38558. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38559. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  38560. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38561. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38562. #if JUCE_WIN32 || DOXYGEN
  38563. /**
  38564. A Windows-specific class that can create and embed an ActiveX control inside
  38565. itself.
  38566. To use it, create one of these, put it in place and make sure it's visible in a
  38567. window, then use createControl() to instantiate an ActiveX control. The control
  38568. will then be moved and resized to follow the movements of this component.
  38569. Of course, since the control is a heavyweight window, it'll obliterate any
  38570. juce components that may overlap this component, but that's life.
  38571. */
  38572. class JUCE_API ActiveXControlComponent : public Component
  38573. {
  38574. public:
  38575. /** Create an initially-empty container. */
  38576. ActiveXControlComponent();
  38577. /** Destructor. */
  38578. ~ActiveXControlComponent();
  38579. /** Tries to create an ActiveX control and embed it in this peer.
  38580. The peer controlIID is a pointer to an IID structure - it's treated
  38581. as a void* because when including the Juce headers, you might not always
  38582. have included windows.h first, in which case IID wouldn't be defined.
  38583. e.g. @code
  38584. const IID myIID = __uuidof (QTControl);
  38585. myControlComp->createControl (&myIID);
  38586. @endcode
  38587. */
  38588. bool createControl (const void* controlIID);
  38589. /** Deletes the ActiveX control, if one has been created.
  38590. */
  38591. void deleteControl();
  38592. /** Returns true if a control is currently in use. */
  38593. bool isControlOpen() const throw() { return control != 0; }
  38594. /** Does a QueryInterface call on the embedded control object.
  38595. This allows you to cast the control to whatever type of COM object you need.
  38596. The iid parameter is a pointer to an IID structure - it's treated
  38597. as a void* because when including the Juce headers, you might not always
  38598. have included windows.h first, in which case IID wouldn't be defined, but
  38599. you should just pass a pointer to an IID.
  38600. e.g. @code
  38601. const IID iid = __uuidof (IOleWindow);
  38602. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  38603. if (oleWindow != 0)
  38604. {
  38605. HWND hwnd;
  38606. oleWindow->GetWindow (&hwnd);
  38607. ...
  38608. oleWindow->Release();
  38609. }
  38610. @endcode
  38611. */
  38612. void* queryInterface (const void* iid) const;
  38613. /** Set this to false to stop mouse events being allowed through to the control.
  38614. */
  38615. void setMouseEventsAllowed (const bool eventsCanReachControl);
  38616. /** Returns true if mouse events are allowed to get through to the control.
  38617. */
  38618. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  38619. /** @internal */
  38620. void paint (Graphics& g);
  38621. /** @internal */
  38622. void* originalWndProc;
  38623. juce_UseDebuggingNewOperator
  38624. private:
  38625. friend class ActiveXControlData;
  38626. void* control;
  38627. bool mouseEventsAllowed;
  38628. ActiveXControlComponent (const ActiveXControlComponent&);
  38629. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  38630. void setControlBounds (const Rectangle& bounds) const;
  38631. void setControlVisible (const bool b) const;
  38632. };
  38633. #endif
  38634. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38635. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  38636. #endif
  38637. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38638. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38639. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38640. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38641. class MidiInputSelectorComponentListBox;
  38642. /**
  38643. A component containing controls to let the user change the audio settings of
  38644. an AudioDeviceManager object.
  38645. Very easy to use - just create one of these and show it to the user.
  38646. @see AudioDeviceManager
  38647. */
  38648. class JUCE_API AudioDeviceSelectorComponent : public Component,
  38649. public ComboBoxListener,
  38650. public ButtonListener,
  38651. public ChangeListener
  38652. {
  38653. public:
  38654. /** Creates the component.
  38655. If your app needs only output channels, you might ask for a maximum of 0 input
  38656. channels, and the component won't display any options for choosing the input
  38657. channels. And likewise if you're doing an input-only app.
  38658. @param deviceManager the device manager that this component should control
  38659. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  38660. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  38661. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  38662. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  38663. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  38664. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  38665. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  38666. treated as a set of separate mono channels.
  38667. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  38668. are shown, with an "advanced" button that shows the rest of them
  38669. */
  38670. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  38671. const int minAudioInputChannels,
  38672. const int maxAudioInputChannels,
  38673. const int minAudioOutputChannels,
  38674. const int maxAudioOutputChannels,
  38675. const bool showMidiInputOptions,
  38676. const bool showMidiOutputSelector,
  38677. const bool showChannelsAsStereoPairs,
  38678. const bool hideAdvancedOptionsWithButton);
  38679. /** Destructor */
  38680. ~AudioDeviceSelectorComponent();
  38681. /** @internal */
  38682. void resized();
  38683. /** @internal */
  38684. void comboBoxChanged (ComboBox*);
  38685. /** @internal */
  38686. void buttonClicked (Button*);
  38687. /** @internal */
  38688. void changeListenerCallback (void*);
  38689. juce_UseDebuggingNewOperator
  38690. private:
  38691. AudioDeviceManager& deviceManager;
  38692. ComboBox* deviceTypeDropDown;
  38693. Label* deviceTypeDropDownLabel;
  38694. Component* audioDeviceSettingsComp;
  38695. String audioDeviceSettingsCompType;
  38696. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  38697. const bool showChannelsAsStereoPairs;
  38698. const bool hideAdvancedOptionsWithButton;
  38699. MidiInputSelectorComponentListBox* midiInputsList;
  38700. Label* midiInputsLabel;
  38701. ComboBox* midiOutputSelector;
  38702. Label* midiOutputLabel;
  38703. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  38704. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  38705. };
  38706. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38707. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38708. #endif
  38709. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38710. /********* Start of inlined file: juce_BubbleComponent.h *********/
  38711. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38712. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38713. /**
  38714. A component for showing a message or other graphics inside a speech-bubble-shaped
  38715. outline, pointing at a location on the screen.
  38716. This is a base class that just draws and positions the bubble shape, but leaves
  38717. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  38718. that draws a text message.
  38719. To use it, create your subclass, then either add it to a parent component or
  38720. put it on the desktop with addToDesktop (0), use setPosition() to
  38721. resize and position it, then make it visible.
  38722. @see BubbleMessageComponent
  38723. */
  38724. class JUCE_API BubbleComponent : public Component
  38725. {
  38726. protected:
  38727. /** Creates a BubbleComponent.
  38728. Your subclass will need to implement the getContentSize() and paintContent()
  38729. methods to draw the bubble's contents.
  38730. */
  38731. BubbleComponent();
  38732. public:
  38733. /** Destructor. */
  38734. ~BubbleComponent();
  38735. /** A list of permitted placements for the bubble, relative to the co-ordinates
  38736. at which it should be pointing.
  38737. @see setAllowedPlacement
  38738. */
  38739. enum BubblePlacement
  38740. {
  38741. above = 1,
  38742. below = 2,
  38743. left = 4,
  38744. right = 8
  38745. };
  38746. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  38747. point at which it's pointing.
  38748. By default when setPosition() is called, the bubble will place itself either
  38749. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  38750. the values in BubblePlacement to restrict this choice.
  38751. E.g. if you only want your bubble to appear above or below the target area,
  38752. use setAllowedPlacement (above | below);
  38753. @see BubblePlacement
  38754. */
  38755. void setAllowedPlacement (const int newPlacement);
  38756. /** Moves and resizes the bubble to point at a given component.
  38757. This will resize the bubble to fit its content, then find a position for it
  38758. so that it's next to, but doesn't overlap the given component.
  38759. It'll put itself either above, below, or to the side of the component depending
  38760. on where there's the most space, honouring any restrictions that were set
  38761. with setAllowedPlacement().
  38762. */
  38763. void setPosition (Component* componentToPointTo);
  38764. /** Moves and resizes the bubble to point at a given point.
  38765. This will resize the bubble to fit its content, then position it
  38766. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  38767. are relative to either the bubble component's parent component if it has one, or
  38768. they are screen co-ordinates if not.
  38769. It'll put itself either above, below, or to the side of this point, depending
  38770. on where there's the most space, honouring any restrictions that were set
  38771. with setAllowedPlacement().
  38772. */
  38773. void setPosition (const int arrowTipX,
  38774. const int arrowTipY);
  38775. /** Moves and resizes the bubble to point at a given rectangle.
  38776. This will resize the bubble to fit its content, then find a position for it
  38777. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  38778. co-ordinates are relative to either the bubble component's parent component
  38779. if it has one, or they are screen co-ordinates if not.
  38780. It'll put itself either above, below, or to the side of the component depending
  38781. on where there's the most space, honouring any restrictions that were set
  38782. with setAllowedPlacement().
  38783. */
  38784. void setPosition (const Rectangle& rectangleToPointTo);
  38785. protected:
  38786. /** Subclasses should override this to return the size of the content they
  38787. want to draw inside the bubble.
  38788. */
  38789. virtual void getContentSize (int& width, int& height) = 0;
  38790. /** Subclasses should override this to draw their bubble's contents.
  38791. The graphics object's clip region and the dimensions passed in here are
  38792. set up to paint just the rectangle inside the bubble.
  38793. */
  38794. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38795. public:
  38796. /** @internal */
  38797. void paint (Graphics& g);
  38798. juce_UseDebuggingNewOperator
  38799. private:
  38800. Rectangle content;
  38801. int side, allowablePlacements;
  38802. float arrowTipX, arrowTipY;
  38803. DropShadowEffect shadow;
  38804. BubbleComponent (const BubbleComponent&);
  38805. const BubbleComponent& operator= (const BubbleComponent&);
  38806. };
  38807. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38808. /********* End of inlined file: juce_BubbleComponent.h *********/
  38809. #endif
  38810. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38811. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38812. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38813. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38814. /**
  38815. A speech-bubble component that displays a short message.
  38816. This can be used to show a message with the tail of the speech bubble
  38817. pointing to a particular component or location on the screen.
  38818. @see BubbleComponent
  38819. */
  38820. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38821. private Timer
  38822. {
  38823. public:
  38824. /** Creates a bubble component.
  38825. After creating one a BubbleComponent, do the following:
  38826. - add it to an appropriate parent component, or put it on the
  38827. desktop with Component::addToDesktop (0).
  38828. - use the showAt() method to show a message.
  38829. - it will make itself invisible after it times-out (and can optionally
  38830. also delete itself), or you can reuse it somewhere else by calling
  38831. showAt() again.
  38832. */
  38833. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38834. /** Destructor. */
  38835. ~BubbleMessageComponent();
  38836. /** Shows a message bubble at a particular position.
  38837. This shows the bubble with its stem pointing to the given location
  38838. (co-ordinates being relative to its parent component).
  38839. For details about exactly how it decides where to position itself, see
  38840. BubbleComponent::updatePosition().
  38841. @param x the x co-ordinate of end of the bubble's tail
  38842. @param y the y co-ordinate of end of the bubble's tail
  38843. @param message the text to display
  38844. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38845. from its parent compnent. If this is 0 or less, it
  38846. will stay there until manually removed.
  38847. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38848. mouse button is pressed (anywhere on the screen)
  38849. @param deleteSelfAfterUse if true, then the component will delete itself after
  38850. it becomes invisible
  38851. */
  38852. void showAt (int x, int y,
  38853. const String& message,
  38854. const int numMillisecondsBeforeRemoving,
  38855. const bool removeWhenMouseClicked = true,
  38856. const bool deleteSelfAfterUse = false);
  38857. /** Shows a message bubble next to a particular component.
  38858. This shows the bubble with its stem pointing at the given component.
  38859. For details about exactly how it decides where to position itself, see
  38860. BubbleComponent::updatePosition().
  38861. @param component the component that you want to point at
  38862. @param message the text to display
  38863. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38864. from its parent compnent. If this is 0 or less, it
  38865. will stay there until manually removed.
  38866. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38867. mouse button is pressed (anywhere on the screen)
  38868. @param deleteSelfAfterUse if true, then the component will delete itself after
  38869. it becomes invisible
  38870. */
  38871. void showAt (Component* const component,
  38872. const String& message,
  38873. const int numMillisecondsBeforeRemoving,
  38874. const bool removeWhenMouseClicked = true,
  38875. const bool deleteSelfAfterUse = false);
  38876. /** @internal */
  38877. void getContentSize (int& w, int& h);
  38878. /** @internal */
  38879. void paintContent (Graphics& g, int w, int h);
  38880. /** @internal */
  38881. void timerCallback();
  38882. juce_UseDebuggingNewOperator
  38883. private:
  38884. int fadeOutLength, mouseClickCounter;
  38885. TextLayout textLayout;
  38886. int64 expiryTime;
  38887. bool deleteAfterUse;
  38888. void init (const int numMillisecondsBeforeRemoving,
  38889. const bool removeWhenMouseClicked,
  38890. const bool deleteSelfAfterUse);
  38891. BubbleMessageComponent (const BubbleMessageComponent&);
  38892. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38893. };
  38894. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38895. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38896. #endif
  38897. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38898. /********* Start of inlined file: juce_ColourSelector.h *********/
  38899. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38900. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38901. /**
  38902. A component that lets the user choose a colour.
  38903. This shows RGB sliders and a colourspace that the user can pick colours from.
  38904. This class is also a ChangeBroadcaster, so listeners can register to be told
  38905. when the colour changes.
  38906. */
  38907. class JUCE_API ColourSelector : public Component,
  38908. public ChangeBroadcaster,
  38909. protected SliderListener
  38910. {
  38911. public:
  38912. /** Options for the type of selector to show. These are passed into the constructor. */
  38913. enum ColourSelectorOptions
  38914. {
  38915. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38916. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38917. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38918. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38919. };
  38920. /** Creates a ColourSelector object.
  38921. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38922. which of the selector's features should be visible.
  38923. The edgeGap value specifies the amount of space to leave around the edge.
  38924. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38925. colourspace and hue selector components.
  38926. */
  38927. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38928. const int edgeGap = 4,
  38929. const int gapAroundColourSpaceComponent = 7);
  38930. /** Destructor. */
  38931. ~ColourSelector();
  38932. /** Returns the colour that the user has currently selected.
  38933. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38934. register to be told when the colour changes.
  38935. @see setCurrentColour
  38936. */
  38937. const Colour getCurrentColour() const;
  38938. /** Changes the colour that is currently being shown.
  38939. */
  38940. void setCurrentColour (const Colour& newColour);
  38941. /** Tells the selector how many preset colour swatches you want to have on the component.
  38942. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38943. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38944. their values.
  38945. */
  38946. virtual int getNumSwatches() const;
  38947. /** Called by the selector to find out the colour of one of the swatches.
  38948. Your subclass should return the colour of the swatch with the given index.
  38949. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38950. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38951. their values.
  38952. */
  38953. virtual const Colour getSwatchColour (const int index) const;
  38954. /** Called by the selector when the user puts a new colour into one of the swatches.
  38955. Your subclass should change the colour of the swatch with the given index.
  38956. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38957. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38958. their values.
  38959. */
  38960. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38961. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38962. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38963. methods.
  38964. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38965. */
  38966. enum ColourIds
  38967. {
  38968. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38969. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38970. };
  38971. juce_UseDebuggingNewOperator
  38972. private:
  38973. friend class ColourSpaceView;
  38974. friend class HueSelectorComp;
  38975. Colour colour;
  38976. float h, s, v;
  38977. Slider* sliders[4];
  38978. Component* colourSpace;
  38979. Component* hueSelector;
  38980. VoidArray swatchComponents;
  38981. const int flags;
  38982. int topSpace, edgeGap;
  38983. void setHue (float newH);
  38984. void setSV (float newS, float newV);
  38985. void updateHSV();
  38986. void update();
  38987. void sliderValueChanged (Slider*);
  38988. void paint (Graphics& g);
  38989. void resized();
  38990. ColourSelector (const ColourSelector&);
  38991. const ColourSelector& operator= (const ColourSelector&);
  38992. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38993. // have changed - if you get an error here, update your code to use the new constructor instead..
  38994. // (xxx - note to self: remember to remove this at some point in the future)
  38995. ColourSelector (const bool);
  38996. };
  38997. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38998. /********* End of inlined file: juce_ColourSelector.h *********/
  38999. #endif
  39000. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39001. #endif
  39002. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39003. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  39004. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39005. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39006. /**
  39007. A component that contains another component, and can magnify or shrink it.
  39008. This component will continually update its size so that it fits the zoomed
  39009. version of the content component that you put inside it, so don't try to
  39010. change the size of this component directly - instead change that of the
  39011. content component.
  39012. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  39013. to remap mouse events correctly. This means that the content component won't
  39014. appear to be a direct child of this component, and instead will think its
  39015. on the desktop.
  39016. */
  39017. class JUCE_API MagnifierComponent : public Component
  39018. {
  39019. public:
  39020. /** Creates a MagnifierComponent.
  39021. This component will continually update its size so that it fits the zoomed
  39022. version of the content component that you put inside it, so don't try to
  39023. change the size of this component directly - instead change that of the
  39024. content component.
  39025. @param contentComponent the component to add as the magnified one
  39026. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  39027. be deleted when this component is deleted. If false,
  39028. it's the caller's responsibility to delete it later.
  39029. */
  39030. MagnifierComponent (Component* const contentComponent,
  39031. const bool deleteContentCompWhenNoLongerNeeded);
  39032. /** Destructor. */
  39033. ~MagnifierComponent();
  39034. /** Returns the current content component. */
  39035. Component* getContentComponent() const throw() { return content; }
  39036. /** Changes the zoom level.
  39037. The scale factor must be greater than zero. Values less than 1 will shrink the
  39038. image; values greater than 1 will multiply its size by this amount.
  39039. When this is called, this component will change its size to fit the full extent
  39040. of the newly zoomed content.
  39041. */
  39042. void setScaleFactor (double newScaleFactor);
  39043. /** Returns the current zoom factor. */
  39044. double getScaleFactor() const throw() { return scaleFactor; }
  39045. juce_UseDebuggingNewOperator
  39046. /** @internal */
  39047. void childBoundsChanged (Component*);
  39048. private:
  39049. Component* content;
  39050. Component* holderComp;
  39051. double scaleFactor;
  39052. ComponentPeer* peer;
  39053. bool deleteContent;
  39054. void paint (Graphics& g);
  39055. void mouseDown (const MouseEvent& e);
  39056. void mouseUp (const MouseEvent& e);
  39057. void mouseDrag (const MouseEvent& e);
  39058. void mouseMove (const MouseEvent& e);
  39059. void mouseEnter (const MouseEvent& e);
  39060. void mouseExit (const MouseEvent& e);
  39061. void mouseWheelMove (const MouseEvent& e, float, float);
  39062. int scaleInt (const int n) const throw();
  39063. MagnifierComponent (const MagnifierComponent&);
  39064. const MagnifierComponent& operator= (const MagnifierComponent&);
  39065. };
  39066. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39067. /********* End of inlined file: juce_MagnifierComponent.h *********/
  39068. #endif
  39069. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39070. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  39071. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39072. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39073. /**
  39074. A component that displays a piano keyboard, whose notes can be clicked on.
  39075. This component will mimic a physical midi keyboard, showing the current state of
  39076. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  39077. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  39078. Another feature is that the computer keyboard can also be used to play notes. By
  39079. default it maps the top two rows of a standard querty keyboard to the notes, but
  39080. these can be remapped if needed. It will only respond to keypresses when it has
  39081. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  39082. The component is also a ChangeBroadcaster, so if you want to be informed when the
  39083. keyboard is scrolled, you can register a ChangeListener for callbacks.
  39084. @see MidiKeyboardState
  39085. */
  39086. class JUCE_API MidiKeyboardComponent : public Component,
  39087. public MidiKeyboardStateListener,
  39088. public ChangeBroadcaster,
  39089. private Timer,
  39090. private AsyncUpdater
  39091. {
  39092. public:
  39093. /** The direction of the keyboard.
  39094. @see setOrientation
  39095. */
  39096. enum Orientation
  39097. {
  39098. horizontalKeyboard,
  39099. verticalKeyboardFacingLeft,
  39100. verticalKeyboardFacingRight,
  39101. };
  39102. /** Creates a MidiKeyboardComponent.
  39103. @param state the midi keyboard model that this component will represent
  39104. @param orientation whether the keyboard is horizonal or vertical
  39105. */
  39106. MidiKeyboardComponent (MidiKeyboardState& state,
  39107. const Orientation orientation);
  39108. /** Destructor. */
  39109. ~MidiKeyboardComponent();
  39110. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  39111. on the component.
  39112. Values are 0 to 1.0, where 1.0 is the heaviest.
  39113. @see setMidiChannel
  39114. */
  39115. void setVelocity (const float velocity);
  39116. /** Changes the midi channel number that will be used for events triggered by clicking
  39117. on the component.
  39118. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  39119. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  39120. Although this is the channel used for outgoing events, the component can display
  39121. incoming events from more than one channel - see setMidiChannelsToDisplay()
  39122. @see setVelocity
  39123. */
  39124. void setMidiChannel (const int midiChannelNumber);
  39125. /** Returns the midi channel that the keyboard is using for midi messages.
  39126. @see setMidiChannel
  39127. */
  39128. int getMidiChannel() const throw() { return midiChannel; }
  39129. /** Sets a mask to indicate which incoming midi channels should be represented by
  39130. key movements.
  39131. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  39132. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  39133. in this mask, the on-screen keys will also go down.
  39134. By default, this mask is set to 0xffff (all channels displayed).
  39135. @see setMidiChannel
  39136. */
  39137. void setMidiChannelsToDisplay (const int midiChannelMask);
  39138. /** Returns the current set of midi channels represented by the component.
  39139. This is the value that was set with setMidiChannelsToDisplay().
  39140. */
  39141. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  39142. /** Changes the width used to draw the white keys. */
  39143. void setKeyWidth (const float widthInPixels);
  39144. /** Returns the width that was set by setKeyWidth(). */
  39145. float getKeyWidth() const throw() { return keyWidth; }
  39146. /** Changes the keyboard's current direction. */
  39147. void setOrientation (const Orientation newOrientation);
  39148. /** Returns the keyboard's current direction. */
  39149. const Orientation getOrientation() const throw() { return orientation; }
  39150. /** Sets the range of midi notes that the keyboard will be limited to.
  39151. By default the range is 0 to 127 (inclusive), but you can limit this if you
  39152. only want a restricted set of the keys to be shown.
  39153. Note that the values here are inclusive and must be between 0 and 127.
  39154. */
  39155. void setAvailableRange (const int lowestNote,
  39156. const int highestNote);
  39157. /** Returns the first note in the available range.
  39158. @see setAvailableRange
  39159. */
  39160. int getRangeStart() const throw() { return rangeStart; }
  39161. /** Returns the last note in the available range.
  39162. @see setAvailableRange
  39163. */
  39164. int getRangeEnd() const throw() { return rangeEnd; }
  39165. /** If the keyboard extends beyond the size of the component, this will scroll
  39166. it to show the given key at the start.
  39167. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  39168. base class to send a callback to any ChangeListeners that have been registered.
  39169. */
  39170. void setLowestVisibleKey (int noteNumber);
  39171. /** Returns the number of the first key shown in the component.
  39172. @see setLowestVisibleKey
  39173. */
  39174. int getLowestVisibleKey() const throw() { return firstKey; }
  39175. /** Returns the length of the black notes.
  39176. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  39177. */
  39178. int getBlackNoteLength() const throw() { return blackNoteLength; }
  39179. /** If set to true, then scroll buttons will appear at either end of the keyboard
  39180. if there are too many notes to fit them all in the component at once.
  39181. */
  39182. void setScrollButtonsVisible (const bool canScroll);
  39183. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39184. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39185. methods.
  39186. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39187. */
  39188. enum ColourIds
  39189. {
  39190. whiteNoteColourId = 0x1005000,
  39191. blackNoteColourId = 0x1005001,
  39192. keySeparatorLineColourId = 0x1005002,
  39193. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  39194. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  39195. textLabelColourId = 0x1005005,
  39196. upDownButtonBackgroundColourId = 0x1005006,
  39197. upDownButtonArrowColourId = 0x1005007
  39198. };
  39199. /** Returns the position within the component of the left-hand edge of a key.
  39200. Depending on the keyboard's orientation, this may be a horizontal or vertical
  39201. distance, in either direction.
  39202. */
  39203. int getKeyStartPosition (const int midiNoteNumber) const;
  39204. /** Deletes all key-mappings.
  39205. @see setKeyPressForNote
  39206. */
  39207. void clearKeyMappings();
  39208. /** Maps a key-press to a given note.
  39209. @param key the key that should trigger the note
  39210. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  39211. be. The actual midi note that gets played will be
  39212. this value + (12 * the current base octave). To change
  39213. the base octave, see setKeyPressBaseOctave()
  39214. */
  39215. void setKeyPressForNote (const KeyPress& key,
  39216. const int midiNoteOffsetFromC);
  39217. /** Removes any key-mappings for a given note.
  39218. For a description of what the note number means, see setKeyPressForNote().
  39219. */
  39220. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  39221. /** Changes the base note above which key-press-triggered notes are played.
  39222. The set of key-mappings that trigger notes can be moved up and down to cover
  39223. the entire scale using this method.
  39224. The value passed in is an octave number between 0 and 10 (inclusive), and
  39225. indicates which C is the base note to which the key-mapped notes are
  39226. relative.
  39227. */
  39228. void setKeyPressBaseOctave (const int newOctaveNumber);
  39229. /** This sets the octave number which is shown as the octave number for middle C.
  39230. This affects only the default implementation of getWhiteNoteText(), which
  39231. passes this octave number to MidiMessage::getMidiNoteName() in order to
  39232. get the note text. See MidiMessage::getMidiNoteName() for more info about
  39233. the parameter.
  39234. By default this value is set to 3.
  39235. @see getOctaveForMiddleC
  39236. */
  39237. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  39238. /** This returns the value set by setOctaveForMiddleC().
  39239. @see setOctaveForMiddleC
  39240. */
  39241. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  39242. /** @internal */
  39243. void paint (Graphics& g);
  39244. /** @internal */
  39245. void resized();
  39246. /** @internal */
  39247. void mouseMove (const MouseEvent& e);
  39248. /** @internal */
  39249. void mouseDrag (const MouseEvent& e);
  39250. /** @internal */
  39251. void mouseDown (const MouseEvent& e);
  39252. /** @internal */
  39253. void mouseUp (const MouseEvent& e);
  39254. /** @internal */
  39255. void mouseEnter (const MouseEvent& e);
  39256. /** @internal */
  39257. void mouseExit (const MouseEvent& e);
  39258. /** @internal */
  39259. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39260. /** @internal */
  39261. void timerCallback();
  39262. /** @internal */
  39263. bool keyStateChanged();
  39264. /** @internal */
  39265. void focusLost (FocusChangeType cause);
  39266. /** @internal */
  39267. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  39268. /** @internal */
  39269. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  39270. /** @internal */
  39271. void handleAsyncUpdate();
  39272. /** @internal */
  39273. void colourChanged();
  39274. juce_UseDebuggingNewOperator
  39275. protected:
  39276. friend class MidiKeyboardUpDownButton;
  39277. /** Draws a white note in the given rectangle.
  39278. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39279. currently pressed down.
  39280. When doing this, be sure to note the keyboard's orientation.
  39281. */
  39282. virtual void drawWhiteNote (int midiNoteNumber,
  39283. Graphics& g,
  39284. int x, int y, int w, int h,
  39285. bool isDown, bool isOver,
  39286. const Colour& lineColour,
  39287. const Colour& textColour);
  39288. /** Draws a black note in the given rectangle.
  39289. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39290. currently pressed down.
  39291. When doing this, be sure to note the keyboard's orientation.
  39292. */
  39293. virtual void drawBlackNote (int midiNoteNumber,
  39294. Graphics& g,
  39295. int x, int y, int w, int h,
  39296. bool isDown, bool isOver,
  39297. const Colour& noteFillColour);
  39298. /** Allows text to be drawn on the white notes.
  39299. By default this is used to label the C in each octave, but could be used for other things.
  39300. @see setOctaveForMiddleC
  39301. */
  39302. virtual const String getWhiteNoteText (const int midiNoteNumber);
  39303. /** Draws the up and down buttons that change the base note. */
  39304. virtual void drawUpDownButton (Graphics& g, int w, int h,
  39305. const bool isMouseOver,
  39306. const bool isButtonPressed,
  39307. const bool movesOctavesUp);
  39308. /** Callback when the mouse is clicked on a key.
  39309. You could use this to do things like handle right-clicks on keys, etc.
  39310. Return true if you want the click to trigger the note, or false if you
  39311. want to handle it yourself and not have the note played.
  39312. @see mouseDraggedToKey
  39313. */
  39314. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  39315. /** Callback when the mouse is dragged from one key onto another.
  39316. @see mouseDownOnKey
  39317. */
  39318. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  39319. /** Calculates the positon of a given midi-note.
  39320. This can be overridden to create layouts with custom key-widths.
  39321. @param midiNoteNumber the note to find
  39322. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  39323. @param x the x position of the left-hand edge of the key (this method
  39324. always works in terms of a horizontal keyboard)
  39325. @param w the width of the key
  39326. */
  39327. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  39328. int& x, int& w) const;
  39329. private:
  39330. MidiKeyboardState& state;
  39331. int xOffset, blackNoteLength;
  39332. float keyWidth;
  39333. Orientation orientation;
  39334. int midiChannel, midiInChannelMask;
  39335. float velocity;
  39336. int noteUnderMouse, mouseDownNote;
  39337. BitArray keysPressed, keysCurrentlyDrawnDown;
  39338. int rangeStart, rangeEnd, firstKey;
  39339. bool canScroll, mouseDragging;
  39340. Button* scrollDown;
  39341. Button* scrollUp;
  39342. Array <KeyPress> keyPresses;
  39343. Array <int> keyPressNotes;
  39344. int keyMappingOctave;
  39345. int octaveNumForMiddleC;
  39346. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  39347. int xyToNote (int x, int y);
  39348. int remappedXYToNote (int x, int y) const;
  39349. void resetAnyKeysInUse();
  39350. void updateNoteUnderMouse (int x, int y);
  39351. void repaintNote (const int midiNoteNumber);
  39352. MidiKeyboardComponent (const MidiKeyboardComponent&);
  39353. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  39354. };
  39355. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39356. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  39357. #endif
  39358. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39359. /********* Start of inlined file: juce_NSViewComponent.h *********/
  39360. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39361. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39362. #if ! DOXYGEN
  39363. class NSViewComponentInternal;
  39364. #endif
  39365. #if JUCE_MAC || DOXYGEN
  39366. /**
  39367. A Mac-specific class that can create and embed an NSView inside itself.
  39368. To use it, create one of these, put it in place and make sure it's visible in a
  39369. window, then use setView() to assign an NSView to it. The view will then be
  39370. moved and resized to follow the movements of this component.
  39371. Of course, since the view is a native object, it'll obliterate any
  39372. juce components that may overlap this component, but that's life.
  39373. */
  39374. class JUCE_API NSViewComponent : public Component
  39375. {
  39376. public:
  39377. /** Create an initially-empty container. */
  39378. NSViewComponent();
  39379. /** Destructor. */
  39380. ~NSViewComponent();
  39381. /** Assigns an NSView to this peer.
  39382. The view will be retained and released by this component for as long as
  39383. it is needed. To remove the current view, just call setView (0).
  39384. Note: a void* is used here to avoid including the cocoa headers as
  39385. part of the juce.h, but the method expects an NSView*.
  39386. */
  39387. void setView (void* nsView);
  39388. /** Returns the current NSView.
  39389. Note: a void* is returned here to avoid including the cocoa headers as
  39390. a requirement of juce.h, so you should just cast the object to an NSView*.
  39391. */
  39392. void* getView() const;
  39393. /** @internal */
  39394. void paint (Graphics& g);
  39395. juce_UseDebuggingNewOperator
  39396. private:
  39397. friend class NSViewComponentInternal;
  39398. NSViewComponentInternal* info;
  39399. NSViewComponent (const NSViewComponent&);
  39400. const NSViewComponent& operator= (const NSViewComponent&);
  39401. };
  39402. #endif
  39403. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39404. /********* End of inlined file: juce_NSViewComponent.h *********/
  39405. #endif
  39406. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39407. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  39408. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39409. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39410. // this is used to disable OpenGL, and is defined in juce_Config.h
  39411. #if JUCE_OPENGL || DOXYGEN
  39412. class OpenGLComponentWatcher;
  39413. /**
  39414. Represents the various properties of an OpenGL bitmap format.
  39415. @see OpenGLComponent::setPixelFormat
  39416. */
  39417. struct OpenGLPixelFormat
  39418. {
  39419. /** Creates an OpenGLPixelFormat.
  39420. The default constructor just initialises the object as a simple 8-bit
  39421. RGBA format.
  39422. */
  39423. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  39424. const int alphaBits = 8,
  39425. const int depthBufferBits = 16,
  39426. const int stencilBufferBits = 0) throw();
  39427. int redBits; /**< The number of bits per pixel to use for the red channel. */
  39428. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  39429. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  39430. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  39431. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  39432. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  39433. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  39434. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  39435. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  39436. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  39437. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  39438. /** Returns a list of all the pixel formats that can be used in this system.
  39439. A reference component is needed in case there are multiple screens with different
  39440. capabilities - in which case, the one that the component is on will be used.
  39441. */
  39442. static void getAvailablePixelFormats (Component* component,
  39443. OwnedArray <OpenGLPixelFormat>& results);
  39444. bool operator== (const OpenGLPixelFormat&) const throw();
  39445. juce_UseDebuggingNewOperator
  39446. };
  39447. /**
  39448. A base class for types of OpenGL context.
  39449. An OpenGLComponent will supply its own context for drawing in its window.
  39450. */
  39451. class OpenGLContext
  39452. {
  39453. public:
  39454. /** Destructor. */
  39455. virtual ~OpenGLContext();
  39456. /** Makes this context the currently active one. */
  39457. virtual bool makeActive() const throw() = 0;
  39458. /** If this context is currently active, it is disactivated. */
  39459. virtual bool makeInactive() const throw() = 0;
  39460. /** Returns true if this context is currently active. */
  39461. virtual bool isActive() const throw() = 0;
  39462. /** Swaps the buffers (if the context can do this). */
  39463. virtual void swapBuffers() = 0;
  39464. /** Sets whether the context checks the vertical sync before swapping.
  39465. The value is the number of frames to allow between buffer-swapping. This is
  39466. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  39467. and greater numbers indicate that it should swap less often.
  39468. Returns true if it sets the value successfully.
  39469. */
  39470. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  39471. /** Returns the current swap-sync interval.
  39472. See setSwapInterval() for info about the value returned.
  39473. */
  39474. virtual int getSwapInterval() const = 0;
  39475. /** Returns the pixel format being used by this context. */
  39476. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  39477. /** For windowed contexts, this moves the context within the bounds of
  39478. its parent window.
  39479. */
  39480. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  39481. /** For windowed contexts, this triggers a repaint of the window.
  39482. (Not relevent on all platforms).
  39483. */
  39484. virtual void repaint() = 0;
  39485. /** Returns an OS-dependent handle to the raw GL context.
  39486. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  39487. a GLXContext.
  39488. */
  39489. virtual void* getRawContext() const throw() = 0;
  39490. /** This tries to create a context that can be used for drawing into the
  39491. area occupied by the specified component.
  39492. Note that you probably shouldn't use this method directly unless you know what
  39493. you're doing - the OpenGLComponent calls this and manages the context for you.
  39494. */
  39495. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  39496. const OpenGLPixelFormat& pixelFormat,
  39497. const OpenGLContext* const contextToShareWith);
  39498. /** Returns the context that's currently in active use by the calling thread.
  39499. Returns 0 if there isn't an active context.
  39500. */
  39501. static OpenGLContext* getCurrentContext();
  39502. juce_UseDebuggingNewOperator
  39503. protected:
  39504. OpenGLContext() throw();
  39505. };
  39506. /**
  39507. A component that contains an OpenGL canvas.
  39508. Override this, add it to whatever component you want to, and use the renderOpenGL()
  39509. method to draw its contents.
  39510. */
  39511. class JUCE_API OpenGLComponent : public Component
  39512. {
  39513. public:
  39514. /** Creates an OpenGLComponent.
  39515. */
  39516. OpenGLComponent();
  39517. /** Destructor. */
  39518. ~OpenGLComponent();
  39519. /** Changes the pixel format used by this component.
  39520. @see OpenGLPixelFormat::getAvailablePixelFormats()
  39521. */
  39522. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  39523. /** Returns the pixel format that this component is currently using. */
  39524. const OpenGLPixelFormat getPixelFormat() const;
  39525. /** Specifies an OpenGL context which should be shared with the one that this
  39526. component is using.
  39527. This is an OpenGL feature that lets two contexts share their texture data.
  39528. Note that this pointer is stored by the component, and when the component
  39529. needs to recreate its internal context for some reason, the same context
  39530. will be used again to share lists. So if you pass a context in here,
  39531. don't delete the context while this component is still using it! You can
  39532. call shareWith (0) to stop this component from sharing with it.
  39533. */
  39534. void shareWith (OpenGLContext* contextToShareListsWith);
  39535. /** Returns the context that this component is sharing with.
  39536. @see shareWith
  39537. */
  39538. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  39539. /** Flips the openGL buffers over. */
  39540. void swapBuffers();
  39541. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  39542. When this is called, makeCurrentContextActive() will already have been called
  39543. for you, so you just need to draw.
  39544. */
  39545. virtual void renderOpenGL() = 0;
  39546. /** This method is called when the component creates a new OpenGL context.
  39547. A new context may be created when the component is first used, or when it
  39548. is moved to a different window, or when the window is hidden and re-shown,
  39549. etc.
  39550. You can use this callback as an opportunity to set up things like textures
  39551. that your context needs.
  39552. New contexts are created on-demand by the makeCurrentContextActive() method - so
  39553. if the context is deleted, e.g. by changing the pixel format or window, no context
  39554. will be created until the next call to makeCurrentContextActive(), which will
  39555. synchronously create one and call this method. This means that if you're using
  39556. a non-GUI thread for rendering, you can make sure this method is be called by
  39557. your renderer thread.
  39558. When this callback happens, the context will already have been made current
  39559. using the makeCurrentContextActive() method, so there's no need to call it
  39560. again in your code.
  39561. */
  39562. virtual void newOpenGLContextCreated() = 0;
  39563. /** Returns the context that will draw into this component.
  39564. This may return 0 if the component is currently invisible or hasn't currently
  39565. got a context. The context object can be deleted and a new one created during
  39566. the lifetime of this component, and there may be times when it doesn't have one.
  39567. @see newOpenGLContextCreated()
  39568. */
  39569. OpenGLContext* getCurrentContext() const throw() { return context; }
  39570. /** Makes this component the current openGL context.
  39571. You might want to use this in things like your resize() method, before calling
  39572. GL commands.
  39573. If this returns false, then the context isn't active, so you should avoid
  39574. making any calls.
  39575. This call may actually create a context if one isn't currently initialised. If
  39576. it does this, it will also synchronously call the newOpenGLContextCreated()
  39577. method to let you initialise it as necessary.
  39578. @see OpenGLContext::makeActive
  39579. */
  39580. bool makeCurrentContextActive();
  39581. /** Stops the current component being the active OpenGL context.
  39582. This is the opposite of makeCurrentContextActive()
  39583. @see OpenGLContext::makeInactive
  39584. */
  39585. void makeCurrentContextInactive();
  39586. /** Returns true if this component is the active openGL context for the
  39587. current thread.
  39588. @see OpenGLContext::isActive
  39589. */
  39590. bool isActiveContext() const throw();
  39591. /** Calls the rendering callback, and swaps the buffers afterwards.
  39592. This is called automatically by paint() when the component needs to be rendered.
  39593. It can be overridden if you need to decouple the rendering from the paint callback
  39594. and render with a custom thread.
  39595. Returns true if the operation succeeded.
  39596. */
  39597. virtual bool renderAndSwapBuffers();
  39598. /** This returns a critical section that can be used to lock the current context.
  39599. Because the context that is used by this component can change, e.g. when the
  39600. component is shown or hidden, then if you're rendering to it on a background
  39601. thread, this allows you to lock the context for the duration of your rendering
  39602. routine.
  39603. */
  39604. CriticalSection& getContextLock() throw() { return contextLock; }
  39605. /** @internal */
  39606. void paint (Graphics& g);
  39607. /** Returns the native handle of an embedded heavyweight window, if there is one.
  39608. E.g. On windows, this will return the HWND of the sub-window containing
  39609. the opengl context, on the mac it'll be the NSOpenGLView.
  39610. */
  39611. void* getNativeWindowHandle() const;
  39612. juce_UseDebuggingNewOperator
  39613. private:
  39614. friend class OpenGLComponentWatcher;
  39615. OpenGLComponentWatcher* componentWatcher;
  39616. OpenGLContext* context;
  39617. OpenGLContext* contextToShareListsWith;
  39618. CriticalSection contextLock;
  39619. OpenGLPixelFormat preferredPixelFormat;
  39620. bool needToUpdateViewport;
  39621. void deleteContext();
  39622. void updateContextPosition();
  39623. void internalRepaint (int x, int y, int w, int h);
  39624. OpenGLComponent (const OpenGLComponent&);
  39625. const OpenGLComponent& operator= (const OpenGLComponent&);
  39626. };
  39627. #endif
  39628. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39629. /********* End of inlined file: juce_OpenGLComponent.h *********/
  39630. #endif
  39631. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39632. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  39633. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39634. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39635. /**
  39636. A component with a set of buttons at the top for changing between pages of
  39637. preferences.
  39638. This is just a handy way of writing a Mac-style preferences panel where you
  39639. have a row of buttons along the top for the different preference categories,
  39640. each button having an icon above its name. Clicking these will show an
  39641. appropriate prefs page below it.
  39642. You can either put one of these inside your own component, or just use the
  39643. showInDialogBox() method to show it in a window and run it modally.
  39644. To use it, just add a set of named pages with the addSettingsPage() method,
  39645. and implement the createComponentForPage() method to create suitable components
  39646. for each of these pages.
  39647. */
  39648. class JUCE_API PreferencesPanel : public Component,
  39649. private ButtonListener
  39650. {
  39651. public:
  39652. /** Creates an empty panel.
  39653. Use addSettingsPage() to add some pages to it in your constructor.
  39654. */
  39655. PreferencesPanel();
  39656. /** Destructor. */
  39657. ~PreferencesPanel();
  39658. /** Creates a page using a set of drawables to define the page's icon.
  39659. Note that the other version of this method is much easier if you're using
  39660. an image instead of a custom drawable.
  39661. @param pageTitle the name of this preferences page - you'll need to
  39662. make sure your createComponentForPage() method creates
  39663. a suitable component when it is passed this name
  39664. @param normalIcon the drawable to display in the page's button normally
  39665. @param overIcon the drawable to display in the page's button when the mouse is over
  39666. @param downIcon the drawable to display in the page's button when the button is down
  39667. @see DrawableButton
  39668. */
  39669. void addSettingsPage (const String& pageTitle,
  39670. const Drawable* normalIcon,
  39671. const Drawable* overIcon,
  39672. const Drawable* downIcon);
  39673. /** Creates a page using a set of drawables to define the page's icon.
  39674. The other version of this method gives you more control over the icon, but this
  39675. one is much easier if you're just loading it from a file.
  39676. @param pageTitle the name of this preferences page - you'll need to
  39677. make sure your createComponentForPage() method creates
  39678. a suitable component when it is passed this name
  39679. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  39680. For this to look good, you'll probably want to use a nice
  39681. transparent png file.
  39682. @param imageDataSize the size of the image data, in bytes
  39683. */
  39684. void addSettingsPage (const String& pageTitle,
  39685. const char* imageData,
  39686. const int imageDataSize);
  39687. /** Utility method to display this panel in a DialogWindow.
  39688. Calling this will create a DialogWindow containing this panel with the
  39689. given size and title, and will run it modally, returning when the user
  39690. closes the dialog box.
  39691. */
  39692. void showInDialogBox (const String& dialogtitle,
  39693. int dialogWidth,
  39694. int dialogHeight,
  39695. const Colour& backgroundColour = Colours::white);
  39696. /** Subclasses must override this to return a component for each preferences page.
  39697. The subclass should return a pointer to a new component representing the named
  39698. page, which the panel will then display.
  39699. The panel will delete the component later when the user goes to another page
  39700. or deletes the panel.
  39701. */
  39702. virtual Component* createComponentForPage (const String& pageName) = 0;
  39703. /** Changes the current page being displayed. */
  39704. void setCurrentPage (const String& pageName);
  39705. /** @internal */
  39706. void resized();
  39707. /** @internal */
  39708. void paint (Graphics& g);
  39709. /** @internal */
  39710. void buttonClicked (Button* button);
  39711. juce_UseDebuggingNewOperator
  39712. private:
  39713. String currentPageName;
  39714. Component* currentPage;
  39715. int buttonSize;
  39716. PreferencesPanel (const PreferencesPanel&);
  39717. const PreferencesPanel& operator= (const PreferencesPanel&);
  39718. };
  39719. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39720. /********* End of inlined file: juce_PreferencesPanel.h *********/
  39721. #endif
  39722. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39723. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  39724. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39725. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39726. // this is used to disable QuickTime, and is defined in juce_Config.h
  39727. #if JUCE_QUICKTIME || DOXYGEN
  39728. #if JUCE_WIN32
  39729. typedef ActiveXControlComponent QTCompBaseClass;
  39730. #else
  39731. typedef NSViewComponent QTCompBaseClass;
  39732. #endif
  39733. /**
  39734. A window that can play back a QuickTime movie.
  39735. */
  39736. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  39737. {
  39738. public:
  39739. /** Creates a QuickTimeMovieComponent, initially blank.
  39740. Use the loadMovie() method to load a movie once you've added the
  39741. component to a window, (or put it on the desktop as a heavyweight window).
  39742. Loading a movie when the component isn't visible can cause problems, as
  39743. QuickTime needs a window handle to initialise properly.
  39744. */
  39745. QuickTimeMovieComponent();
  39746. /** Destructor. */
  39747. ~QuickTimeMovieComponent();
  39748. /** Returns true if QT is installed and working on this machine.
  39749. */
  39750. static bool isQuickTimeAvailable() throw();
  39751. /** Tries to load a QuickTime movie into the player.
  39752. It's best to call this function once you've added the component to a window,
  39753. (or put it on the desktop as a heavyweight window). Loading a movie when the
  39754. component isn't visible can cause problems, because QuickTime needs a window
  39755. handle to do its stuff.
  39756. @param movieFile the .mov file to open
  39757. @param isControllerVisible whether to show a controller bar at the bottom
  39758. @returns true if the movie opens successfully
  39759. */
  39760. bool loadMovie (const File& movieFile,
  39761. const bool isControllerVisible);
  39762. bool loadMovie (InputStream* movieStream,
  39763. const bool isControllerVisible);
  39764. /** Closes the movie, if one is open. */
  39765. void closeMovie();
  39766. /** Returns the movie file that is currently open.
  39767. If there isn't one, this returns File::nonexistent
  39768. */
  39769. const File getCurrentMovieFile() const;
  39770. /** Returns true if there's currently a movie open. */
  39771. bool isMovieOpen() const;
  39772. /** Returns the length of the movie, in seconds. */
  39773. double getMovieDuration() const;
  39774. /** Returns the movie's natural size, in pixels.
  39775. You can use this to resize the component to show the movie at its preferred
  39776. scale.
  39777. If no movie is loaded, the size returned will be 0 x 0.
  39778. */
  39779. void getMovieNormalSize (int& width, int& height) const;
  39780. /** This will position the component within a given area, keeping its aspect
  39781. ratio correct according to the movie's normal size.
  39782. The component will be made as large as it can go within the space, and will
  39783. be aligned according to the justification value if this means there are gaps at
  39784. the top or sides.
  39785. */
  39786. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  39787. const RectanglePlacement& placement);
  39788. /** Starts the movie playing. */
  39789. void play();
  39790. /** Stops the movie playing. */
  39791. void stop();
  39792. /** Returns true if the movie is currently playing. */
  39793. bool isPlaying() const;
  39794. /** Moves the movie's position back to the start. */
  39795. void goToStart();
  39796. /** Sets the movie's position to a given time. */
  39797. void setPosition (const double seconds);
  39798. /** Returns the current play position of the movie. */
  39799. double getPosition() const;
  39800. /** Changes the movie playback rate.
  39801. A value of 1 is normal speed, greater values play it proportionately faster,
  39802. smaller values play it slower.
  39803. */
  39804. void setSpeed (const float newSpeed);
  39805. /** Changes the movie's playback volume.
  39806. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39807. */
  39808. void setMovieVolume (const float newVolume);
  39809. /** Returns the movie's playback volume.
  39810. @returns the volume in the range 0 (silent) to 1.0 (full)
  39811. */
  39812. float getMovieVolume() const;
  39813. /** Tells the movie whether it should loop. */
  39814. void setLooping (const bool shouldLoop);
  39815. /** Returns true if the movie is currently looping.
  39816. @see setLooping
  39817. */
  39818. bool isLooping() const;
  39819. /** True if the native QuickTime controller bar is shown in the window.
  39820. @see loadMovie
  39821. */
  39822. bool isControllerVisible() const;
  39823. /** @internal */
  39824. void paint (Graphics& g);
  39825. juce_UseDebuggingNewOperator
  39826. private:
  39827. File movieFile;
  39828. bool movieLoaded, controllerVisible, looping;
  39829. #if JUCE_WIN32
  39830. /** @internal */
  39831. void parentHierarchyChanged();
  39832. /** @internal */
  39833. void visibilityChanged();
  39834. void createControlIfNeeded();
  39835. bool isControlCreated() const;
  39836. void* internal;
  39837. #else
  39838. void* movie;
  39839. #endif
  39840. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39841. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39842. };
  39843. #endif
  39844. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39845. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39846. #endif
  39847. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39848. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39849. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39850. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39851. class ToggleButton;
  39852. class TextButton;
  39853. class AlertWindow;
  39854. class TextLayout;
  39855. class ScrollBar;
  39856. class BubbleComponent;
  39857. class ComboBox;
  39858. class Button;
  39859. class FilenameComponent;
  39860. class DocumentWindow;
  39861. class ResizableWindow;
  39862. class GroupComponent;
  39863. class MenuBarComponent;
  39864. class DropShadower;
  39865. class GlyphArrangement;
  39866. class PropertyComponent;
  39867. class TableHeaderComponent;
  39868. class Toolbar;
  39869. class ToolbarItemComponent;
  39870. class PopupMenu;
  39871. class ProgressBar;
  39872. class FileBrowserComponent;
  39873. class DirectoryContentsDisplayComponent;
  39874. class FilePreviewComponent;
  39875. class ImageButton;
  39876. /**
  39877. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39878. can be used to apply different 'skins' to the application.
  39879. */
  39880. class JUCE_API LookAndFeel
  39881. {
  39882. public:
  39883. /** Creates the default JUCE look and feel. */
  39884. LookAndFeel();
  39885. /** Destructor. */
  39886. virtual ~LookAndFeel();
  39887. /** Returns the current default look-and-feel for a component to use when it
  39888. hasn't got one explicitly set.
  39889. @see setDefaultLookAndFeel
  39890. */
  39891. static LookAndFeel& getDefaultLookAndFeel() throw();
  39892. /** Changes the default look-and-feel.
  39893. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39894. set to 0, it will revert to using the default one. The
  39895. object passed-in must be deleted by the caller when
  39896. it's no longer needed.
  39897. @see getDefaultLookAndFeel
  39898. */
  39899. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39900. /** Looks for a colour that has been registered with the given colour ID number.
  39901. If a colour has been set for this ID number using setColour(), then it is
  39902. returned. If none has been set, it will just return Colours::black.
  39903. The colour IDs for various purposes are stored as enums in the components that
  39904. they are relevent to - for an example, see Slider::ColourIds,
  39905. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39906. If you're looking up a colour for use in drawing a component, it's usually
  39907. best not to call this directly, but to use the Component::findColour() method
  39908. instead. That will first check whether a suitable colour has been registered
  39909. directly with the component, and will fall-back on calling the component's
  39910. LookAndFeel's findColour() method if none is found.
  39911. @see setColour, Component::findColour, Component::setColour
  39912. */
  39913. const Colour findColour (const int colourId) const throw();
  39914. /** Registers a colour to be used for a particular purpose.
  39915. For more details, see the comments for findColour().
  39916. @see findColour, Component::findColour, Component::setColour
  39917. */
  39918. void setColour (const int colourId, const Colour& colour) throw();
  39919. /** Returns true if the specified colour ID has been explicitly set using the
  39920. setColour() method.
  39921. */
  39922. bool isColourSpecified (const int colourId) const throw();
  39923. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  39924. /** Allows you to change the default sans-serif font.
  39925. If you need to supply your own Typeface object for any of the default fonts, rather
  39926. than just supplying the name (e.g. if you want to use an embedded font), then
  39927. you should instead override getTypefaceForFont() to create and return the typeface.
  39928. */
  39929. void setDefaultSansSerifTypefaceName (const String& newName);
  39930. /** Draws the lozenge-shaped background for a standard button. */
  39931. virtual void drawButtonBackground (Graphics& g,
  39932. Button& button,
  39933. const Colour& backgroundColour,
  39934. bool isMouseOverButton,
  39935. bool isButtonDown);
  39936. /** Draws the text for a TextButton. */
  39937. virtual void drawButtonText (Graphics& g,
  39938. TextButton& button,
  39939. bool isMouseOverButton,
  39940. bool isButtonDown);
  39941. /** Draws the contents of a standard ToggleButton. */
  39942. virtual void drawToggleButton (Graphics& g,
  39943. ToggleButton& button,
  39944. bool isMouseOverButton,
  39945. bool isButtonDown);
  39946. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39947. virtual void drawTickBox (Graphics& g,
  39948. Component& component,
  39949. int x, int y, int w, int h,
  39950. const bool ticked,
  39951. const bool isEnabled,
  39952. const bool isMouseOverButton,
  39953. const bool isButtonDown);
  39954. /** AlertWindow handling..
  39955. */
  39956. virtual AlertWindow* createAlertWindow (const String& title,
  39957. const String& message,
  39958. const String& button1,
  39959. const String& button2,
  39960. const String& button3,
  39961. AlertWindow::AlertIconType iconType,
  39962. int numButtons,
  39963. Component* associatedComponent);
  39964. virtual void drawAlertBox (Graphics& g,
  39965. AlertWindow& alert,
  39966. const Rectangle& textArea,
  39967. TextLayout& textLayout);
  39968. virtual int getAlertBoxWindowFlags();
  39969. virtual int getAlertWindowButtonHeight();
  39970. virtual const Font getAlertWindowFont();
  39971. /** Draws a progress bar.
  39972. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39973. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39974. isn't known). It can use the current time as a basis for playing an animation.
  39975. (Used by progress bars in AlertWindow).
  39976. */
  39977. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39978. int width, int height,
  39979. double progress, const String& textToShow);
  39980. /** Draws one of the buttons on a scrollbar.
  39981. @param g the context to draw into
  39982. @param scrollbar the bar itself
  39983. @param width the width of the button
  39984. @param height the height of the button
  39985. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39986. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39987. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39988. @param isButtonDown whether the mouse button's held down
  39989. */
  39990. virtual void drawScrollbarButton (Graphics& g,
  39991. ScrollBar& scrollbar,
  39992. int width, int height,
  39993. int buttonDirection,
  39994. bool isScrollbarVertical,
  39995. bool isMouseOverButton,
  39996. bool isButtonDown);
  39997. /** Draws the thumb area of a scrollbar.
  39998. @param g the context to draw into
  39999. @param scrollbar the bar itself
  40000. @param x the x position of the left edge of the thumb area to draw in
  40001. @param y the y position of the top edge of the thumb area to draw in
  40002. @param width the width of the thumb area to draw in
  40003. @param height the height of the thumb area to draw in
  40004. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40005. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40006. thumb, or its x position for horizontal bars
  40007. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40008. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40009. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40010. currently dragging the thumb
  40011. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40012. */
  40013. virtual void drawScrollbar (Graphics& g,
  40014. ScrollBar& scrollbar,
  40015. int x, int y,
  40016. int width, int height,
  40017. bool isScrollbarVertical,
  40018. int thumbStartPosition,
  40019. int thumbSize,
  40020. bool isMouseOver,
  40021. bool isMouseDown);
  40022. /** Returns the component effect to use for a scrollbar */
  40023. virtual ImageEffectFilter* getScrollbarEffect();
  40024. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40025. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40026. /** Returns the default thickness to use for a scrollbar. */
  40027. virtual int getDefaultScrollbarWidth();
  40028. /** Returns the length in pixels to use for a scrollbar button. */
  40029. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40030. /** Returns a tick shape for use in yes/no boxes, etc. */
  40031. virtual const Path getTickShape (const float height);
  40032. /** Returns a cross shape for use in yes/no boxes, etc. */
  40033. virtual const Path getCrossShape (const float height);
  40034. /** Draws the + or - box in a treeview. */
  40035. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40036. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40037. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40038. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40039. virtual Image* getDefaultFolderImage();
  40040. virtual Image* getDefaultDocumentFileImage();
  40041. virtual void createFileChooserHeaderText (const String& title,
  40042. const String& instructions,
  40043. GlyphArrangement& destArrangement,
  40044. int width);
  40045. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40046. const String& filename, Image* icon,
  40047. const String& fileSizeDescription,
  40048. const String& fileTimeDescription,
  40049. const bool isDirectory,
  40050. const bool isItemSelected,
  40051. const int itemIndex);
  40052. virtual Button* createFileBrowserGoUpButton();
  40053. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40054. DirectoryContentsDisplayComponent* fileListComponent,
  40055. FilePreviewComponent* previewComp,
  40056. ComboBox* currentPathBox,
  40057. TextEditor* filenameBox,
  40058. Button* goUpButton);
  40059. virtual void drawBubble (Graphics& g,
  40060. float tipX, float tipY,
  40061. float boxX, float boxY, float boxW, float boxH);
  40062. /** Fills the background of a popup menu component. */
  40063. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40064. /** Draws one of the items in a popup menu. */
  40065. virtual void drawPopupMenuItem (Graphics& g,
  40066. int width, int height,
  40067. const bool isSeparator,
  40068. const bool isActive,
  40069. const bool isHighlighted,
  40070. const bool isTicked,
  40071. const bool hasSubMenu,
  40072. const String& text,
  40073. const String& shortcutKeyText,
  40074. Image* image,
  40075. const Colour* const textColour);
  40076. /** Returns the size and style of font to use in popup menus. */
  40077. virtual const Font getPopupMenuFont();
  40078. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40079. int width, int height,
  40080. bool isScrollUpArrow);
  40081. /** Finds the best size for an item in a popup menu. */
  40082. virtual void getIdealPopupMenuItemSize (const String& text,
  40083. const bool isSeparator,
  40084. int standardMenuItemHeight,
  40085. int& idealWidth,
  40086. int& idealHeight);
  40087. virtual int getMenuWindowFlags();
  40088. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40089. bool isMouseOverBar,
  40090. MenuBarComponent& menuBar);
  40091. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40092. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40093. virtual void drawMenuBarItem (Graphics& g,
  40094. int width, int height,
  40095. int itemIndex,
  40096. const String& itemText,
  40097. bool isMouseOverItem,
  40098. bool isMenuOpen,
  40099. bool isMouseOverBar,
  40100. MenuBarComponent& menuBar);
  40101. virtual void drawComboBox (Graphics& g, int width, int height,
  40102. const bool isButtonDown,
  40103. int buttonX, int buttonY,
  40104. int buttonW, int buttonH,
  40105. ComboBox& box);
  40106. virtual const Font getComboBoxFont (ComboBox& box);
  40107. virtual Label* createComboBoxTextBox (ComboBox& box);
  40108. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40109. virtual void drawLabel (Graphics& g, Label& label);
  40110. virtual void drawLinearSlider (Graphics& g,
  40111. int x, int y,
  40112. int width, int height,
  40113. float sliderPos,
  40114. float minSliderPos,
  40115. float maxSliderPos,
  40116. const Slider::SliderStyle style,
  40117. Slider& slider);
  40118. virtual void drawLinearSliderBackground (Graphics& g,
  40119. int x, int y,
  40120. int width, int height,
  40121. float sliderPos,
  40122. float minSliderPos,
  40123. float maxSliderPos,
  40124. const Slider::SliderStyle style,
  40125. Slider& slider);
  40126. virtual void drawLinearSliderThumb (Graphics& g,
  40127. int x, int y,
  40128. int width, int height,
  40129. float sliderPos,
  40130. float minSliderPos,
  40131. float maxSliderPos,
  40132. const Slider::SliderStyle style,
  40133. Slider& slider);
  40134. virtual int getSliderThumbRadius (Slider& slider);
  40135. virtual void drawRotarySlider (Graphics& g,
  40136. int x, int y,
  40137. int width, int height,
  40138. float sliderPosProportional,
  40139. const float rotaryStartAngle,
  40140. const float rotaryEndAngle,
  40141. Slider& slider);
  40142. virtual Button* createSliderButton (const bool isIncrement);
  40143. virtual Label* createSliderTextBox (Slider& slider);
  40144. virtual ImageEffectFilter* getSliderEffect();
  40145. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40146. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40147. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40148. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40149. ComboBox* filenameBox, Button* browseButton);
  40150. virtual void drawCornerResizer (Graphics& g,
  40151. int w, int h,
  40152. bool isMouseOver,
  40153. bool isMouseDragging);
  40154. virtual void drawResizableFrame (Graphics& g,
  40155. int w, int h,
  40156. const BorderSize& borders);
  40157. virtual void drawResizableWindowBorder (Graphics& g,
  40158. int w, int h,
  40159. const BorderSize& border,
  40160. ResizableWindow& window);
  40161. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40162. Graphics& g, int w, int h,
  40163. int titleSpaceX, int titleSpaceW,
  40164. const Image* icon,
  40165. bool drawTitleTextOnLeft);
  40166. virtual Button* createDocumentWindowButton (int buttonType);
  40167. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40168. int titleBarX, int titleBarY,
  40169. int titleBarW, int titleBarH,
  40170. Button* minimiseButton,
  40171. Button* maximiseButton,
  40172. Button* closeButton,
  40173. bool positionTitleBarButtonsOnLeft);
  40174. virtual int getDefaultMenuBarHeight();
  40175. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40176. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40177. int w, int h,
  40178. bool isVerticalBar,
  40179. bool isMouseOver,
  40180. bool isMouseDragging);
  40181. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40182. const String& text,
  40183. const Justification& position,
  40184. GroupComponent& group);
  40185. virtual void createTabButtonShape (Path& p,
  40186. int width, int height,
  40187. int tabIndex,
  40188. const String& text,
  40189. Button& button,
  40190. TabbedButtonBar::Orientation orientation,
  40191. const bool isMouseOver,
  40192. const bool isMouseDown,
  40193. const bool isFrontTab);
  40194. virtual void fillTabButtonShape (Graphics& g,
  40195. const Path& path,
  40196. const Colour& preferredBackgroundColour,
  40197. int tabIndex,
  40198. const String& text,
  40199. Button& button,
  40200. TabbedButtonBar::Orientation orientation,
  40201. const bool isMouseOver,
  40202. const bool isMouseDown,
  40203. const bool isFrontTab);
  40204. virtual void drawTabButtonText (Graphics& g,
  40205. int x, int y, int w, int h,
  40206. const Colour& preferredBackgroundColour,
  40207. int tabIndex,
  40208. const String& text,
  40209. Button& button,
  40210. TabbedButtonBar::Orientation orientation,
  40211. const bool isMouseOver,
  40212. const bool isMouseDown,
  40213. const bool isFrontTab);
  40214. virtual int getTabButtonOverlap (int tabDepth);
  40215. virtual int getTabButtonSpaceAroundImage();
  40216. virtual int getTabButtonBestWidth (int tabIndex,
  40217. const String& text,
  40218. int tabDepth,
  40219. Button& button);
  40220. virtual void drawTabButton (Graphics& g,
  40221. int w, int h,
  40222. const Colour& preferredColour,
  40223. int tabIndex,
  40224. const String& text,
  40225. Button& button,
  40226. TabbedButtonBar::Orientation orientation,
  40227. const bool isMouseOver,
  40228. const bool isMouseDown,
  40229. const bool isFrontTab);
  40230. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40231. int w, int h,
  40232. TabbedButtonBar& tabBar,
  40233. TabbedButtonBar::Orientation orientation);
  40234. virtual Button* createTabBarExtrasButton();
  40235. virtual void drawImageButton (Graphics& g, Image* image,
  40236. int imageX, int imageY, int imageW, int imageH,
  40237. const Colour& overlayColour,
  40238. float imageOpacity,
  40239. ImageButton& button);
  40240. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40241. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40242. int width, int height,
  40243. bool isMouseOver, bool isMouseDown,
  40244. int columnFlags);
  40245. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40246. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40247. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40248. bool isMouseOver, bool isMouseDown,
  40249. ToolbarItemComponent& component);
  40250. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40251. const String& text, ToolbarItemComponent& component);
  40252. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40253. bool isOpen, int width, int height);
  40254. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40255. PropertyComponent& component);
  40256. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40257. PropertyComponent& component);
  40258. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  40259. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40260. /**
  40261. */
  40262. virtual void playAlertSound();
  40263. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40264. static void drawGlassSphere (Graphics& g,
  40265. const float x, const float y,
  40266. const float diameter,
  40267. const Colour& colour,
  40268. const float outlineThickness) throw();
  40269. static void drawGlassPointer (Graphics& g,
  40270. const float x, const float y,
  40271. const float diameter,
  40272. const Colour& colour, const float outlineThickness,
  40273. const int direction) throw();
  40274. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40275. static void drawGlassLozenge (Graphics& g,
  40276. const float x, const float y,
  40277. const float width, const float height,
  40278. const Colour& colour,
  40279. const float outlineThickness,
  40280. const float cornerSize,
  40281. const bool flatOnLeft, const bool flatOnRight,
  40282. const bool flatOnTop, const bool flatOnBottom) throw();
  40283. juce_UseDebuggingNewOperator
  40284. protected:
  40285. // xxx the following methods are only here to cause a compiler error, because they've been
  40286. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  40287. // error if you try to build a subclass with the old versions.
  40288. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  40289. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  40290. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  40291. virtual void getTabButtonBestWidth (int, const String&, int) {}
  40292. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  40293. private:
  40294. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40295. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40296. Array <int> colourIds;
  40297. Array <Colour> colours;
  40298. // default typeface names
  40299. String defaultSans, defaultSerif, defaultFixed;
  40300. void drawShinyButtonShape (Graphics& g,
  40301. float x, float y, float w, float h, float maxCornerSize,
  40302. const Colour& baseColour,
  40303. const float strokeWidth,
  40304. const bool flatOnLeft,
  40305. const bool flatOnRight,
  40306. const bool flatOnTop,
  40307. const bool flatOnBottom) throw();
  40308. LookAndFeel (const LookAndFeel&);
  40309. const LookAndFeel& operator= (const LookAndFeel&);
  40310. };
  40311. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40312. /********* End of inlined file: juce_LookAndFeel.h *********/
  40313. #endif
  40314. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40315. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40316. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40317. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40318. /**
  40319. The original Juce look-and-feel.
  40320. */
  40321. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40322. {
  40323. public:
  40324. /** Creates the default JUCE look and feel. */
  40325. OldSchoolLookAndFeel();
  40326. /** Destructor. */
  40327. virtual ~OldSchoolLookAndFeel();
  40328. /** Draws the lozenge-shaped background for a standard button. */
  40329. virtual void drawButtonBackground (Graphics& g,
  40330. Button& button,
  40331. const Colour& backgroundColour,
  40332. bool isMouseOverButton,
  40333. bool isButtonDown);
  40334. /** Draws the contents of a standard ToggleButton. */
  40335. virtual void drawToggleButton (Graphics& g,
  40336. ToggleButton& button,
  40337. bool isMouseOverButton,
  40338. bool isButtonDown);
  40339. virtual void drawTickBox (Graphics& g,
  40340. Component& component,
  40341. int x, int y, int w, int h,
  40342. const bool ticked,
  40343. const bool isEnabled,
  40344. const bool isMouseOverButton,
  40345. const bool isButtonDown);
  40346. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40347. int width, int height,
  40348. double progress, const String& textToShow);
  40349. virtual void drawScrollbarButton (Graphics& g,
  40350. ScrollBar& scrollbar,
  40351. int width, int height,
  40352. int buttonDirection,
  40353. bool isScrollbarVertical,
  40354. bool isMouseOverButton,
  40355. bool isButtonDown);
  40356. virtual void drawScrollbar (Graphics& g,
  40357. ScrollBar& scrollbar,
  40358. int x, int y,
  40359. int width, int height,
  40360. bool isScrollbarVertical,
  40361. int thumbStartPosition,
  40362. int thumbSize,
  40363. bool isMouseOver,
  40364. bool isMouseDown);
  40365. virtual ImageEffectFilter* getScrollbarEffect();
  40366. virtual void drawTextEditorOutline (Graphics& g,
  40367. int width, int height,
  40368. TextEditor& textEditor);
  40369. /** Fills the background of a popup menu component. */
  40370. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40371. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40372. bool isMouseOverBar,
  40373. MenuBarComponent& menuBar);
  40374. virtual void drawComboBox (Graphics& g, int width, int height,
  40375. const bool isButtonDown,
  40376. int buttonX, int buttonY,
  40377. int buttonW, int buttonH,
  40378. ComboBox& box);
  40379. virtual const Font getComboBoxFont (ComboBox& box);
  40380. virtual void drawLinearSlider (Graphics& g,
  40381. int x, int y,
  40382. int width, int height,
  40383. float sliderPos,
  40384. float minSliderPos,
  40385. float maxSliderPos,
  40386. const Slider::SliderStyle style,
  40387. Slider& slider);
  40388. virtual int getSliderThumbRadius (Slider& slider);
  40389. virtual Button* createSliderButton (const bool isIncrement);
  40390. virtual ImageEffectFilter* getSliderEffect();
  40391. virtual void drawCornerResizer (Graphics& g,
  40392. int w, int h,
  40393. bool isMouseOver,
  40394. bool isMouseDragging);
  40395. virtual Button* createDocumentWindowButton (int buttonType);
  40396. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40397. int titleBarX, int titleBarY,
  40398. int titleBarW, int titleBarH,
  40399. Button* minimiseButton,
  40400. Button* maximiseButton,
  40401. Button* closeButton,
  40402. bool positionTitleBarButtonsOnLeft);
  40403. juce_UseDebuggingNewOperator
  40404. private:
  40405. DropShadowEffect scrollbarShadow;
  40406. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40407. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40408. };
  40409. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40410. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40411. #endif
  40412. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40413. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  40414. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40415. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40416. /**
  40417. A class to take care of the logic involved with the loading/saving of some kind
  40418. of document.
  40419. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  40420. functions you need for documents that get saved to a file, so this class attempts
  40421. to abstract most of the boring stuff.
  40422. Your subclass should just implement all the pure virtual methods, and you can
  40423. then use the higher-level public methods to do the load/save dialogs, to warn the user
  40424. about overwriting files, etc.
  40425. The document object keeps track of whether it has changed since it was last saved or
  40426. loaded, so when you change something, call its changed() method. This will set a
  40427. flag so it knows it needs saving, and will also broadcast a change message using the
  40428. ChangeBroadcaster base class.
  40429. @see ChangeBroadcaster
  40430. */
  40431. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  40432. {
  40433. public:
  40434. /** Creates a FileBasedDocument.
  40435. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  40436. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  40437. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  40438. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  40439. */
  40440. FileBasedDocument (const String& fileExtension,
  40441. const String& fileWildCard,
  40442. const String& openFileDialogTitle,
  40443. const String& saveFileDialogTitle);
  40444. /** Destructor. */
  40445. virtual ~FileBasedDocument();
  40446. /** Returns true if the changed() method has been called since the file was
  40447. last saved or loaded.
  40448. @see resetChangedFlag, changed
  40449. */
  40450. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  40451. /** Called to indicate that the document has changed and needs saving.
  40452. This method will also trigger a change message to be sent out using the
  40453. ChangeBroadcaster base class.
  40454. After calling the method, the hasChangedSinceSaved() method will return true, until
  40455. it is reset either by saving to a file or using the resetChangedFlag() method.
  40456. @see hasChangedSinceSaved, resetChangedFlag
  40457. */
  40458. virtual void changed();
  40459. /** Sets the state of the 'changed' flag.
  40460. The 'changed' flag is set to true when the changed() method is called - use this method
  40461. to reset it or to set it without also broadcasting a change message.
  40462. @see changed, hasChangedSinceSaved
  40463. */
  40464. void setChangedFlag (const bool hasChanged);
  40465. /** Tries to open a file.
  40466. If the file opens correctly, the document's file (see the getFile() method) is set
  40467. to this new one; if it fails, the document's file is left unchanged, and optionally
  40468. a message box is shown telling the user there was an error.
  40469. @returns true if the new file loaded successfully
  40470. @see loadDocument, loadFromUserSpecifiedFile
  40471. */
  40472. bool loadFrom (const File& fileToLoadFrom,
  40473. const bool showMessageOnFailure);
  40474. /** Asks the user for a file and tries to load it.
  40475. This will pop up a dialog box using the title, file extension and
  40476. wildcard specified in the document's constructor, and asks the user
  40477. for a file. If they pick one, the loadFrom() method is used to
  40478. try to load it, optionally showing a message if it fails.
  40479. @returns true if a file was loaded; false if the user cancelled or if they
  40480. picked a file which failed to load correctly
  40481. @see loadFrom
  40482. */
  40483. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  40484. /** A set of possible outcomes of one of the save() methods
  40485. */
  40486. enum SaveResult
  40487. {
  40488. savedOk = 0, /**< indicates that a file was saved successfully. */
  40489. userCancelledSave, /**< indicates that the user aborted the save operation. */
  40490. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  40491. };
  40492. /** Tries to save the document to the last file it was saved or loaded from.
  40493. This will always try to write to the file, even if the document isn't flagged as
  40494. having changed.
  40495. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  40496. true, it will prompt the user to pick a file, as if
  40497. saveAsInteractive() was called.
  40498. @param showMessageOnFailure if true it will show a warning message when if the
  40499. save operation fails
  40500. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  40501. */
  40502. SaveResult save (const bool askUserForFileIfNotSpecified,
  40503. const bool showMessageOnFailure);
  40504. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  40505. it if they say yes.
  40506. If you've got a document open and want to close it (e.g. to quit the app), this is the
  40507. method to call.
  40508. If the document doesn't need saving it'll return the value savedOk so
  40509. you can go ahead and delete the document.
  40510. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  40511. return savedOk, so again, you can safely delete the document.
  40512. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  40513. close-document operation.
  40514. And if they click "save changes", it'll try to save and either return savedOk, or
  40515. failedToWriteToFile if there was a problem.
  40516. @see save, saveAs, saveAsInteractive
  40517. */
  40518. SaveResult saveIfNeededAndUserAgrees();
  40519. /** Tries to save the document to a specified file.
  40520. If this succeeds, it'll also change the document's internal file (as returned by
  40521. the getFile() method). If it fails, the file will be left unchanged.
  40522. @param newFile the file to try to write to
  40523. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  40524. the user first if they want to overwrite it
  40525. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  40526. use the saveAsInteractive() method to ask the user for a
  40527. filename
  40528. @param showMessageOnFailure if true and the write operation fails, it'll show
  40529. a message box to warn the user
  40530. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  40531. */
  40532. SaveResult saveAs (const File& newFile,
  40533. const bool warnAboutOverwritingExistingFiles,
  40534. const bool askUserForFileIfNotSpecified,
  40535. const bool showMessageOnFailure);
  40536. /** Prompts the user for a filename and tries to save to it.
  40537. This will pop up a dialog box using the title, file extension and
  40538. wildcard specified in the document's constructor, and asks the user
  40539. for a file. If they pick one, the saveAs() method is used to try to save
  40540. to this file.
  40541. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  40542. the user first if they want to overwrite it
  40543. @see saveIfNeededAndUserAgrees, save, saveAs
  40544. */
  40545. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  40546. /** Returns the file that this document was last successfully saved or loaded from.
  40547. When the document object is created, this will be set to File::nonexistent.
  40548. It is changed when one of the load or save methods is used, or when setFile()
  40549. is used to explicitly set it.
  40550. */
  40551. const File getFile() const throw() { return documentFile; }
  40552. /** Sets the file that this document thinks it was loaded from.
  40553. This won't actually load anything - it just changes the file stored internally.
  40554. @see getFile
  40555. */
  40556. void setFile (const File& newFile);
  40557. protected:
  40558. /** Overload this to return the title of the document.
  40559. This is used in message boxes, filenames and file choosers, so it should be
  40560. something sensible.
  40561. */
  40562. virtual const String getDocumentTitle() = 0;
  40563. /** This method should try to load your document from the given file.
  40564. If it fails, it should return an error message. If it succeeds, it should return
  40565. an empty string.
  40566. */
  40567. virtual const String loadDocument (const File& file) = 0;
  40568. /** This method should try to write your document to the given file.
  40569. If it fails, it should return an error message. If it succeeds, it should return
  40570. an empty string.
  40571. */
  40572. virtual const String saveDocument (const File& file) = 0;
  40573. /** This is used for dialog boxes to make them open at the last folder you
  40574. were using.
  40575. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  40576. the last document that was used - you might want to store this value
  40577. in a static variable, or even in your application's properties. It should
  40578. be a global setting rather than a property of this object.
  40579. This method works very well in conjunction with a RecentlyOpenedFilesList
  40580. object to manage your recent-files list.
  40581. As a default value, it's ok to return File::nonexistent, and the document
  40582. object will use a sensible one instead.
  40583. @see RecentlyOpenedFilesList
  40584. */
  40585. virtual const File getLastDocumentOpened() = 0;
  40586. /** This is used for dialog boxes to make them open at the last folder you
  40587. were using.
  40588. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  40589. the last document that was used - you might want to store this value
  40590. in a static variable, or even in your application's properties. It should
  40591. be a global setting rather than a property of this object.
  40592. This method works very well in conjunction with a RecentlyOpenedFilesList
  40593. object to manage your recent-files list.
  40594. @see RecentlyOpenedFilesList
  40595. */
  40596. virtual void setLastDocumentOpened (const File& file) = 0;
  40597. public:
  40598. juce_UseDebuggingNewOperator
  40599. private:
  40600. File documentFile;
  40601. bool changedSinceSave;
  40602. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  40603. FileBasedDocument (const FileBasedDocument&);
  40604. const FileBasedDocument& operator= (const FileBasedDocument&);
  40605. };
  40606. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40607. /********* End of inlined file: juce_FileBasedDocument.h *********/
  40608. #endif
  40609. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40610. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40611. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40612. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40613. /**
  40614. Manages a set of files for use as a list of recently-opened documents.
  40615. This is a handy class for holding your list of recently-opened documents, with
  40616. helpful methods for things like purging any non-existent files, automatically
  40617. adding them to a menu, and making persistence easy.
  40618. @see File, FileBasedDocument
  40619. */
  40620. class JUCE_API RecentlyOpenedFilesList
  40621. {
  40622. public:
  40623. /** Creates an empty list.
  40624. */
  40625. RecentlyOpenedFilesList();
  40626. /** Destructor. */
  40627. ~RecentlyOpenedFilesList();
  40628. /** Sets a limit for the number of files that will be stored in the list.
  40629. When addFile() is called, then if there is no more space in the list, the
  40630. least-recently added file will be dropped.
  40631. @see getMaxNumberOfItems
  40632. */
  40633. void setMaxNumberOfItems (const int newMaxNumber);
  40634. /** Returns the number of items that this list will store.
  40635. @see setMaxNumberOfItems
  40636. */
  40637. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  40638. /** Returns the number of files in the list.
  40639. The most recently added file is always at index 0.
  40640. */
  40641. int getNumFiles() const;
  40642. /** Returns one of the files in the list.
  40643. The most recently added file is always at index 0.
  40644. */
  40645. const File getFile (const int index) const;
  40646. /** Returns an array of all the absolute pathnames in the list.
  40647. */
  40648. const StringArray& getAllFilenames() const throw() { return files; }
  40649. /** Clears all the files from the list. */
  40650. void clear();
  40651. /** Adds a file to the list.
  40652. The file will be added at index 0. If this file is already in the list, it will
  40653. be moved up to index 0, but a file can only appear once in the list.
  40654. If the list already contains the maximum number of items that is permitted, the
  40655. least-recently added file will be dropped from the end.
  40656. */
  40657. void addFile (const File& file);
  40658. /** Checks each of the files in the list, removing any that don't exist.
  40659. You might want to call this after reloading a list of files, or before putting them
  40660. on a menu.
  40661. */
  40662. void removeNonExistentFiles();
  40663. /** Adds entries to a menu, representing each of the files in the list.
  40664. This is handy for creating an "open recent file..." menu in your app. The
  40665. menu items are numbered consecutively starting with the baseItemId value,
  40666. and can either be added as complete pathnames, or just the last part of the
  40667. filename.
  40668. If dontAddNonExistentFiles is true, then each file will be checked and only those
  40669. that exist will be added.
  40670. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  40671. pointers to file objects. Any files that appear in this list will not be added to the
  40672. menu - the reason for this is that you might have a number of files already open, so
  40673. might not want these to be shown in the menu.
  40674. It returns the number of items that were added.
  40675. */
  40676. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  40677. const int baseItemId,
  40678. const bool showFullPaths,
  40679. const bool dontAddNonExistentFiles,
  40680. const File** filesToAvoid = 0);
  40681. /** Returns a string that encapsulates all the files in the list.
  40682. The string that is returned can later be passed into restoreFromString() in
  40683. order to recreate the list. This is handy for persisting your list, e.g. in
  40684. a PropertiesFile object.
  40685. @see restoreFromString
  40686. */
  40687. const String toString() const;
  40688. /** Restores the list from a previously stringified version of the list.
  40689. Pass in a stringified version created with toString() in order to persist/restore
  40690. your list.
  40691. @see toString
  40692. */
  40693. void restoreFromString (const String& stringifiedVersion);
  40694. juce_UseDebuggingNewOperator
  40695. private:
  40696. StringArray files;
  40697. int maxNumberOfItems;
  40698. };
  40699. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40700. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40701. #endif
  40702. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40703. #endif
  40704. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  40705. #endif
  40706. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40707. #endif
  40708. #endif
  40709. /********* End of inlined file: juce_app_includes.h *********/
  40710. #endif
  40711. #if JUCE_MSVC
  40712. #pragma warning (pop)
  40713. #pragma pack (pop)
  40714. #endif
  40715. #if JUCE_MAC
  40716. #pragma align=reset
  40717. #endif
  40718. END_JUCE_NAMESPACE
  40719. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40720. #ifdef JUCE_NAMESPACE
  40721. // this will obviously save a lot of typing, but can be disabled by
  40722. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40723. using namespace JUCE_NAMESPACE;
  40724. /* On the Mac, these symbols are defined in the Mac libraries, so
  40725. these macros make it easier to reference them without writing out
  40726. the namespace every time.
  40727. If you run into difficulties where these macros interfere with the contents
  40728. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40729. the comments in that file for more information.
  40730. */
  40731. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40732. #define Component JUCE_NAMESPACE::Component
  40733. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40734. #define Point JUCE_NAMESPACE::Point
  40735. #define Button JUCE_NAMESPACE::Button
  40736. #endif
  40737. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40738. it easier to use the juce version explicitly.
  40739. If you run into difficulties where this macro interferes with other 3rd party header
  40740. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40741. file for more information.
  40742. */
  40743. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40744. #define Rectangle JUCE_NAMESPACE::Rectangle
  40745. #endif
  40746. #endif
  40747. #endif
  40748. /* Easy autolinking to the right JUCE libraries under win32.
  40749. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40750. including this header file.
  40751. */
  40752. #if JUCE_MSVC
  40753. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40754. /** If you want your application to link to Juce as a DLL instead of
  40755. a static library (on win32), just define the JUCE_DLL macro before
  40756. including juce.h
  40757. */
  40758. #ifdef JUCE_DLL
  40759. #ifdef JUCE_DEBUG
  40760. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40761. #else
  40762. #define AUTOLINKEDLIB "JUCE.lib"
  40763. #endif
  40764. #else
  40765. #ifdef JUCE_DEBUG
  40766. #ifdef _WIN64
  40767. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40768. #else
  40769. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40770. #endif
  40771. #else
  40772. #ifdef _WIN64
  40773. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40774. #else
  40775. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40776. #endif
  40777. #endif
  40778. #endif
  40779. #pragma comment(lib, AUTOLINKEDLIB)
  40780. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40781. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40782. #endif
  40783. // Auto-link the other win32 libs that are needed by library calls..
  40784. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40785. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40786. // Auto-links to various win32 libs that are needed by library calls..
  40787. #pragma comment(lib, "kernel32.lib")
  40788. #pragma comment(lib, "user32.lib")
  40789. #pragma comment(lib, "shell32.lib")
  40790. #pragma comment(lib, "gdi32.lib")
  40791. #pragma comment(lib, "vfw32.lib")
  40792. #pragma comment(lib, "comdlg32.lib")
  40793. #pragma comment(lib, "winmm.lib")
  40794. #pragma comment(lib, "wininet.lib")
  40795. #pragma comment(lib, "ole32.lib")
  40796. #pragma comment(lib, "advapi32.lib")
  40797. #pragma comment(lib, "ws2_32.lib")
  40798. #pragma comment(lib, "comsupp.lib")
  40799. #pragma comment(lib, "version.lib")
  40800. #if JUCE_OPENGL
  40801. #pragma comment(lib, "OpenGL32.Lib")
  40802. #pragma comment(lib, "GlU32.Lib")
  40803. #endif
  40804. #if JUCE_QUICKTIME
  40805. #pragma comment (lib, "QTMLClient.lib")
  40806. #endif
  40807. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40808. #endif
  40809. #endif
  40810. #endif
  40811. /*
  40812. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40813. AppSubClass is the name of a class derived from JUCEApplication.
  40814. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40815. */
  40816. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40817. #define START_JUCE_APPLICATION(AppClass) \
  40818. int main (int argc, char* argv[]) \
  40819. { \
  40820. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40821. }
  40822. #elif JUCE_WIN32
  40823. #ifdef _CONSOLE
  40824. #define START_JUCE_APPLICATION(AppClass) \
  40825. int main (int, char* argv[]) \
  40826. { \
  40827. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40828. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40829. }
  40830. #elif ! defined (_AFXDLL)
  40831. #ifdef _WINDOWS_
  40832. #define START_JUCE_APPLICATION(AppClass) \
  40833. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40834. { \
  40835. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40836. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40837. }
  40838. #else
  40839. #define START_JUCE_APPLICATION(AppClass) \
  40840. int __stdcall WinMain (int, int, const char*, int) \
  40841. { \
  40842. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40843. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40844. }
  40845. #endif
  40846. #endif
  40847. #endif
  40848. #endif // __JUCE_JUCEHEADER__
  40849. /********* End of inlined file: juce.h *********/
  40850. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__