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.

54411 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_ATOMIC_JUCEHEADER__
  1927. /********* Start of inlined file: juce_Atomic.h *********/
  1928. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1929. #define __JUCE_ATOMIC_JUCEHEADER__
  1930. // Atomic increment/decrement operations..
  1931. #if JUCE_MAC && ! DOXYGEN
  1932. #if ! MACOS_10_3_OR_EARLIER
  1933. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1934. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1935. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1936. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1937. #else
  1938. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  1939. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  1940. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1941. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1942. #endif
  1943. #elif JUCE_GCC
  1944. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1945. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1946. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1947. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1948. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1949. #else
  1950. /** Increments an integer in a thread-safe way. */
  1951. forcedinline void atomicIncrement (int& variable) throw()
  1952. {
  1953. __asm__ __volatile__ (
  1954. #if JUCE_64BIT
  1955. "lock incl (%%rax)"
  1956. :
  1957. : "a" (&variable)
  1958. : "cc", "memory");
  1959. #else
  1960. "lock incl %0"
  1961. : "=m" (variable)
  1962. : "m" (variable));
  1963. #endif
  1964. }
  1965. /** Increments an integer in a thread-safe way and returns the incremented value. */
  1966. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  1967. {
  1968. int result;
  1969. __asm__ __volatile__ (
  1970. #if JUCE_64BIT
  1971. "lock xaddl %%ebx, (%%rax) \n\
  1972. incl %%ebx"
  1973. : "=b" (result)
  1974. : "a" (&variable), "b" (1)
  1975. : "cc", "memory");
  1976. #else
  1977. "lock xaddl %%eax, (%%ecx) \n\
  1978. incl %%eax"
  1979. : "=a" (result)
  1980. : "c" (&variable), "a" (1)
  1981. : "memory");
  1982. #endif
  1983. return result;
  1984. }
  1985. /** Decrememts an integer in a thread-safe way. */
  1986. forcedinline void atomicDecrement (int& variable) throw()
  1987. {
  1988. __asm__ __volatile__ (
  1989. #if JUCE_64BIT
  1990. "lock decl (%%rax)"
  1991. :
  1992. : "a" (&variable)
  1993. : "cc", "memory");
  1994. #else
  1995. "lock decl %0"
  1996. : "=m" (variable)
  1997. : "m" (variable));
  1998. #endif
  1999. }
  2000. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2001. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  2002. {
  2003. int result;
  2004. __asm__ __volatile__ (
  2005. #if JUCE_64BIT
  2006. "lock xaddl %%ebx, (%%rax) \n\
  2007. decl %%ebx"
  2008. : "=b" (result)
  2009. : "a" (&variable), "b" (-1)
  2010. : "cc", "memory");
  2011. #else
  2012. "lock xaddl %%eax, (%%ecx) \n\
  2013. decl %%eax"
  2014. : "=a" (result)
  2015. : "c" (&variable), "a" (-1)
  2016. : "memory");
  2017. #endif
  2018. return result;
  2019. }
  2020. #endif
  2021. #elif JUCE_USE_INTRINSICS
  2022. #pragma intrinsic (_InterlockedIncrement)
  2023. #pragma intrinsic (_InterlockedDecrement)
  2024. /** Increments an integer in a thread-safe way. */
  2025. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2026. {
  2027. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2028. }
  2029. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2030. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2031. {
  2032. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2033. }
  2034. /** Decrememts an integer in a thread-safe way. */
  2035. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2036. {
  2037. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2038. }
  2039. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2040. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2041. {
  2042. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2043. }
  2044. #else
  2045. /** Increments an integer in a thread-safe way. */
  2046. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2047. {
  2048. __asm {
  2049. mov ecx, dword ptr [variable]
  2050. lock inc dword ptr [ecx]
  2051. }
  2052. }
  2053. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2054. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2055. {
  2056. int result;
  2057. __asm {
  2058. mov ecx, dword ptr [variable]
  2059. mov eax, 1
  2060. lock xadd dword ptr [ecx], eax
  2061. inc eax
  2062. mov result, eax
  2063. }
  2064. return result;
  2065. }
  2066. /** Decrememts an integer in a thread-safe way. */
  2067. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2068. {
  2069. __asm {
  2070. mov ecx, dword ptr [variable]
  2071. lock dec dword ptr [ecx]
  2072. }
  2073. }
  2074. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2075. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2076. {
  2077. int result;
  2078. __asm {
  2079. mov ecx, dword ptr [variable]
  2080. mov eax, -1
  2081. lock xadd dword ptr [ecx], eax
  2082. dec eax
  2083. mov result, eax
  2084. }
  2085. return result;
  2086. }
  2087. #endif
  2088. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2089. /********* End of inlined file: juce_Atomic.h *********/
  2090. #endif
  2091. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2092. #endif
  2093. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2094. /********* Start of inlined file: juce_FileLogger.h *********/
  2095. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2096. #define __JUCE_FILELOGGER_JUCEHEADER__
  2097. /********* Start of inlined file: juce_File.h *********/
  2098. #ifndef __JUCE_FILE_JUCEHEADER__
  2099. #define __JUCE_FILE_JUCEHEADER__
  2100. /********* Start of inlined file: juce_OwnedArray.h *********/
  2101. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2102. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2103. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2104. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2105. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2106. /** The default size of chunk in which arrays increase their storage.
  2107. Used by ArrayAllocationBase and its subclasses.
  2108. */
  2109. const int juceDefaultArrayGranularity = 8;
  2110. /**
  2111. Implements some basic array storage allocation functions.
  2112. This class isn't really for public use - it's used by the other
  2113. array classes, but might come in handy for some purposes.
  2114. @see Array, OwnedArray, ReferenceCountedArray
  2115. */
  2116. template <class ElementType>
  2117. class ArrayAllocationBase
  2118. {
  2119. protected:
  2120. /** Creates an empty array.
  2121. @param granularity_ this is the size of increment by which the internal storage
  2122. will be increased.
  2123. */
  2124. ArrayAllocationBase (const int granularity_) throw()
  2125. : elements (0),
  2126. numAllocated (0),
  2127. granularity (granularity_)
  2128. {
  2129. jassert (granularity > 0);
  2130. }
  2131. /** Destructor. */
  2132. ~ArrayAllocationBase() throw()
  2133. {
  2134. delete[] elements;
  2135. }
  2136. /** Changes the amount of storage allocated.
  2137. This will retain any data currently held in the array, and either add or
  2138. remove extra space at the end.
  2139. @param numElements the number of elements that are needed
  2140. */
  2141. void setAllocatedSize (const int numElements) throw()
  2142. {
  2143. if (numAllocated != numElements)
  2144. {
  2145. if (numElements > 0)
  2146. {
  2147. ElementType* const newElements = new ElementType [numElements];
  2148. const int itemsToRetain = jmin (numElements, numAllocated);
  2149. for (int i = 0; i < itemsToRetain; ++i)
  2150. newElements[i] = elements[i];
  2151. delete[] elements;
  2152. elements = newElements;
  2153. }
  2154. else if (elements != 0)
  2155. {
  2156. delete[] elements;
  2157. elements = 0;
  2158. }
  2159. numAllocated = numElements;
  2160. }
  2161. }
  2162. /** Increases the amount of storage allocated if it is less than a given amount.
  2163. This will retain any data currently held in the array, but will add
  2164. extra space at the end to make sure there it's at least as big as the size
  2165. passed in. If it's already bigger, no action is taken.
  2166. @param minNumElements the minimum number of elements that are needed
  2167. */
  2168. void ensureAllocatedSize (int minNumElements) throw()
  2169. {
  2170. if (minNumElements > numAllocated)
  2171. {
  2172. // for arrays with small granularity that get big, start
  2173. // increasing the size in bigger jumps
  2174. if (minNumElements > (granularity << 6))
  2175. {
  2176. minNumElements += (minNumElements / granularity);
  2177. if (minNumElements > (granularity << 8))
  2178. minNumElements += granularity << 6;
  2179. else
  2180. minNumElements += granularity << 5;
  2181. }
  2182. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2183. }
  2184. }
  2185. ElementType* elements;
  2186. int numAllocated, granularity;
  2187. private:
  2188. ArrayAllocationBase (const ArrayAllocationBase&);
  2189. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2190. };
  2191. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2192. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2193. /********* Start of inlined file: juce_ElementComparator.h *********/
  2194. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2195. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2196. /**
  2197. Sorts a range of elements in an array.
  2198. The comparator object that is passed-in must define a public method with the following
  2199. signature:
  2200. @code
  2201. int compareElements (ElementType first, ElementType second);
  2202. @endcode
  2203. ..and this method must return:
  2204. - a value of < 0 if the first comes before the second
  2205. - a value of 0 if the two objects are equivalent
  2206. - a value of > 0 if the second comes before the first
  2207. To improve performance, the compareElements() method can be declared as static or const.
  2208. @param comparator an object which defines a compareElements() method
  2209. @param array the array to sort
  2210. @param firstElement the index of the first element of the range to be sorted
  2211. @param lastElement the index of the last element in the range that needs
  2212. sorting (this is inclusive)
  2213. @param retainOrderOfEquivalentItems if true, the order of items that the
  2214. comparator deems the same will be maintained - this will be
  2215. a slower algorithm than if they are allowed to be moved around.
  2216. @see sortArrayRetainingOrder
  2217. */
  2218. template <class ElementType, class ElementComparator>
  2219. static void sortArray (ElementComparator& comparator,
  2220. ElementType* const array,
  2221. int firstElement,
  2222. int lastElement,
  2223. const bool retainOrderOfEquivalentItems)
  2224. {
  2225. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2226. // avoids getting warning messages about the parameter being unused
  2227. if (lastElement > firstElement)
  2228. {
  2229. if (retainOrderOfEquivalentItems)
  2230. {
  2231. for (int i = firstElement; i < lastElement; ++i)
  2232. {
  2233. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2234. {
  2235. const ElementType temp = array [i];
  2236. array [i] = array[i + 1];
  2237. array [i + 1] = temp;
  2238. if (i > firstElement)
  2239. i -= 2;
  2240. }
  2241. }
  2242. }
  2243. else
  2244. {
  2245. int fromStack[30], toStack[30];
  2246. int stackIndex = 0;
  2247. for (;;)
  2248. {
  2249. const int size = (lastElement - firstElement) + 1;
  2250. if (size <= 8)
  2251. {
  2252. int j = lastElement;
  2253. int maxIndex;
  2254. while (j > firstElement)
  2255. {
  2256. maxIndex = firstElement;
  2257. for (int k = firstElement + 1; k <= j; ++k)
  2258. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2259. maxIndex = k;
  2260. const ElementType temp = array [maxIndex];
  2261. array [maxIndex] = array[j];
  2262. array [j] = temp;
  2263. --j;
  2264. }
  2265. }
  2266. else
  2267. {
  2268. const int mid = firstElement + (size >> 1);
  2269. ElementType temp = array [mid];
  2270. array [mid] = array [firstElement];
  2271. array [firstElement] = temp;
  2272. int i = firstElement;
  2273. int j = lastElement + 1;
  2274. for (;;)
  2275. {
  2276. while (++i <= lastElement
  2277. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2278. {}
  2279. while (--j > firstElement
  2280. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2281. {}
  2282. if (j < i)
  2283. break;
  2284. temp = array[i];
  2285. array[i] = array[j];
  2286. array[j] = temp;
  2287. }
  2288. temp = array [firstElement];
  2289. array [firstElement] = array[j];
  2290. array [j] = temp;
  2291. if (j - 1 - firstElement >= lastElement - i)
  2292. {
  2293. if (firstElement + 1 < j)
  2294. {
  2295. fromStack [stackIndex] = firstElement;
  2296. toStack [stackIndex] = j - 1;
  2297. ++stackIndex;
  2298. }
  2299. if (i < lastElement)
  2300. {
  2301. firstElement = i;
  2302. continue;
  2303. }
  2304. }
  2305. else
  2306. {
  2307. if (i < lastElement)
  2308. {
  2309. fromStack [stackIndex] = i;
  2310. toStack [stackIndex] = lastElement;
  2311. ++stackIndex;
  2312. }
  2313. if (firstElement + 1 < j)
  2314. {
  2315. lastElement = j - 1;
  2316. continue;
  2317. }
  2318. }
  2319. }
  2320. if (--stackIndex < 0)
  2321. break;
  2322. jassert (stackIndex < numElementsInArray (fromStack));
  2323. firstElement = fromStack [stackIndex];
  2324. lastElement = toStack [stackIndex];
  2325. }
  2326. }
  2327. }
  2328. }
  2329. /**
  2330. Searches a sorted array of elements, looking for the index at which a specified value
  2331. should be inserted for it to be in the correct order.
  2332. The comparator object that is passed-in must define a public method with the following
  2333. signature:
  2334. @code
  2335. int compareElements (ElementType first, ElementType second);
  2336. @endcode
  2337. ..and this method must return:
  2338. - a value of < 0 if the first comes before the second
  2339. - a value of 0 if the two objects are equivalent
  2340. - a value of > 0 if the second comes before the first
  2341. To improve performance, the compareElements() method can be declared as static or const.
  2342. @param comparator an object which defines a compareElements() method
  2343. @param array the array to search
  2344. @param newElement the value that is going to be inserted
  2345. @param firstElement the index of the first element to search
  2346. @param lastElement the index of the last element in the range (this is non-inclusive)
  2347. */
  2348. template <class ElementType, class ElementComparator>
  2349. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2350. ElementType* const array,
  2351. const ElementType newElement,
  2352. int firstElement,
  2353. int lastElement)
  2354. {
  2355. jassert (firstElement <= lastElement);
  2356. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2357. // avoids getting warning messages about the parameter being unused
  2358. while (firstElement < lastElement)
  2359. {
  2360. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2361. {
  2362. ++firstElement;
  2363. break;
  2364. }
  2365. else
  2366. {
  2367. const int halfway = (firstElement + lastElement) >> 1;
  2368. if (halfway == firstElement)
  2369. {
  2370. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2371. ++firstElement;
  2372. break;
  2373. }
  2374. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2375. {
  2376. firstElement = halfway;
  2377. }
  2378. else
  2379. {
  2380. lastElement = halfway;
  2381. }
  2382. }
  2383. }
  2384. return firstElement;
  2385. }
  2386. /**
  2387. A simple ElementComparator class that can be used to sort an array of
  2388. integer primitive objects.
  2389. Example: @code
  2390. Array <int> myArray;
  2391. IntegerElementComparator<int> sorter;
  2392. myArray.sort (sorter);
  2393. @endcode
  2394. For floating point values, see the FloatElementComparator class instead.
  2395. @see FloatElementComparator, ElementComparator
  2396. */
  2397. template <class ElementType>
  2398. class IntegerElementComparator
  2399. {
  2400. public:
  2401. static int compareElements (const ElementType first,
  2402. const ElementType second) throw()
  2403. {
  2404. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2405. }
  2406. };
  2407. /**
  2408. A simple ElementComparator class that can be used to sort an array of numeric
  2409. double or floating point primitive objects.
  2410. Example: @code
  2411. Array <double> myArray;
  2412. FloatElementComparator<double> sorter;
  2413. myArray.sort (sorter);
  2414. @endcode
  2415. For integer values, see the IntegerElementComparator class instead.
  2416. @see IntegerElementComparator, ElementComparator
  2417. */
  2418. template <class ElementType>
  2419. class FloatElementComparator
  2420. {
  2421. public:
  2422. static int compareElements (const ElementType first,
  2423. const ElementType second) throw()
  2424. {
  2425. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2426. }
  2427. };
  2428. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2429. /********* End of inlined file: juce_ElementComparator.h *********/
  2430. /********* Start of inlined file: juce_CriticalSection.h *********/
  2431. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2432. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2433. /**
  2434. Prevents multiple threads from accessing shared objects at the same time.
  2435. @see ScopedLock, Thread, InterProcessLock
  2436. */
  2437. class JUCE_API CriticalSection
  2438. {
  2439. public:
  2440. /**
  2441. Creates a CriticalSection object
  2442. */
  2443. CriticalSection() throw();
  2444. /** Destroys a CriticalSection object.
  2445. If the critical section is deleted whilst locked, its subsequent behaviour
  2446. is unpredictable.
  2447. */
  2448. ~CriticalSection() throw();
  2449. /** Locks this critical section.
  2450. If the lock is currently held by another thread, this will wait until it
  2451. becomes free.
  2452. If the lock is already held by the caller thread, the method returns immediately.
  2453. @see exit, ScopedLock
  2454. */
  2455. void enter() const throw();
  2456. /** Attempts to lock this critical section without blocking.
  2457. This method behaves identically to CriticalSection::enter, except that the caller thread
  2458. does not wait if the lock is currently held by another thread but returns false immediately.
  2459. @returns false if the lock is currently held by another thread, true otherwise.
  2460. @see enter
  2461. */
  2462. bool tryEnter() const throw();
  2463. /** Releases the lock.
  2464. If the caller thread hasn't got the lock, this can have unpredictable results.
  2465. If the enter() method has been called multiple times by the thread, each
  2466. call must be matched by a call to exit() before other threads will be allowed
  2467. to take over the lock.
  2468. @see enter, ScopedLock
  2469. */
  2470. void exit() const throw();
  2471. juce_UseDebuggingNewOperator
  2472. private:
  2473. #if JUCE_WIN32
  2474. #if JUCE_64BIT
  2475. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2476. // block of memory here that's big enough to be used internally as a windows critical
  2477. // section object.
  2478. uint8 internal [44];
  2479. #else
  2480. uint8 internal [24];
  2481. #endif
  2482. #else
  2483. mutable pthread_mutex_t internal;
  2484. #endif
  2485. CriticalSection (const CriticalSection&);
  2486. const CriticalSection& operator= (const CriticalSection&);
  2487. };
  2488. /**
  2489. A class that can be used in place of a real CriticalSection object.
  2490. This is currently used by some templated array classes, and should get
  2491. optimised out by the compiler.
  2492. @see Array, OwnedArray, ReferenceCountedArray
  2493. */
  2494. class JUCE_API DummyCriticalSection
  2495. {
  2496. public:
  2497. forcedinline DummyCriticalSection() throw() {}
  2498. forcedinline ~DummyCriticalSection() throw() {}
  2499. forcedinline void enter() const throw() {}
  2500. forcedinline void exit() const throw() {}
  2501. };
  2502. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2503. /********* End of inlined file: juce_CriticalSection.h *********/
  2504. /** An array designed for holding objects.
  2505. This holds a list of pointers to objects, and will automatically
  2506. delete the objects when they are removed from the array, or when the
  2507. array is itself deleted.
  2508. Declare it in the form: OwnedArray<MyObjectClass>
  2509. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2510. After adding objects, they are 'owned' by the array and will be deleted when
  2511. removed or replaced.
  2512. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2513. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2514. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2515. */
  2516. template <class ObjectClass,
  2517. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2518. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2519. {
  2520. public:
  2521. /** Creates an empty array.
  2522. @param granularity this is the size of increment by which the internal storage
  2523. used by the array will grow. Only change it from the default if you know the
  2524. array is going to be very big and needs to be able to grow efficiently.
  2525. @see ArrayAllocationBase
  2526. */
  2527. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2528. : ArrayAllocationBase <ObjectClass*> (granularity),
  2529. numUsed (0)
  2530. {
  2531. }
  2532. /** Deletes the array and also deletes any objects inside it.
  2533. To get rid of the array without deleting its objects, use its
  2534. clear (false) method before deleting it.
  2535. */
  2536. ~OwnedArray()
  2537. {
  2538. clear (true);
  2539. }
  2540. /** Clears the array, optionally deleting the objects inside it first. */
  2541. void clear (const bool deleteObjects = true)
  2542. {
  2543. lock.enter();
  2544. if (deleteObjects)
  2545. {
  2546. while (numUsed > 0)
  2547. delete this->elements [--numUsed];
  2548. }
  2549. this->setAllocatedSize (0);
  2550. numUsed = 0;
  2551. lock.exit();
  2552. }
  2553. /** Returns the number of items currently in the array.
  2554. @see operator[]
  2555. */
  2556. inline int size() const throw()
  2557. {
  2558. return numUsed;
  2559. }
  2560. /** Returns a pointer to the object at this index in the array.
  2561. If the index is out-of-range, this will return a null pointer, (and
  2562. it could be null anyway, because it's ok for the array to hold null
  2563. pointers as well as objects).
  2564. @see getUnchecked
  2565. */
  2566. inline ObjectClass* operator[] (const int index) const throw()
  2567. {
  2568. lock.enter();
  2569. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2570. ? this->elements [index]
  2571. : (ObjectClass*) 0;
  2572. lock.exit();
  2573. return result;
  2574. }
  2575. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2576. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2577. it can be used when you're sure the index if always going to be legal.
  2578. */
  2579. inline ObjectClass* getUnchecked (const int index) const throw()
  2580. {
  2581. lock.enter();
  2582. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2583. ObjectClass* const result = this->elements [index];
  2584. lock.exit();
  2585. return result;
  2586. }
  2587. /** Returns a pointer to the first object in the array.
  2588. This will return a null pointer if the array's empty.
  2589. @see getLast
  2590. */
  2591. inline ObjectClass* getFirst() const throw()
  2592. {
  2593. lock.enter();
  2594. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2595. : (ObjectClass*) 0;
  2596. lock.exit();
  2597. return result;
  2598. }
  2599. /** Returns a pointer to the last object in the array.
  2600. This will return a null pointer if the array's empty.
  2601. @see getFirst
  2602. */
  2603. inline ObjectClass* getLast() const throw()
  2604. {
  2605. lock.enter();
  2606. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2607. : (ObjectClass*) 0;
  2608. lock.exit();
  2609. return result;
  2610. }
  2611. /** Finds the index of an object which might be in the array.
  2612. @param objectToLookFor the object to look for
  2613. @returns the index at which the object was found, or -1 if it's not found
  2614. */
  2615. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2616. {
  2617. int result = -1;
  2618. lock.enter();
  2619. ObjectClass* const* e = this->elements;
  2620. for (int i = numUsed; --i >= 0;)
  2621. {
  2622. if (objectToLookFor == *e)
  2623. {
  2624. result = (int) (e - this->elements);
  2625. break;
  2626. }
  2627. ++e;
  2628. }
  2629. lock.exit();
  2630. return result;
  2631. }
  2632. /** Returns true if the array contains a specified object.
  2633. @param objectToLookFor the object to look for
  2634. @returns true if the object is in the array
  2635. */
  2636. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2637. {
  2638. lock.enter();
  2639. ObjectClass* const* e = this->elements;
  2640. int i = numUsed;
  2641. while (i >= 4)
  2642. {
  2643. if (objectToLookFor == *e
  2644. || objectToLookFor == *++e
  2645. || objectToLookFor == *++e
  2646. || objectToLookFor == *++e)
  2647. {
  2648. lock.exit();
  2649. return true;
  2650. }
  2651. i -= 4;
  2652. ++e;
  2653. }
  2654. while (i > 0)
  2655. {
  2656. if (objectToLookFor == *e)
  2657. {
  2658. lock.exit();
  2659. return true;
  2660. }
  2661. --i;
  2662. ++e;
  2663. }
  2664. lock.exit();
  2665. return false;
  2666. }
  2667. /** Appends a new object to the end of the array.
  2668. Note that the this object will be deleted by the OwnedArray when it
  2669. is removed, so be careful not to delete it somewhere else.
  2670. Also be careful not to add the same object to the array more than once,
  2671. as this will obviously cause deletion of dangling pointers.
  2672. @param newObject the new object to add to the array
  2673. @see set, insert, addIfNotAlreadyThere, addSorted
  2674. */
  2675. void add (const ObjectClass* const newObject) throw()
  2676. {
  2677. lock.enter();
  2678. this->ensureAllocatedSize (numUsed + 1);
  2679. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2680. lock.exit();
  2681. }
  2682. /** Inserts a new object into the array at the given index.
  2683. Note that the this object will be deleted by the OwnedArray when it
  2684. is removed, so be careful not to delete it somewhere else.
  2685. If the index is less than 0 or greater than the size of the array, the
  2686. element will be added to the end of the array.
  2687. Otherwise, it will be inserted into the array, moving all the later elements
  2688. along to make room.
  2689. Be careful not to add the same object to the array more than once,
  2690. as this will obviously cause deletion of dangling pointers.
  2691. @param indexToInsertAt the index at which the new element should be inserted
  2692. @param newObject the new object to add to the array
  2693. @see add, addSorted, addIfNotAlreadyThere, set
  2694. */
  2695. void insert (int indexToInsertAt,
  2696. const ObjectClass* const newObject) throw()
  2697. {
  2698. if (indexToInsertAt >= 0)
  2699. {
  2700. lock.enter();
  2701. if (indexToInsertAt > numUsed)
  2702. indexToInsertAt = numUsed;
  2703. this->ensureAllocatedSize (numUsed + 1);
  2704. ObjectClass** const e = this->elements + indexToInsertAt;
  2705. const int numToMove = numUsed - indexToInsertAt;
  2706. if (numToMove > 0)
  2707. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2708. *e = const_cast <ObjectClass*> (newObject);
  2709. ++numUsed;
  2710. lock.exit();
  2711. }
  2712. else
  2713. {
  2714. add (newObject);
  2715. }
  2716. }
  2717. /** Appends a new object at the end of the array as long as the array doesn't
  2718. already contain it.
  2719. If the array already contains a matching object, nothing will be done.
  2720. @param newObject the new object to add to the array
  2721. */
  2722. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2723. {
  2724. lock.enter();
  2725. if (! contains (newObject))
  2726. add (newObject);
  2727. lock.exit();
  2728. }
  2729. /** Replaces an object in the array with a different one.
  2730. If the index is less than zero, this method does nothing.
  2731. If the index is beyond the end of the array, the new object is added to the end of the array.
  2732. Be careful not to add the same object to the array more than once,
  2733. as this will obviously cause deletion of dangling pointers.
  2734. @param indexToChange the index whose value you want to change
  2735. @param newObject the new value to set for this index.
  2736. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2737. @see add, insert, remove
  2738. */
  2739. void set (const int indexToChange,
  2740. const ObjectClass* const newObject,
  2741. const bool deleteOldElement = true)
  2742. {
  2743. if (indexToChange >= 0)
  2744. {
  2745. ObjectClass* toDelete = 0;
  2746. lock.enter();
  2747. if (indexToChange < numUsed)
  2748. {
  2749. if (deleteOldElement)
  2750. toDelete = this->elements [indexToChange];
  2751. if (toDelete == newObject)
  2752. toDelete = 0;
  2753. else
  2754. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2755. }
  2756. else
  2757. {
  2758. this->ensureAllocatedSize (numUsed + 1);
  2759. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2760. }
  2761. lock.exit();
  2762. delete toDelete;
  2763. }
  2764. }
  2765. /** Inserts a new object into the array assuming that the array is sorted.
  2766. This will use a comparator to find the position at which the new object
  2767. should go. If the array isn't sorted, the behaviour of this
  2768. method will be unpredictable.
  2769. @param comparator the comparator to use to compare the elements - see the sort method
  2770. for details about this object's structure
  2771. @param newObject the new object to insert to the array
  2772. @see add, sort, indexOfSorted
  2773. */
  2774. template <class ElementComparator>
  2775. void addSorted (ElementComparator& comparator,
  2776. ObjectClass* const newObject) throw()
  2777. {
  2778. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2779. // avoids getting warning messages about the parameter being unused
  2780. lock.enter();
  2781. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2782. lock.exit();
  2783. }
  2784. /** Finds the index of an object in the array, assuming that the array is sorted.
  2785. This will use a comparator to do a binary-chop to find the index of the given
  2786. element, if it exists. If the array isn't sorted, the behaviour of this
  2787. method will be unpredictable.
  2788. @param comparator the comparator to use to compare the elements - see the sort()
  2789. method for details about the form this object should take
  2790. @param objectToLookFor the object to search for
  2791. @returns the index of the element, or -1 if it's not found
  2792. @see addSorted, sort
  2793. */
  2794. template <class ElementComparator>
  2795. int indexOfSorted (ElementComparator& comparator,
  2796. const ObjectClass* const objectToLookFor) const throw()
  2797. {
  2798. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2799. // avoids getting warning messages about the parameter being unused
  2800. lock.enter();
  2801. int start = 0;
  2802. int end = numUsed;
  2803. for (;;)
  2804. {
  2805. if (start >= end)
  2806. {
  2807. lock.exit();
  2808. return -1;
  2809. }
  2810. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2811. {
  2812. lock.exit();
  2813. return start;
  2814. }
  2815. else
  2816. {
  2817. const int halfway = (start + end) >> 1;
  2818. if (halfway == start)
  2819. {
  2820. lock.exit();
  2821. return -1;
  2822. }
  2823. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2824. start = halfway;
  2825. else
  2826. end = halfway;
  2827. }
  2828. }
  2829. }
  2830. /** Removes an object from the array.
  2831. This will remove the object at a given index (optionally also
  2832. deleting it) and move back all the subsequent objects to close the gap.
  2833. If the index passed in is out-of-range, nothing will happen.
  2834. @param indexToRemove the index of the element to remove
  2835. @param deleteObject whether to delete the object that is removed
  2836. @see removeObject, removeRange
  2837. */
  2838. void remove (const int indexToRemove,
  2839. const bool deleteObject = true)
  2840. {
  2841. lock.enter();
  2842. ObjectClass* toDelete = 0;
  2843. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2844. {
  2845. ObjectClass** const e = this->elements + indexToRemove;
  2846. if (deleteObject)
  2847. toDelete = *e;
  2848. --numUsed;
  2849. const int numToShift = numUsed - indexToRemove;
  2850. if (numToShift > 0)
  2851. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2852. if ((numUsed << 1) < this->numAllocated)
  2853. minimiseStorageOverheads();
  2854. }
  2855. lock.exit();
  2856. delete toDelete;
  2857. }
  2858. /** Removes a specified object from the array.
  2859. If the item isn't found, no action is taken.
  2860. @param objectToRemove the object to try to remove
  2861. @param deleteObject whether to delete the object (if it's found)
  2862. @see remove, removeRange
  2863. */
  2864. void removeObject (const ObjectClass* const objectToRemove,
  2865. const bool deleteObject = true)
  2866. {
  2867. lock.enter();
  2868. ObjectClass** e = this->elements;
  2869. for (int i = numUsed; --i >= 0;)
  2870. {
  2871. if (objectToRemove == *e)
  2872. {
  2873. remove ((int) (e - this->elements), deleteObject);
  2874. break;
  2875. }
  2876. ++e;
  2877. }
  2878. lock.exit();
  2879. }
  2880. /** Removes a range of objects from the array.
  2881. This will remove a set of objects, starting from the given index,
  2882. and move any subsequent elements down to close the gap.
  2883. If the range extends beyond the bounds of the array, it will
  2884. be safely clipped to the size of the array.
  2885. @param startIndex the index of the first object to remove
  2886. @param numberToRemove how many objects should be removed
  2887. @param deleteObjects whether to delete the objects that get removed
  2888. @see remove, removeObject
  2889. */
  2890. void removeRange (int startIndex,
  2891. const int numberToRemove,
  2892. const bool deleteObjects = true)
  2893. {
  2894. lock.enter();
  2895. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2896. startIndex = jlimit (0, numUsed, startIndex);
  2897. if (endIndex > startIndex)
  2898. {
  2899. if (deleteObjects)
  2900. {
  2901. for (int i = startIndex; i < endIndex; ++i)
  2902. {
  2903. delete this->elements [i];
  2904. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2905. }
  2906. }
  2907. const int rangeSize = endIndex - startIndex;
  2908. ObjectClass** e = this->elements + startIndex;
  2909. int numToShift = numUsed - endIndex;
  2910. numUsed -= rangeSize;
  2911. while (--numToShift >= 0)
  2912. {
  2913. *e = e [rangeSize];
  2914. ++e;
  2915. }
  2916. if ((numUsed << 1) < this->numAllocated)
  2917. minimiseStorageOverheads();
  2918. }
  2919. lock.exit();
  2920. }
  2921. /** Removes the last n objects from the array.
  2922. @param howManyToRemove how many objects to remove from the end of the array
  2923. @param deleteObjects whether to also delete the objects that are removed
  2924. @see remove, removeObject, removeRange
  2925. */
  2926. void removeLast (int howManyToRemove = 1,
  2927. const bool deleteObjects = true)
  2928. {
  2929. lock.enter();
  2930. if (howManyToRemove >= numUsed)
  2931. {
  2932. clear (deleteObjects);
  2933. }
  2934. else
  2935. {
  2936. while (--howManyToRemove >= 0)
  2937. remove (numUsed - 1, deleteObjects);
  2938. }
  2939. lock.exit();
  2940. }
  2941. /** Swaps a pair of objects in the array.
  2942. If either of the indexes passed in is out-of-range, nothing will happen,
  2943. otherwise the two objects at these positions will be exchanged.
  2944. */
  2945. void swap (const int index1,
  2946. const int index2) throw()
  2947. {
  2948. lock.enter();
  2949. if (((unsigned int) index1) < (unsigned int) numUsed
  2950. && ((unsigned int) index2) < (unsigned int) numUsed)
  2951. {
  2952. swapVariables (this->elements [index1],
  2953. this->elements [index2]);
  2954. }
  2955. lock.exit();
  2956. }
  2957. /** Moves one of the objects to a different position.
  2958. This will move the object to a specified index, shuffling along
  2959. any intervening elements as required.
  2960. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  2961. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  2962. @param currentIndex the index of the object to be moved. If this isn't a
  2963. valid index, then nothing will be done
  2964. @param newIndex the index at which you'd like this object to end up. If this
  2965. is less than zero, it will be moved to the end of the array
  2966. */
  2967. void move (const int currentIndex,
  2968. int newIndex) throw()
  2969. {
  2970. if (currentIndex != newIndex)
  2971. {
  2972. lock.enter();
  2973. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  2974. {
  2975. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  2976. newIndex = numUsed - 1;
  2977. ObjectClass* const value = this->elements [currentIndex];
  2978. if (newIndex > currentIndex)
  2979. {
  2980. memmove (this->elements + currentIndex,
  2981. this->elements + currentIndex + 1,
  2982. (newIndex - currentIndex) * sizeof (ObjectClass*));
  2983. }
  2984. else
  2985. {
  2986. memmove (this->elements + newIndex + 1,
  2987. this->elements + newIndex,
  2988. (currentIndex - newIndex) * sizeof (ObjectClass*));
  2989. }
  2990. this->elements [newIndex] = value;
  2991. }
  2992. lock.exit();
  2993. }
  2994. }
  2995. /** This swaps the contents of this array with those of another array.
  2996. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2997. because it just swaps their internal pointers.
  2998. */
  2999. template <class OtherArrayType>
  3000. void swapWithArray (OtherArrayType& otherArray) throw()
  3001. {
  3002. lock.enter();
  3003. otherArray.lock.enter();
  3004. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3005. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  3006. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3007. otherArray.lock.exit();
  3008. lock.exit();
  3009. }
  3010. /** Reduces the amount of storage being used by the array.
  3011. Arrays typically allocate slightly more storage than they need, and after
  3012. removing elements, they may have quite a lot of unused space allocated.
  3013. This method will reduce the amount of allocated storage to a minimum.
  3014. */
  3015. void minimiseStorageOverheads() throw()
  3016. {
  3017. lock.enter();
  3018. if (numUsed == 0)
  3019. {
  3020. this->setAllocatedSize (0);
  3021. }
  3022. else
  3023. {
  3024. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3025. if (newAllocation < this->numAllocated)
  3026. this->setAllocatedSize (newAllocation);
  3027. }
  3028. lock.exit();
  3029. }
  3030. /** Increases the array's internal storage to hold a minimum number of elements.
  3031. Calling this before adding a large known number of elements means that
  3032. the array won't have to keep dynamically resizing itself as the elements
  3033. are added, and it'll therefore be more efficient.
  3034. */
  3035. void ensureStorageAllocated (const int minNumElements) throw()
  3036. {
  3037. this->ensureAllocatedSize (minNumElements);
  3038. }
  3039. /** Sorts the elements in the array.
  3040. This will use a comparator object to sort the elements into order. The object
  3041. passed must have a method of the form:
  3042. @code
  3043. int compareElements (ElementType first, ElementType second);
  3044. @endcode
  3045. ..and this method must return:
  3046. - a value of < 0 if the first comes before the second
  3047. - a value of 0 if the two objects are equivalent
  3048. - a value of > 0 if the second comes before the first
  3049. To improve performance, the compareElements() method can be declared as static or const.
  3050. @param comparator the comparator to use for comparing elements.
  3051. @param retainOrderOfEquivalentItems if this is true, then items
  3052. which the comparator says are equivalent will be
  3053. kept in the order in which they currently appear
  3054. in the array. This is slower to perform, but may
  3055. be important in some cases. If it's false, a faster
  3056. algorithm is used, but equivalent elements may be
  3057. rearranged.
  3058. @see sortArray, indexOfSorted
  3059. */
  3060. template <class ElementComparator>
  3061. void sort (ElementComparator& comparator,
  3062. const bool retainOrderOfEquivalentItems = false) const throw()
  3063. {
  3064. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3065. // avoids getting warning messages about the parameter being unused
  3066. lock.enter();
  3067. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3068. lock.exit();
  3069. }
  3070. /** Locks the array's CriticalSection.
  3071. Of course if the type of section used is a DummyCriticalSection, this won't
  3072. have any effect.
  3073. @see unlockArray
  3074. */
  3075. void lockArray() const throw()
  3076. {
  3077. lock.enter();
  3078. }
  3079. /** Unlocks the array's CriticalSection.
  3080. Of course if the type of section used is a DummyCriticalSection, this won't
  3081. have any effect.
  3082. @see lockArray
  3083. */
  3084. void unlockArray() const throw()
  3085. {
  3086. lock.exit();
  3087. }
  3088. juce_UseDebuggingNewOperator
  3089. private:
  3090. int numUsed;
  3091. TypeOfCriticalSectionToUse lock;
  3092. // disallow copy constructor and assignment
  3093. OwnedArray (const OwnedArray&);
  3094. const OwnedArray& operator= (const OwnedArray&);
  3095. };
  3096. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3097. /********* End of inlined file: juce_OwnedArray.h *********/
  3098. /********* Start of inlined file: juce_Time.h *********/
  3099. #ifndef __JUCE_TIME_JUCEHEADER__
  3100. #define __JUCE_TIME_JUCEHEADER__
  3101. /********* Start of inlined file: juce_RelativeTime.h *********/
  3102. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3103. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3104. /** A relative measure of time.
  3105. The time is stored as a number of seconds, at double-precision floating
  3106. point accuracy, and may be positive or negative.
  3107. If you need an absolute time, (i.e. a date + time), see the Time class.
  3108. */
  3109. class JUCE_API RelativeTime
  3110. {
  3111. public:
  3112. /** Creates a RelativeTime.
  3113. @param seconds the number of seconds, which may be +ve or -ve.
  3114. @see milliseconds, minutes, hours, days, weeks
  3115. */
  3116. explicit RelativeTime (const double seconds = 0.0) throw();
  3117. /** Copies another relative time. */
  3118. RelativeTime (const RelativeTime& other) throw();
  3119. /** Copies another relative time. */
  3120. const RelativeTime& operator= (const RelativeTime& other) throw();
  3121. /** Destructor. */
  3122. ~RelativeTime() throw();
  3123. /** Creates a new RelativeTime object representing a number of milliseconds.
  3124. @see minutes, hours, days, weeks
  3125. */
  3126. static const RelativeTime milliseconds (const int milliseconds) throw();
  3127. /** Creates a new RelativeTime object representing a number of milliseconds.
  3128. @see minutes, hours, days, weeks
  3129. */
  3130. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3131. /** Creates a new RelativeTime object representing a number of minutes.
  3132. @see milliseconds, hours, days, weeks
  3133. */
  3134. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3135. /** Creates a new RelativeTime object representing a number of hours.
  3136. @see milliseconds, minutes, days, weeks
  3137. */
  3138. static const RelativeTime hours (const double numberOfHours) throw();
  3139. /** Creates a new RelativeTime object representing a number of days.
  3140. @see milliseconds, minutes, hours, weeks
  3141. */
  3142. static const RelativeTime days (const double numberOfDays) throw();
  3143. /** Creates a new RelativeTime object representing a number of weeks.
  3144. @see milliseconds, minutes, hours, days
  3145. */
  3146. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3147. /** Returns the number of milliseconds this time represents.
  3148. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3149. */
  3150. int64 inMilliseconds() const throw();
  3151. /** Returns the number of seconds this time represents.
  3152. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3153. */
  3154. double inSeconds() const throw() { return seconds; }
  3155. /** Returns the number of minutes this time represents.
  3156. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3157. */
  3158. double inMinutes() const throw();
  3159. /** Returns the number of hours this time represents.
  3160. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3161. */
  3162. double inHours() const throw();
  3163. /** Returns the number of days this time represents.
  3164. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3165. */
  3166. double inDays() const throw();
  3167. /** Returns the number of weeks this time represents.
  3168. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3169. */
  3170. double inWeeks() const throw();
  3171. /** Returns a readable textual description of the time.
  3172. The exact format of the string returned will depend on
  3173. the magnitude of the time - e.g.
  3174. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3175. so that only the two most significant units are printed.
  3176. The returnValueForZeroTime value is the result that is returned if the
  3177. length is zero. Depending on your application you might want to use this
  3178. to return something more relevant like "empty" or "0 secs", etc.
  3179. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3180. */
  3181. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3182. /** Compares two RelativeTimes. */
  3183. bool operator== (const RelativeTime& other) const throw();
  3184. /** Compares two RelativeTimes. */
  3185. bool operator!= (const RelativeTime& other) const throw();
  3186. /** Compares two RelativeTimes. */
  3187. bool operator> (const RelativeTime& other) const throw();
  3188. /** Compares two RelativeTimes. */
  3189. bool operator< (const RelativeTime& other) const throw();
  3190. /** Compares two RelativeTimes. */
  3191. bool operator>= (const RelativeTime& other) const throw();
  3192. /** Compares two RelativeTimes. */
  3193. bool operator<= (const RelativeTime& other) const throw();
  3194. /** Adds another RelativeTime to this one and returns the result. */
  3195. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3196. /** Subtracts another RelativeTime from this one and returns the result. */
  3197. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3198. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3199. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3200. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3201. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3202. /** Adds another RelativeTime to this one. */
  3203. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3204. /** Subtracts another RelativeTime from this one. */
  3205. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3206. /** Adds a number of seconds to this time. */
  3207. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3208. /** Subtracts a number of seconds from this time. */
  3209. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3210. juce_UseDebuggingNewOperator
  3211. private:
  3212. double seconds;
  3213. };
  3214. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3215. /********* End of inlined file: juce_RelativeTime.h *********/
  3216. /**
  3217. Holds an absolute date and time.
  3218. Internally, the time is stored at millisecond precision.
  3219. @see RelativeTime
  3220. */
  3221. class JUCE_API Time
  3222. {
  3223. public:
  3224. /** Creates a Time object.
  3225. This default constructor creates a time of 1st January 1970, (which is
  3226. represented internally as 0ms).
  3227. To create a time object representing the current time, use getCurrentTime().
  3228. @see getCurrentTime
  3229. */
  3230. Time() throw();
  3231. /** Creates a copy of another Time object. */
  3232. Time (const Time& other) throw();
  3233. /** Creates a time based on a number of milliseconds.
  3234. The internal millisecond count is set to 0 (1st January 1970). To create a
  3235. time object set to the current time, use getCurrentTime().
  3236. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3237. 'epoch' (midnight Jan 1st 1970).
  3238. @see getCurrentTime, currentTimeMillis
  3239. */
  3240. Time (const int64 millisecondsSinceEpoch) throw();
  3241. /** Creates a time from a set of date components.
  3242. The timezone is assumed to be whatever the system is using as its locale.
  3243. @param year the year, in 4-digit format, e.g. 2004
  3244. @param month the month, in the range 0 to 11
  3245. @param day the day of the month, in the range 1 to 31
  3246. @param hours hours in 24-hour clock format, 0 to 23
  3247. @param minutes minutes 0 to 59
  3248. @param seconds seconds 0 to 59
  3249. @param milliseconds milliseconds 0 to 999
  3250. @param useLocalTime if true, encode using the current machine's local time; if
  3251. false, it will always work in GMT.
  3252. */
  3253. Time (const int year,
  3254. const int month,
  3255. const int day,
  3256. const int hours,
  3257. const int minutes,
  3258. const int seconds = 0,
  3259. const int milliseconds = 0,
  3260. const bool useLocalTime = true) throw();
  3261. /** Destructor. */
  3262. ~Time() throw();
  3263. /** Copies this time from another one. */
  3264. const Time& operator= (const Time& other) throw();
  3265. /** Returns a Time object that is set to the current system time.
  3266. @see currentTimeMillis
  3267. */
  3268. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3269. /** Returns the time as a number of milliseconds.
  3270. @returns the number of milliseconds this Time object represents, since
  3271. midnight jan 1st 1970.
  3272. @see getMilliseconds
  3273. */
  3274. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3275. /** Returns the year.
  3276. A 4-digit format is used, e.g. 2004.
  3277. */
  3278. int getYear() const throw();
  3279. /** Returns the number of the month.
  3280. The value returned is in the range 0 to 11.
  3281. @see getMonthName
  3282. */
  3283. int getMonth() const throw();
  3284. /** Returns the name of the month.
  3285. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3286. it'll return the long form, e.g. "January"
  3287. @see getMonth
  3288. */
  3289. const String getMonthName (const bool threeLetterVersion) const throw();
  3290. /** Returns the day of the month.
  3291. The value returned is in the range 1 to 31.
  3292. */
  3293. int getDayOfMonth() const throw();
  3294. /** Returns the number of the day of the week.
  3295. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3296. */
  3297. int getDayOfWeek() const throw();
  3298. /** Returns the name of the weekday.
  3299. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3300. false, it'll return the full version, e.g. "Tuesday".
  3301. */
  3302. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3303. /** Returns the number of hours since midnight.
  3304. This is in 24-hour clock format, in the range 0 to 23.
  3305. @see getHoursInAmPmFormat, isAfternoon
  3306. */
  3307. int getHours() const throw();
  3308. /** Returns true if the time is in the afternoon.
  3309. So it returns true for "PM", false for "AM".
  3310. @see getHoursInAmPmFormat, getHours
  3311. */
  3312. bool isAfternoon() const throw();
  3313. /** Returns the hours in 12-hour clock format.
  3314. This will return a value 1 to 12 - use isAfternoon() to find out
  3315. whether this is in the afternoon or morning.
  3316. @see getHours, isAfternoon
  3317. */
  3318. int getHoursInAmPmFormat() const throw();
  3319. /** Returns the number of minutes, 0 to 59. */
  3320. int getMinutes() const throw();
  3321. /** Returns the number of seconds, 0 to 59. */
  3322. int getSeconds() const throw();
  3323. /** Returns the number of milliseconds, 0 to 999.
  3324. Unlike toMilliseconds(), this just returns the position within the
  3325. current second rather than the total number since the epoch.
  3326. @see toMilliseconds
  3327. */
  3328. int getMilliseconds() const throw();
  3329. /** Returns true if the local timezone uses a daylight saving correction. */
  3330. bool isDaylightSavingTime() const throw();
  3331. /** Returns a 3-character string to indicate the local timezone. */
  3332. const String getTimeZone() const throw();
  3333. /** Quick way of getting a string version of a date and time.
  3334. For a more powerful way of formatting the date and time, see the formatted() method.
  3335. @param includeDate whether to include the date in the string
  3336. @param includeTime whether to include the time in the string
  3337. @param includeSeconds if the time is being included, this provides an option not to include
  3338. the seconds in it
  3339. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3340. hour notation.
  3341. @see formatted
  3342. */
  3343. const String toString (const bool includeDate,
  3344. const bool includeTime,
  3345. const bool includeSeconds = true,
  3346. const bool use24HourClock = false) const throw();
  3347. /** Converts this date/time to a string with a user-defined format.
  3348. This uses the C strftime() function to format this time as a string. To save you
  3349. looking it up, these are the escape codes that strftime uses (other codes might
  3350. work on some platforms and not others, but these are the common ones):
  3351. %a is replaced by the locale's abbreviated weekday name.
  3352. %A is replaced by the locale's full weekday name.
  3353. %b is replaced by the locale's abbreviated month name.
  3354. %B is replaced by the locale's full month name.
  3355. %c is replaced by the locale's appropriate date and time representation.
  3356. %d is replaced by the day of the month as a decimal number [01,31].
  3357. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3358. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3359. %j is replaced by the day of the year as a decimal number [001,366].
  3360. %m is replaced by the month as a decimal number [01,12].
  3361. %M is replaced by the minute as a decimal number [00,59].
  3362. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3363. %S is replaced by the second as a decimal number [00,61].
  3364. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3365. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3366. %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.
  3367. %x is replaced by the locale's appropriate date representation.
  3368. %X is replaced by the locale's appropriate time representation.
  3369. %y is replaced by the year without century as a decimal number [00,99].
  3370. %Y is replaced by the year with century as a decimal number.
  3371. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3372. %% is replaced by %.
  3373. @see toString
  3374. */
  3375. const String formatted (const tchar* const format) const throw();
  3376. /** Adds a RelativeTime to this time and returns the result. */
  3377. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3378. /** Subtracts a RelativeTime from this time and returns the result. */
  3379. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3380. /** Returns the relative time difference between this time and another one. */
  3381. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3382. /** Compares two Time objects. */
  3383. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3384. /** Compares two Time objects. */
  3385. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3386. /** Compares two Time objects. */
  3387. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3388. /** Compares two Time objects. */
  3389. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3390. /** Compares two Time objects. */
  3391. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3392. /** Compares two Time objects. */
  3393. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3394. /** Tries to set the computer's clock.
  3395. @returns true if this succeeds, although depending on the system, the
  3396. application might not have sufficient privileges to do this.
  3397. */
  3398. bool setSystemTimeToThisTime() const throw();
  3399. /** Returns the name of a day of the week.
  3400. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3401. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3402. false, it'll return the full version, e.g. "Tuesday".
  3403. */
  3404. static const String getWeekdayName (int dayNumber,
  3405. const bool threeLetterVersion) throw();
  3406. /** Returns the name of one of the months.
  3407. @param monthNumber the month, 0 to 11
  3408. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3409. it'll return the long form, e.g. "January"
  3410. */
  3411. static const String getMonthName (int monthNumber,
  3412. const bool threeLetterVersion) throw();
  3413. // Static methods for getting system timers directly..
  3414. /** Returns the current system time.
  3415. Returns the number of milliseconds since midnight jan 1st 1970.
  3416. Should be accurate to within a few millisecs, depending on platform,
  3417. hardware, etc.
  3418. */
  3419. static int64 currentTimeMillis() throw();
  3420. /** Returns the number of millisecs since system startup.
  3421. Should be accurate to within a few millisecs, depending on platform,
  3422. hardware, etc.
  3423. @see getApproximateMillisecondCounter
  3424. */
  3425. static uint32 getMillisecondCounter() throw();
  3426. /** Returns the number of millisecs since system startup.
  3427. Same as getMillisecondCounter(), but returns a more accurate value, using
  3428. the high-res timer.
  3429. @see getMillisecondCounter
  3430. */
  3431. static double getMillisecondCounterHiRes() throw();
  3432. /** Waits until the getMillisecondCounter() reaches a given value.
  3433. This will make the thread sleep as efficiently as it can while it's waiting.
  3434. */
  3435. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3436. /** Less-accurate but faster version of getMillisecondCounter().
  3437. This will return the last value that getMillisecondCounter() returned, so doesn't
  3438. need to make a system call, but is less accurate - it shouldn't be more than
  3439. 100ms away from the correct time, though, so is still accurate enough for a
  3440. lot of purposes.
  3441. @see getMillisecondCounter
  3442. */
  3443. static uint32 getApproximateMillisecondCounter() throw();
  3444. // High-resolution timers..
  3445. /** Returns the current high-resolution counter's tick-count.
  3446. This is a similar idea to getMillisecondCounter(), but with a higher
  3447. resolution.
  3448. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3449. secondsToHighResolutionTicks
  3450. */
  3451. static int64 getHighResolutionTicks() throw();
  3452. /** Returns the resolution of the high-resolution counter in ticks per second.
  3453. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3454. secondsToHighResolutionTicks
  3455. */
  3456. static int64 getHighResolutionTicksPerSecond() throw();
  3457. /** Converts a number of high-resolution ticks into seconds.
  3458. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3459. secondsToHighResolutionTicks
  3460. */
  3461. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3462. /** Converts a number seconds into high-resolution ticks.
  3463. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3464. highResolutionTicksToSeconds
  3465. */
  3466. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3467. private:
  3468. int64 millisSinceEpoch;
  3469. };
  3470. #endif // __JUCE_TIME_JUCEHEADER__
  3471. /********* End of inlined file: juce_Time.h *********/
  3472. /********* Start of inlined file: juce_StringArray.h *********/
  3473. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3474. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3475. /********* Start of inlined file: juce_VoidArray.h *********/
  3476. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3477. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3478. /********* Start of inlined file: juce_Array.h *********/
  3479. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3480. #define __JUCE_ARRAY_JUCEHEADER__
  3481. /**
  3482. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3483. Examples of arrays are: Array<int> or Array<MyClass*>
  3484. Note that when holding pointers to objects, the array doesn't take any ownership
  3485. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3486. If you're using a class or struct as the element type, it must be
  3487. capable of being copied or moved with a straightforward memcpy, rather than
  3488. needing construction and destruction code.
  3489. For holding lists of strings, use the specialised class StringArray.
  3490. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3491. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3492. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3493. */
  3494. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3495. class Array : private ArrayAllocationBase <ElementType>
  3496. {
  3497. public:
  3498. /** Creates an empty array.
  3499. @param granularity this is the size of increment by which the internal storage
  3500. used by the array will grow. Only change it from the default if you know the
  3501. array is going to be very big and needs to be able to grow efficiently.
  3502. @see ArrayAllocationBase
  3503. */
  3504. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3505. : ArrayAllocationBase <ElementType> (granularity),
  3506. numUsed (0)
  3507. {
  3508. }
  3509. /** Creates a copy of another array.
  3510. @param other the array to copy
  3511. */
  3512. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3513. : ArrayAllocationBase <ElementType> (other.granularity)
  3514. {
  3515. other.lockArray();
  3516. numUsed = other.numUsed;
  3517. this->setAllocatedSize (other.numUsed);
  3518. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3519. other.unlockArray();
  3520. }
  3521. /** Initalises from a null-terminated C array of values.
  3522. @param values the array to copy from
  3523. */
  3524. Array (const ElementType* values) throw()
  3525. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3526. numUsed (0)
  3527. {
  3528. while (*values != 0)
  3529. add (*values++);
  3530. }
  3531. /** Initalises from a C array of values.
  3532. @param values the array to copy from
  3533. @param numValues the number of values in the array
  3534. */
  3535. Array (const ElementType* values, int numValues) throw()
  3536. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3537. numUsed (numValues)
  3538. {
  3539. this->setAllocatedSize (numValues);
  3540. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3541. }
  3542. /** Destructor. */
  3543. ~Array() throw()
  3544. {
  3545. }
  3546. /** Copies another array.
  3547. @param other the array to copy
  3548. */
  3549. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3550. {
  3551. if (this != &other)
  3552. {
  3553. other.lockArray();
  3554. lock.enter();
  3555. this->granularity = other.granularity;
  3556. this->ensureAllocatedSize (other.size());
  3557. numUsed = other.numUsed;
  3558. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3559. minimiseStorageOverheads();
  3560. lock.exit();
  3561. other.unlockArray();
  3562. }
  3563. return *this;
  3564. }
  3565. /** Compares this array to another one.
  3566. Two arrays are considered equal if they both contain the same set of
  3567. elements, in the same order.
  3568. @param other the other array to compare with
  3569. */
  3570. template <class OtherArrayType>
  3571. bool operator== (const OtherArrayType& other) const throw()
  3572. {
  3573. lock.enter();
  3574. if (this->numUsed != other.numUsed)
  3575. {
  3576. lock.exit();
  3577. return false;
  3578. }
  3579. for (int i = numUsed; --i >= 0;)
  3580. {
  3581. if (this->elements [i] != other.elements [i])
  3582. {
  3583. lock.exit();
  3584. return false;
  3585. }
  3586. }
  3587. lock.exit();
  3588. return true;
  3589. }
  3590. /** Compares this array to another one.
  3591. Two arrays are considered equal if they both contain the same set of
  3592. elements, in the same order.
  3593. @param other the other array to compare with
  3594. */
  3595. template <class OtherArrayType>
  3596. bool operator!= (const OtherArrayType& other) const throw()
  3597. {
  3598. return ! operator== (other);
  3599. }
  3600. /** Removes all elements from the array.
  3601. This will remove all the elements, and free any storage that the array is
  3602. using. To clear the array without freeing the storage, use the clearQuick()
  3603. method instead.
  3604. @see clearQuick
  3605. */
  3606. void clear() throw()
  3607. {
  3608. lock.enter();
  3609. this->setAllocatedSize (0);
  3610. numUsed = 0;
  3611. lock.exit();
  3612. }
  3613. /** Removes all elements from the array without freeing the array's allocated storage.
  3614. @see clear
  3615. */
  3616. void clearQuick() throw()
  3617. {
  3618. lock.enter();
  3619. numUsed = 0;
  3620. lock.exit();
  3621. }
  3622. /** Returns the current number of elements in the array.
  3623. */
  3624. inline int size() const throw()
  3625. {
  3626. return numUsed;
  3627. }
  3628. /** Returns one of the elements in the array.
  3629. If the index passed in is beyond the range of valid elements, this
  3630. will return zero.
  3631. If you're certain that the index will always be a valid element, you
  3632. can call getUnchecked() instead, which is faster.
  3633. @param index the index of the element being requested (0 is the first element in the array)
  3634. @see getUnchecked, getFirst, getLast
  3635. */
  3636. inline ElementType operator[] (const int index) const throw()
  3637. {
  3638. lock.enter();
  3639. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3640. ? this->elements [index]
  3641. : ElementType();
  3642. lock.exit();
  3643. return result;
  3644. }
  3645. /** Returns one of the elements in the array, without checking the index passed in.
  3646. Unlike the operator[] method, this will try to return an element without
  3647. checking that the index is within the bounds of the array, so should only
  3648. be used when you're confident that it will always be a valid index.
  3649. @param index the index of the element being requested (0 is the first element in the array)
  3650. @see operator[], getFirst, getLast
  3651. */
  3652. inline ElementType getUnchecked (const int index) const throw()
  3653. {
  3654. lock.enter();
  3655. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3656. const ElementType result = this->elements [index];
  3657. lock.exit();
  3658. return result;
  3659. }
  3660. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3661. This is like getUnchecked, but returns a direct reference to the element, so that
  3662. you can alter it directly. Obviously this can be dangerous, so only use it when
  3663. absolutely necessary.
  3664. @param index the index of the element being requested (0 is the first element in the array)
  3665. @see operator[], getFirst, getLast
  3666. */
  3667. inline ElementType& getReference (const int index) const throw()
  3668. {
  3669. lock.enter();
  3670. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3671. ElementType& result = this->elements [index];
  3672. lock.exit();
  3673. return result;
  3674. }
  3675. /** Returns the first element in the array, or 0 if the array is empty.
  3676. @see operator[], getUnchecked, getLast
  3677. */
  3678. inline ElementType getFirst() const throw()
  3679. {
  3680. lock.enter();
  3681. const ElementType result = (numUsed > 0) ? this->elements [0]
  3682. : ElementType();
  3683. lock.exit();
  3684. return result;
  3685. }
  3686. /** Returns the last element in the array, or 0 if the array is empty.
  3687. @see operator[], getUnchecked, getFirst
  3688. */
  3689. inline ElementType getLast() const throw()
  3690. {
  3691. lock.enter();
  3692. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3693. : ElementType();
  3694. lock.exit();
  3695. return result;
  3696. }
  3697. /** Finds the index of the first element which matches the value passed in.
  3698. This will search the array for the given object, and return the index
  3699. of its first occurrence. If the object isn't found, the method will return -1.
  3700. @param elementToLookFor the value or object to look for
  3701. @returns the index of the object, or -1 if it's not found
  3702. */
  3703. int indexOf (const ElementType elementToLookFor) const throw()
  3704. {
  3705. int result = -1;
  3706. lock.enter();
  3707. const ElementType* e = this->elements;
  3708. for (int i = numUsed; --i >= 0;)
  3709. {
  3710. if (elementToLookFor == *e)
  3711. {
  3712. result = (int) (e - this->elements);
  3713. break;
  3714. }
  3715. ++e;
  3716. }
  3717. lock.exit();
  3718. return result;
  3719. }
  3720. /** Returns true if the array contains at least one occurrence of an object.
  3721. @param elementToLookFor the value or object to look for
  3722. @returns true if the item is found
  3723. */
  3724. bool contains (const ElementType elementToLookFor) const throw()
  3725. {
  3726. lock.enter();
  3727. const ElementType* e = this->elements;
  3728. int num = numUsed;
  3729. while (num >= 4)
  3730. {
  3731. if (*e == elementToLookFor
  3732. || *++e == elementToLookFor
  3733. || *++e == elementToLookFor
  3734. || *++e == elementToLookFor)
  3735. {
  3736. lock.exit();
  3737. return true;
  3738. }
  3739. num -= 4;
  3740. ++e;
  3741. }
  3742. while (num > 0)
  3743. {
  3744. if (elementToLookFor == *e)
  3745. {
  3746. lock.exit();
  3747. return true;
  3748. }
  3749. --num;
  3750. ++e;
  3751. }
  3752. lock.exit();
  3753. return false;
  3754. }
  3755. /** Appends a new element at the end of the array.
  3756. @param newElement the new object to add to the array
  3757. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3758. */
  3759. void add (const ElementType newElement) throw()
  3760. {
  3761. lock.enter();
  3762. this->ensureAllocatedSize (numUsed + 1);
  3763. this->elements [numUsed++] = newElement;
  3764. lock.exit();
  3765. }
  3766. /** Inserts a new element into the array at a given position.
  3767. If the index is less than 0 or greater than the size of the array, the
  3768. element will be added to the end of the array.
  3769. Otherwise, it will be inserted into the array, moving all the later elements
  3770. along to make room.
  3771. @param indexToInsertAt the index at which the new element should be
  3772. inserted (pass in -1 to add it to the end)
  3773. @param newElement the new object to add to the array
  3774. @see add, addSorted, set
  3775. */
  3776. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3777. {
  3778. lock.enter();
  3779. this->ensureAllocatedSize (numUsed + 1);
  3780. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3781. {
  3782. ElementType* const insertPos = this->elements + indexToInsertAt;
  3783. const int numberToMove = numUsed - indexToInsertAt;
  3784. if (numberToMove > 0)
  3785. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3786. *insertPos = newElement;
  3787. ++numUsed;
  3788. }
  3789. else
  3790. {
  3791. this->elements [numUsed++] = newElement;
  3792. }
  3793. lock.exit();
  3794. }
  3795. /** Inserts multiple copies of an element into the array at a given position.
  3796. If the index is less than 0 or greater than the size of the array, the
  3797. element will be added to the end of the array.
  3798. Otherwise, it will be inserted into the array, moving all the later elements
  3799. along to make room.
  3800. @param indexToInsertAt the index at which the new element should be inserted
  3801. @param newElement the new object to add to the array
  3802. @param numberOfTimesToInsertIt how many copies of the value to insert
  3803. @see insert, add, addSorted, set
  3804. */
  3805. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3806. int numberOfTimesToInsertIt) throw()
  3807. {
  3808. if (numberOfTimesToInsertIt > 0)
  3809. {
  3810. lock.enter();
  3811. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3812. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3813. {
  3814. ElementType* insertPos = this->elements + indexToInsertAt;
  3815. const int numberToMove = numUsed - indexToInsertAt;
  3816. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3817. numUsed += numberOfTimesToInsertIt;
  3818. while (--numberOfTimesToInsertIt >= 0)
  3819. *insertPos++ = newElement;
  3820. }
  3821. else
  3822. {
  3823. while (--numberOfTimesToInsertIt >= 0)
  3824. this->elements [numUsed++] = newElement;
  3825. }
  3826. lock.exit();
  3827. }
  3828. }
  3829. /** Inserts an array of values into this array at a given position.
  3830. If the index is less than 0 or greater than the size of the array, the
  3831. new elements will be added to the end of the array.
  3832. Otherwise, they will be inserted into the array, moving all the later elements
  3833. along to make room.
  3834. @param indexToInsertAt the index at which the first new element should be inserted
  3835. @param newElements the new values to add to the array
  3836. @param numberOfElements how many items are in the array
  3837. @see insert, add, addSorted, set
  3838. */
  3839. void insertArray (int indexToInsertAt,
  3840. const ElementType* newElements,
  3841. int numberOfElements) throw()
  3842. {
  3843. if (numberOfElements > 0)
  3844. {
  3845. lock.enter();
  3846. this->ensureAllocatedSize (numUsed + numberOfElements);
  3847. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3848. {
  3849. ElementType* insertPos = this->elements + indexToInsertAt;
  3850. const int numberToMove = numUsed - indexToInsertAt;
  3851. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3852. numUsed += numberOfElements;
  3853. while (--numberOfElements >= 0)
  3854. *insertPos++ = *newElements++;
  3855. }
  3856. else
  3857. {
  3858. while (--numberOfElements >= 0)
  3859. this->elements [numUsed++] = *newElements++;
  3860. }
  3861. lock.exit();
  3862. }
  3863. }
  3864. /** Appends a new element at the end of the array as long as the array doesn't
  3865. already contain it.
  3866. If the array already contains an element that matches the one passed in, nothing
  3867. will be done.
  3868. @param newElement the new object to add to the array
  3869. */
  3870. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3871. {
  3872. lock.enter();
  3873. if (! contains (newElement))
  3874. add (newElement);
  3875. lock.exit();
  3876. }
  3877. /** Replaces an element with a new value.
  3878. If the index is less than zero, this method does nothing.
  3879. If the index is beyond the end of the array, the item is added to the end of the array.
  3880. @param indexToChange the index whose value you want to change
  3881. @param newValue the new value to set for this index.
  3882. @see add, insert
  3883. */
  3884. void set (const int indexToChange,
  3885. const ElementType newValue) throw()
  3886. {
  3887. jassert (indexToChange >= 0);
  3888. if (indexToChange >= 0)
  3889. {
  3890. lock.enter();
  3891. if (indexToChange < numUsed)
  3892. {
  3893. this->elements [indexToChange] = newValue;
  3894. }
  3895. else
  3896. {
  3897. this->ensureAllocatedSize (numUsed + 1);
  3898. this->elements [numUsed++] = newValue;
  3899. }
  3900. lock.exit();
  3901. }
  3902. }
  3903. /** Replaces an element with a new value without doing any bounds-checking.
  3904. This just sets a value directly in the array's internal storage, so you'd
  3905. better make sure it's in range!
  3906. @param indexToChange the index whose value you want to change
  3907. @param newValue the new value to set for this index.
  3908. @see set, getUnchecked
  3909. */
  3910. void setUnchecked (const int indexToChange,
  3911. const ElementType newValue) throw()
  3912. {
  3913. lock.enter();
  3914. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3915. this->elements [indexToChange] = newValue;
  3916. lock.exit();
  3917. }
  3918. /** Adds elements from an array to the end of this array.
  3919. @param elementsToAdd the array of elements to add
  3920. @param numElementsToAdd how many elements are in this other array
  3921. @see add
  3922. */
  3923. void addArray (const ElementType* elementsToAdd,
  3924. int numElementsToAdd) throw()
  3925. {
  3926. lock.enter();
  3927. if (numElementsToAdd > 0)
  3928. {
  3929. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3930. while (--numElementsToAdd >= 0)
  3931. this->elements [numUsed++] = *elementsToAdd++;
  3932. }
  3933. lock.exit();
  3934. }
  3935. /** This swaps the contents of this array with those of another array.
  3936. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3937. because it just swaps their internal pointers.
  3938. */
  3939. template <class OtherArrayType>
  3940. void swapWithArray (OtherArrayType& otherArray) throw()
  3941. {
  3942. lock.enter();
  3943. otherArray.lock.enter();
  3944. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3945. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3946. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3947. otherArray.lock.exit();
  3948. lock.exit();
  3949. }
  3950. /** Adds elements from another array to the end of this array.
  3951. @param arrayToAddFrom the array from which to copy the elements
  3952. @param startIndex the first element of the other array to start copying from
  3953. @param numElementsToAdd how many elements to add from the other array. If this
  3954. value is negative or greater than the number of available elements,
  3955. all available elements will be copied.
  3956. @see add
  3957. */
  3958. template <class OtherArrayType>
  3959. void addArray (const OtherArrayType& arrayToAddFrom,
  3960. int startIndex = 0,
  3961. int numElementsToAdd = -1) throw()
  3962. {
  3963. arrayToAddFrom.lockArray();
  3964. lock.enter();
  3965. jassert (this != &arrayToAddFrom);
  3966. if (startIndex < 0)
  3967. {
  3968. jassertfalse
  3969. startIndex = 0;
  3970. }
  3971. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3972. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3973. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  3974. lock.exit();
  3975. arrayToAddFrom.unlockArray();
  3976. }
  3977. /** Inserts a new element into the array, assuming that the array is sorted.
  3978. This will use a comparator to find the position at which the new element
  3979. should go. If the array isn't sorted, the behaviour of this
  3980. method will be unpredictable.
  3981. @param comparator the comparator to use to compare the elements - see the sort()
  3982. method for details about the form this object should take
  3983. @param newElement the new element to insert to the array
  3984. @see add, sort
  3985. */
  3986. template <class ElementComparator>
  3987. void addSorted (ElementComparator& comparator,
  3988. const ElementType newElement) throw()
  3989. {
  3990. lock.enter();
  3991. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  3992. lock.exit();
  3993. }
  3994. /** Finds the index of an element in the array, assuming that the array is sorted.
  3995. This will use a comparator to do a binary-chop to find the index of the given
  3996. element, if it exists. If the array isn't sorted, the behaviour of this
  3997. method will be unpredictable.
  3998. @param comparator the comparator to use to compare the elements - see the sort()
  3999. method for details about the form this object should take
  4000. @param elementToLookFor the element to search for
  4001. @returns the index of the element, or -1 if it's not found
  4002. @see addSorted, sort
  4003. */
  4004. template <class ElementComparator>
  4005. int indexOfSorted (ElementComparator& comparator,
  4006. const ElementType elementToLookFor) const throw()
  4007. {
  4008. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4009. // avoids getting warning messages about the parameter being unused
  4010. lock.enter();
  4011. int start = 0;
  4012. int end = numUsed;
  4013. for (;;)
  4014. {
  4015. if (start >= end)
  4016. {
  4017. lock.exit();
  4018. return -1;
  4019. }
  4020. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4021. {
  4022. lock.exit();
  4023. return start;
  4024. }
  4025. else
  4026. {
  4027. const int halfway = (start + end) >> 1;
  4028. if (halfway == start)
  4029. {
  4030. lock.exit();
  4031. return -1;
  4032. }
  4033. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4034. start = halfway;
  4035. else
  4036. end = halfway;
  4037. }
  4038. }
  4039. }
  4040. /** Removes an element from the array.
  4041. This will remove the element at a given index, and move back
  4042. all the subsequent elements to close the gap.
  4043. If the index passed in is out-of-range, nothing will happen.
  4044. @param indexToRemove the index of the element to remove
  4045. @returns the element that has been removed
  4046. @see removeValue, removeRange
  4047. */
  4048. ElementType remove (const int indexToRemove) throw()
  4049. {
  4050. lock.enter();
  4051. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4052. {
  4053. --numUsed;
  4054. ElementType* const e = this->elements + indexToRemove;
  4055. ElementType const removed = *e;
  4056. const int numberToShift = numUsed - indexToRemove;
  4057. if (numberToShift > 0)
  4058. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4059. if ((numUsed << 1) < this->numAllocated)
  4060. minimiseStorageOverheads();
  4061. lock.exit();
  4062. return removed;
  4063. }
  4064. else
  4065. {
  4066. lock.exit();
  4067. return ElementType();
  4068. }
  4069. }
  4070. /** Removes an item from the array.
  4071. This will remove the first occurrence of the given element from the array.
  4072. If the item isn't found, no action is taken.
  4073. @param valueToRemove the object to try to remove
  4074. @see remove, removeRange
  4075. */
  4076. void removeValue (const ElementType valueToRemove) throw()
  4077. {
  4078. lock.enter();
  4079. ElementType* e = this->elements;
  4080. for (int i = numUsed; --i >= 0;)
  4081. {
  4082. if (valueToRemove == *e)
  4083. {
  4084. remove ((int) (e - this->elements));
  4085. break;
  4086. }
  4087. ++e;
  4088. }
  4089. lock.exit();
  4090. }
  4091. /** Removes a range of elements from the array.
  4092. This will remove a set of elements, starting from the given index,
  4093. and move subsequent elements down to close the gap.
  4094. If the range extends beyond the bounds of the array, it will
  4095. be safely clipped to the size of the array.
  4096. @param startIndex the index of the first element to remove
  4097. @param numberToRemove how many elements should be removed
  4098. @see remove, removeValue
  4099. */
  4100. void removeRange (int startIndex,
  4101. const int numberToRemove) throw()
  4102. {
  4103. lock.enter();
  4104. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4105. startIndex = jlimit (0, numUsed, startIndex);
  4106. if (endIndex > startIndex)
  4107. {
  4108. const int rangeSize = endIndex - startIndex;
  4109. ElementType* e = this->elements + startIndex;
  4110. int numToShift = numUsed - endIndex;
  4111. numUsed -= rangeSize;
  4112. while (--numToShift >= 0)
  4113. {
  4114. *e = e [rangeSize];
  4115. ++e;
  4116. }
  4117. if ((numUsed << 1) < this->numAllocated)
  4118. minimiseStorageOverheads();
  4119. }
  4120. lock.exit();
  4121. }
  4122. /** Removes the last n elements from the array.
  4123. @param howManyToRemove how many elements to remove from the end of the array
  4124. @see remove, removeValue, removeRange
  4125. */
  4126. void removeLast (const int howManyToRemove = 1) throw()
  4127. {
  4128. lock.enter();
  4129. numUsed = jmax (0, numUsed - howManyToRemove);
  4130. if ((numUsed << 1) < this->numAllocated)
  4131. minimiseStorageOverheads();
  4132. lock.exit();
  4133. }
  4134. /** Removes any elements which are also in another array.
  4135. @param otherArray the other array in which to look for elements to remove
  4136. @see removeValuesNotIn, remove, removeValue, removeRange
  4137. */
  4138. template <class OtherArrayType>
  4139. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4140. {
  4141. otherArray.lockArray();
  4142. lock.enter();
  4143. if (this == &otherArray)
  4144. {
  4145. clear();
  4146. }
  4147. else
  4148. {
  4149. if (otherArray.size() > 0)
  4150. {
  4151. for (int i = numUsed; --i >= 0;)
  4152. if (otherArray.contains (this->elements [i]))
  4153. remove (i);
  4154. }
  4155. }
  4156. lock.exit();
  4157. otherArray.unlockArray();
  4158. }
  4159. /** Removes any elements which are not found in another array.
  4160. Only elements which occur in this other array will be retained.
  4161. @param otherArray the array in which to look for elements NOT to remove
  4162. @see removeValuesIn, remove, removeValue, removeRange
  4163. */
  4164. template <class OtherArrayType>
  4165. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4166. {
  4167. otherArray.lockArray();
  4168. lock.enter();
  4169. if (this != &otherArray)
  4170. {
  4171. if (otherArray.size() <= 0)
  4172. {
  4173. clear();
  4174. }
  4175. else
  4176. {
  4177. for (int i = numUsed; --i >= 0;)
  4178. if (! otherArray.contains (this->elements [i]))
  4179. remove (i);
  4180. }
  4181. }
  4182. lock.exit();
  4183. otherArray.unlockArray();
  4184. }
  4185. /** Swaps over two elements in the array.
  4186. This swaps over the elements found at the two indexes passed in.
  4187. If either index is out-of-range, this method will do nothing.
  4188. @param index1 index of one of the elements to swap
  4189. @param index2 index of the other element to swap
  4190. */
  4191. void swap (const int index1,
  4192. const int index2) throw()
  4193. {
  4194. lock.enter();
  4195. if (((unsigned int) index1) < (unsigned int) numUsed
  4196. && ((unsigned int) index2) < (unsigned int) numUsed)
  4197. {
  4198. swapVariables (this->elements [index1],
  4199. this->elements [index2]);
  4200. }
  4201. lock.exit();
  4202. }
  4203. /** Moves one of the values to a different position.
  4204. This will move the value to a specified index, shuffling along
  4205. any intervening elements as required.
  4206. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4207. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4208. @param currentIndex the index of the value to be moved. If this isn't a
  4209. valid index, then nothing will be done
  4210. @param newIndex the index at which you'd like this value to end up. If this
  4211. is less than zero, the value will be moved to the end
  4212. of the array
  4213. */
  4214. void move (const int currentIndex,
  4215. int newIndex) throw()
  4216. {
  4217. if (currentIndex != newIndex)
  4218. {
  4219. lock.enter();
  4220. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4221. {
  4222. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4223. newIndex = numUsed - 1;
  4224. const ElementType value = this->elements [currentIndex];
  4225. if (newIndex > currentIndex)
  4226. {
  4227. memmove (this->elements + currentIndex,
  4228. this->elements + currentIndex + 1,
  4229. (newIndex - currentIndex) * sizeof (ElementType));
  4230. }
  4231. else
  4232. {
  4233. memmove (this->elements + newIndex + 1,
  4234. this->elements + newIndex,
  4235. (currentIndex - newIndex) * sizeof (ElementType));
  4236. }
  4237. this->elements [newIndex] = value;
  4238. }
  4239. lock.exit();
  4240. }
  4241. }
  4242. /** Reduces the amount of storage being used by the array.
  4243. Arrays typically allocate slightly more storage than they need, and after
  4244. removing elements, they may have quite a lot of unused space allocated.
  4245. This method will reduce the amount of allocated storage to a minimum.
  4246. */
  4247. void minimiseStorageOverheads() throw()
  4248. {
  4249. lock.enter();
  4250. if (numUsed == 0)
  4251. {
  4252. this->setAllocatedSize (0);
  4253. }
  4254. else
  4255. {
  4256. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4257. if (newAllocation < this->numAllocated)
  4258. this->setAllocatedSize (newAllocation);
  4259. }
  4260. lock.exit();
  4261. }
  4262. /** Increases the array's internal storage to hold a minimum number of elements.
  4263. Calling this before adding a large known number of elements means that
  4264. the array won't have to keep dynamically resizing itself as the elements
  4265. are added, and it'll therefore be more efficient.
  4266. */
  4267. void ensureStorageAllocated (const int minNumElements) throw()
  4268. {
  4269. this->ensureAllocatedSize (minNumElements);
  4270. }
  4271. /** Sorts the elements in the array.
  4272. This will use a comparator object to sort the elements into order. The object
  4273. passed must have a method of the form:
  4274. @code
  4275. int compareElements (ElementType first, ElementType second);
  4276. @endcode
  4277. ..and this method must return:
  4278. - a value of < 0 if the first comes before the second
  4279. - a value of 0 if the two objects are equivalent
  4280. - a value of > 0 if the second comes before the first
  4281. To improve performance, the compareElements() method can be declared as static or const.
  4282. @param comparator the comparator to use for comparing elements.
  4283. @param retainOrderOfEquivalentItems if this is true, then items
  4284. which the comparator says are equivalent will be
  4285. kept in the order in which they currently appear
  4286. in the array. This is slower to perform, but may
  4287. be important in some cases. If it's false, a faster
  4288. algorithm is used, but equivalent elements may be
  4289. rearranged.
  4290. @see addSorted, indexOfSorted, sortArray
  4291. */
  4292. template <class ElementComparator>
  4293. void sort (ElementComparator& comparator,
  4294. const bool retainOrderOfEquivalentItems = false) const throw()
  4295. {
  4296. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4297. // avoids getting warning messages about the parameter being unused
  4298. lock.enter();
  4299. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4300. lock.exit();
  4301. }
  4302. /** Locks the array's CriticalSection.
  4303. Of course if the type of section used is a DummyCriticalSection, this won't
  4304. have any effect.
  4305. @see unlockArray
  4306. */
  4307. void lockArray() const throw()
  4308. {
  4309. lock.enter();
  4310. }
  4311. /** Unlocks the array's CriticalSection.
  4312. Of course if the type of section used is a DummyCriticalSection, this won't
  4313. have any effect.
  4314. @see lockArray
  4315. */
  4316. void unlockArray() const throw()
  4317. {
  4318. lock.exit();
  4319. }
  4320. juce_UseDebuggingNewOperator
  4321. private:
  4322. int numUsed;
  4323. TypeOfCriticalSectionToUse lock;
  4324. };
  4325. #endif // __JUCE_ARRAY_JUCEHEADER__
  4326. /********* End of inlined file: juce_Array.h *********/
  4327. /**
  4328. A typedef for an Array of void*'s.
  4329. VoidArrays are used in various places throughout the library instead of
  4330. more strongly-typed arrays, to keep code-size low.
  4331. */
  4332. typedef Array <void*> VoidArray;
  4333. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4334. /********* End of inlined file: juce_VoidArray.h *********/
  4335. #ifndef DOXYGEN
  4336. // (used in StringArray::appendNumbersToDuplicates)
  4337. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4338. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4339. #endif
  4340. /**
  4341. A special array for holding a list of strings.
  4342. @see String, StringPairArray
  4343. */
  4344. class JUCE_API StringArray
  4345. {
  4346. public:
  4347. /** Creates an empty string array */
  4348. StringArray() throw();
  4349. /** Creates a copy of another string array */
  4350. StringArray (const StringArray& other) throw();
  4351. /** Creates a copy of an array of string literals.
  4352. @param strings an array of strings to add. Null pointers in the array will be
  4353. treated as empty strings
  4354. @param numberOfStrings how many items there are in the array
  4355. */
  4356. StringArray (const juce_wchar** const strings,
  4357. const int numberOfStrings) throw();
  4358. /** Creates a copy of an array of string literals.
  4359. @param strings an array of strings to add. Null pointers in the array will be
  4360. treated as empty strings
  4361. @param numberOfStrings how many items there are in the array
  4362. */
  4363. StringArray (const char** const strings,
  4364. const int numberOfStrings) throw();
  4365. /** Creates a copy of a null-terminated array of string literals.
  4366. Each item from the array passed-in is added, until it encounters a null pointer,
  4367. at which point it stops.
  4368. */
  4369. StringArray (const juce_wchar** const strings) throw();
  4370. /** Creates a copy of a null-terminated array of string literals.
  4371. Each item from the array passed-in is added, until it encounters a null pointer,
  4372. at which point it stops.
  4373. */
  4374. StringArray (const char** const strings) throw();
  4375. /** Destructor. */
  4376. virtual ~StringArray() throw();
  4377. /** Copies the contents of another string array into this one */
  4378. const StringArray& operator= (const StringArray& other) throw();
  4379. /** Compares two arrays.
  4380. Comparisons are case-sensitive.
  4381. @returns true only if the other array contains exactly the same strings in the same order
  4382. */
  4383. bool operator== (const StringArray& other) const throw();
  4384. /** Compares two arrays.
  4385. Comparisons are case-sensitive.
  4386. @returns false if the other array contains exactly the same strings in the same order
  4387. */
  4388. bool operator!= (const StringArray& other) const throw();
  4389. /** Returns the number of strings in the array */
  4390. inline int size() const throw() { return strings.size(); };
  4391. /** Returns one of the strings from the array.
  4392. If the index is out-of-range, an empty string is returned.
  4393. Obviously the reference returned shouldn't be stored for later use, as the
  4394. string it refers to may disappear when the array changes.
  4395. */
  4396. const String& operator[] (const int index) const throw();
  4397. /** Searches for a string in the array.
  4398. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4399. @returns true if the string is found inside the array
  4400. */
  4401. bool contains (const String& stringToLookFor,
  4402. const bool ignoreCase = false) const throw();
  4403. /** Searches for a string in the array.
  4404. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4405. @param stringToLookFor the string to try to find
  4406. @param ignoreCase whether the comparison should be case-insensitive
  4407. @param startIndex the first index to start searching from
  4408. @returns the index of the first occurrence of the string in this array,
  4409. or -1 if it isn't found.
  4410. */
  4411. int indexOf (const String& stringToLookFor,
  4412. const bool ignoreCase = false,
  4413. int startIndex = 0) const throw();
  4414. /** Appends a string at the end of the array. */
  4415. void add (const String& stringToAdd) throw();
  4416. /** Inserts a string into the array.
  4417. This will insert a string into the array at the given index, moving
  4418. up the other elements to make room for it.
  4419. If the index is less than zero or greater than the size of the array,
  4420. the new string will be added to the end of the array.
  4421. */
  4422. void insert (const int index,
  4423. const String& stringToAdd) throw();
  4424. /** Adds a string to the array as long as it's not already in there.
  4425. The search can optionally be case-insensitive.
  4426. */
  4427. void addIfNotAlreadyThere (const String& stringToAdd,
  4428. const bool ignoreCase = false) throw();
  4429. /** Replaces one of the strings in the array with another one.
  4430. If the index is higher than the array's size, the new string will be
  4431. added to the end of the array; if it's less than zero nothing happens.
  4432. */
  4433. void set (const int index,
  4434. const String& newString) throw();
  4435. /** Appends some strings from another array to the end of this one.
  4436. @param other the array to add
  4437. @param startIndex the first element of the other array to add
  4438. @param numElementsToAdd the maximum number of elements to add (if this is
  4439. less than zero, they are all added)
  4440. */
  4441. void addArray (const StringArray& other,
  4442. int startIndex = 0,
  4443. int numElementsToAdd = -1) throw();
  4444. /** Breaks up a string into tokens and adds them to this array.
  4445. This will tokenise the given string using whitespace characters as the
  4446. token delimiters, and will add these tokens to the end of the array.
  4447. @returns the number of tokens added
  4448. */
  4449. int addTokens (const tchar* const stringToTokenise,
  4450. const bool preserveQuotedStrings) throw();
  4451. /** Breaks up a string into tokens and adds them to this array.
  4452. This will tokenise the given string (using the string passed in to define the
  4453. token delimiters), and will add these tokens to the end of the array.
  4454. @param stringToTokenise the string to tokenise
  4455. @param breakCharacters a string of characters, any of which will be considered
  4456. to be a token delimiter.
  4457. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4458. which are treated as quotes. Any text occurring
  4459. between quotes is not broken up into tokens.
  4460. @returns the number of tokens added
  4461. */
  4462. int addTokens (const tchar* const stringToTokenise,
  4463. const tchar* breakCharacters,
  4464. const tchar* quoteCharacters) throw();
  4465. /** Breaks up a string into lines and adds them to this array.
  4466. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4467. to the array. Line-break characters are omitted from the strings that are added to
  4468. the array.
  4469. */
  4470. int addLines (const tchar* stringToBreakUp) throw();
  4471. /** Removes all elements from the array. */
  4472. void clear() throw();
  4473. /** Removes a string from the array.
  4474. If the index is out-of-range, no action will be taken.
  4475. */
  4476. void remove (const int index) throw();
  4477. /** Finds a string in the array and removes it.
  4478. This will remove the first occurrence of the given string from the array. The
  4479. comparison may be case-insensitive depending on the ignoreCase parameter.
  4480. */
  4481. void removeString (const String& stringToRemove,
  4482. const bool ignoreCase = false) throw();
  4483. /** Removes any duplicated elements from the array.
  4484. If any string appears in the array more than once, only the first occurrence of
  4485. it will be retained.
  4486. @param ignoreCase whether to use a case-insensitive comparison
  4487. */
  4488. void removeDuplicates (const bool ignoreCase) throw();
  4489. /** Removes empty strings from the array.
  4490. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4491. characters will also be removed
  4492. */
  4493. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4494. /** Moves one of the strings to a different position.
  4495. This will move the string to a specified index, shuffling along
  4496. any intervening elements as required.
  4497. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4498. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4499. @param currentIndex the index of the value to be moved. If this isn't a
  4500. valid index, then nothing will be done
  4501. @param newIndex the index at which you'd like this value to end up. If this
  4502. is less than zero, the value will be moved to the end
  4503. of the array
  4504. */
  4505. void move (const int currentIndex, int newIndex) throw();
  4506. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4507. void trim() throw();
  4508. /** Adds numbers to the strings in the array, to make each string unique.
  4509. This will add numbers to the ends of groups of similar strings.
  4510. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4511. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4512. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4513. also has a number appended to it.
  4514. @param preNumberString when adding a number, this string is added before the number
  4515. @param postNumberString this string is appended after any numbers that are added
  4516. */
  4517. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4518. const bool appendNumberToFirstInstance,
  4519. const tchar* const preNumberString = defaultPreNumberString,
  4520. const tchar* const postNumberString = defaultPostNumberString) throw();
  4521. /** Joins the strings in the array together into one string.
  4522. This will join a range of elements from the array into a string, separating
  4523. them with a given string.
  4524. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4525. @param separatorString the string to insert between all the strings
  4526. @param startIndex the first element to join
  4527. @param numberOfElements how many elements to join together. If this is less
  4528. than zero, all available elements will be used.
  4529. */
  4530. const String joinIntoString (const String& separatorString,
  4531. int startIndex = 0,
  4532. int numberOfElements = -1) const throw();
  4533. /** Sorts the array into alphabetical order.
  4534. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4535. */
  4536. void sort (const bool ignoreCase) throw();
  4537. /** Reduces the amount of storage being used by the array.
  4538. Arrays typically allocate slightly more storage than they need, and after
  4539. removing elements, they may have quite a lot of unused space allocated.
  4540. This method will reduce the amount of allocated storage to a minimum.
  4541. */
  4542. void minimiseStorageOverheads() throw();
  4543. juce_UseDebuggingNewOperator
  4544. private:
  4545. VoidArray strings;
  4546. };
  4547. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4548. /********* End of inlined file: juce_StringArray.h *********/
  4549. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4550. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4551. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4552. /**
  4553. A class to hold a resizable block of raw data.
  4554. */
  4555. class JUCE_API MemoryBlock
  4556. {
  4557. public:
  4558. /** Create an uninitialised block with 0 size. */
  4559. MemoryBlock() throw();
  4560. /** Creates a memory block with a given initial size.
  4561. @param initialSize the size of block to create
  4562. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4563. */
  4564. MemoryBlock (const int initialSize,
  4565. const bool initialiseToZero = false) throw();
  4566. /** Creates a copy of another memory block. */
  4567. MemoryBlock (const MemoryBlock& other) throw();
  4568. /** Creates a memory block using a copy of a block of data.
  4569. @param dataToInitialiseFrom some data to copy into this block
  4570. @param sizeInBytes how much space to use
  4571. */
  4572. MemoryBlock (const void* const dataToInitialiseFrom,
  4573. const int sizeInBytes) throw();
  4574. /** Destructor. */
  4575. ~MemoryBlock() throw();
  4576. /** Copies another memory block onto this one.
  4577. This block will be resized and copied to exactly match the other one.
  4578. */
  4579. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4580. /** Compares two memory blocks.
  4581. @returns true only if the two blocks are the same size and have identical contents.
  4582. */
  4583. bool operator== (const MemoryBlock& other) const throw();
  4584. /** Compares two memory blocks.
  4585. @returns true if the two blocks are different sizes or have different contents.
  4586. */
  4587. bool operator!= (const MemoryBlock& other) const throw();
  4588. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4589. Note that the pointer returned will probably become invalid when the
  4590. block is resized.
  4591. */
  4592. template <class DataType>
  4593. operator DataType*() const throw() { return (DataType*) data; }
  4594. /** Returns a void pointer to the data.
  4595. Note that the pointer returned will probably become invalid when the
  4596. block is resized.
  4597. */
  4598. void* getData() const throw() { return data; }
  4599. /** Returns a byte from the memory block.
  4600. This returns a reference, so you can also use it to set a byte.
  4601. */
  4602. char& operator[] (const int offset) const throw() { return data [offset]; }
  4603. /** Returns the block's current allocated size, in bytes. */
  4604. int getSize() const throw() { return size; }
  4605. /** Resizes the memory block.
  4606. This will try to keep as much of the block's current content as it can,
  4607. and can optionally be made to clear any new space that gets allocated at
  4608. the end of the block.
  4609. @param newSize the new desired size for the block
  4610. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4611. whether to clear the new section or just leave it
  4612. uninitialised
  4613. @see ensureSize
  4614. */
  4615. void setSize (const int newSize,
  4616. const bool initialiseNewSpaceToZero = false) throw();
  4617. /** Increases the block's size only if it's smaller than a given size.
  4618. @param minimumSize if the block is already bigger than this size, no action
  4619. will be taken; otherwise it will be increased to this size
  4620. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4621. whether to clear the new section or just leave it
  4622. uninitialised
  4623. @see setSize
  4624. */
  4625. void ensureSize (const int minimumSize,
  4626. const bool initialiseNewSpaceToZero = false) throw();
  4627. /** Fills the entire memory block with a repeated byte value.
  4628. This is handy for clearing a block of memory to zero.
  4629. */
  4630. void fillWith (const uint8 valueToUse) throw();
  4631. /** Adds another block of data to the end of this one.
  4632. This block's size will be increased accordingly.
  4633. */
  4634. void append (const void* const data,
  4635. const int numBytes) throw();
  4636. /** Copies data into this MemoryBlock from a memory address.
  4637. @param srcData the memory location of the data to copy into this block
  4638. @param destinationOffset the offset in this block at which the data being copied should begin
  4639. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4640. it will be clipped so not to do anything nasty)
  4641. */
  4642. void copyFrom (const void* srcData,
  4643. int destinationOffset,
  4644. int numBytes) throw();
  4645. /** Copies data from this MemoryBlock to a memory address.
  4646. @param destData the memory location to write to
  4647. @param sourceOffset the offset within this block from which the copied data will be read
  4648. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4649. zeros will be used for that portion of the data)
  4650. */
  4651. void copyTo (void* destData,
  4652. int sourceOffset,
  4653. int numBytes) const throw();
  4654. /** Chops out a section of the block.
  4655. This will remove a section of the memory block and close the gap around it,
  4656. shifting any subsequent data downwards and reducing the size of the block.
  4657. If the range specified goes beyond the size of the block, it will be clipped.
  4658. */
  4659. void removeSection (int startByte, int numBytesToRemove) throw();
  4660. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4661. characters in the system's default encoding. */
  4662. const String toString() const throw();
  4663. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4664. The block will be resized to the number of valid bytes read from the string.
  4665. Non-hex characters in the string will be ignored.
  4666. @see String::toHexString()
  4667. */
  4668. void loadFromHexString (const String& sourceHexString) throw();
  4669. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4670. void setBitRange (int bitRangeStart,
  4671. int numBits,
  4672. int binaryNumberToApply) throw();
  4673. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4674. int getBitRange (int bitRangeStart,
  4675. int numBitsToRead) const throw();
  4676. /** Returns a string of characters that represent the binary contents of this block.
  4677. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4678. of simple non-extended characters, e.g. for storage in XML.
  4679. @see fromBase64Encoding
  4680. */
  4681. const String toBase64Encoding() const throw();
  4682. /** Takes a string of encoded characters and turns it into binary data.
  4683. The string passed in must have been created by to64BitEncoding(), and this
  4684. block will be resized to recreate the original data block.
  4685. @see toBase64Encoding
  4686. */
  4687. bool fromBase64Encoding (const String& encodedString) throw();
  4688. juce_UseDebuggingNewOperator
  4689. private:
  4690. char* data;
  4691. int size;
  4692. };
  4693. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4694. /********* End of inlined file: juce_MemoryBlock.h *********/
  4695. class FileInputStream;
  4696. class FileOutputStream;
  4697. /**
  4698. Represents a local file or directory.
  4699. This class encapsulates the absolute pathname of a file or directory, and
  4700. has methods for finding out about the file and changing its properties.
  4701. To read or write to the file, there are methods for returning an input or
  4702. output stream.
  4703. @see FileInputStream, FileOutputStream
  4704. */
  4705. class JUCE_API File
  4706. {
  4707. public:
  4708. /** Creates an (invalid) file object.
  4709. The file is initially set to an empty path, so getFullPath() will return
  4710. an empty string, and comparing the file to File::nonexistent will return
  4711. true.
  4712. You can use its operator= method to point it at a proper file.
  4713. */
  4714. File() throw() {}
  4715. /** Creates a file from an absolute path.
  4716. If the path supplied is a relative path, it is taken to be relative
  4717. to the current working directory (see File::getCurrentWorkingDirectory()),
  4718. but this isn't a recommended way of creating a file, because you
  4719. never know what the CWD is going to be.
  4720. On the Mac/Linux, the path can include "~" notation for referring to
  4721. user home directories.
  4722. */
  4723. File (const String& path) throw();
  4724. /** Creates a copy of another file object. */
  4725. File (const File& other) throw();
  4726. /** Destructor. */
  4727. ~File() throw() {}
  4728. /** Sets the file based on an absolute pathname.
  4729. If the path supplied is a relative path, it is taken to be relative
  4730. to the current working directory (see File::getCurrentWorkingDirectory()),
  4731. but this isn't a recommended way of creating a file, because you
  4732. never know what the CWD is going to be.
  4733. On the Mac/Linux, the path can include "~" notation for referring to
  4734. user home directories.
  4735. */
  4736. const File& operator= (const String& newFilePath) throw();
  4737. /** Copies from another file object. */
  4738. const File& operator= (const File& otherFile) throw();
  4739. /** This static constant is used for referring to an 'invalid' file. */
  4740. static const File nonexistent;
  4741. /** Checks whether the file actually exists.
  4742. @returns true if the file exists, either as a file or a directory.
  4743. @see existsAsFile, isDirectory
  4744. */
  4745. bool exists() const throw();
  4746. /** Checks whether the file exists and is a file rather than a directory.
  4747. @returns true only if this is a real file, false if it's a directory
  4748. or doesn't exist
  4749. @see exists, isDirectory
  4750. */
  4751. bool existsAsFile() const throw();
  4752. /** Checks whether the file is a directory that exists.
  4753. @returns true only if the file is a directory which actually exists, so
  4754. false if it's a file or doesn't exist at all
  4755. @see exists, existsAsFile
  4756. */
  4757. bool isDirectory() const throw();
  4758. /** Returns the size of the file in bytes.
  4759. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4760. */
  4761. int64 getSize() const throw();
  4762. /** Utility function to convert a file size in bytes to a neat string description.
  4763. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4764. 2000000 would produce "2 MB", etc.
  4765. */
  4766. static const String descriptionOfSizeInBytes (const int64 bytes);
  4767. /** Returns the complete, absolute path of this file.
  4768. This includes the filename and all its parent folders. On Windows it'll
  4769. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4770. path starting from the root folder.
  4771. If you just want the file's name, you should use getFileName() or
  4772. getFileNameWithoutExtension().
  4773. @see getFileName, getRelativePathFrom
  4774. */
  4775. const String& getFullPathName() const throw() { return fullPath; }
  4776. /** Returns the last section of the pathname.
  4777. Returns just the final part of the path - e.g. if the whole path
  4778. is "/moose/fish/foo.txt" this will return "foo.txt".
  4779. For a directory, it returns the final part of the path - e.g. for the
  4780. directory "/moose/fish" it'll return "fish".
  4781. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4782. "/moose/.fish", it'll return ".fish"
  4783. @see getFullPathName, getFileNameWithoutExtension
  4784. */
  4785. const String getFileName() const throw();
  4786. /** Creates a relative path that refers to a file relatively to a given directory.
  4787. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4788. would return "../../foo.txt".
  4789. If it's not possible to navigate from one file to the other, an absolute
  4790. path is returned. If the paths are invalid, an empty string may also be
  4791. returned.
  4792. @param directoryToBeRelativeTo the directory which the resultant string will
  4793. be relative to. If this is actually a file rather than
  4794. a directory, its parent directory will be used instead.
  4795. If it doesn't exist, it's assumed to be a directory.
  4796. @see getChildFile, isAbsolutePath
  4797. */
  4798. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4799. /** Returns the file's extension.
  4800. Returns the file extension of this file, also including the dot.
  4801. e.g. "/moose/fish/foo.txt" would return ".txt"
  4802. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4803. */
  4804. const String getFileExtension() const throw();
  4805. /** Checks whether the file has a given extension.
  4806. @param extensionToTest the extension to look for - it doesn't matter whether or
  4807. not this string has a dot at the start, so ".wav" and "wav"
  4808. will have the same effect. The comparison used is
  4809. case-insensitve.
  4810. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4811. */
  4812. bool hasFileExtension (const String& extensionToTest) const throw();
  4813. /** Returns a version of this file with a different file extension.
  4814. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4815. @param newExtension the new extension, either with or without a dot at the start (this
  4816. doesn't make any difference). To get remove a file's extension altogether,
  4817. pass an empty string into this function.
  4818. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4819. */
  4820. const File withFileExtension (const String& newExtension) const throw();
  4821. /** Returns the last part of the filename, without its file extension.
  4822. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4823. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4824. */
  4825. const String getFileNameWithoutExtension() const throw();
  4826. /** Returns a 32-bit hash-code that identifies this file.
  4827. This is based on the filename. Obviously it's possible, although unlikely, that
  4828. two files will have the same hash-code.
  4829. */
  4830. int hashCode() const throw();
  4831. /** Returns a 64-bit hash-code that identifies this file.
  4832. This is based on the filename. Obviously it's possible, although unlikely, that
  4833. two files will have the same hash-code.
  4834. */
  4835. int64 hashCode64() const throw();
  4836. /** Returns a file based on a relative path.
  4837. This will find a child file or directory of the current object.
  4838. e.g.
  4839. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4840. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4841. If the string is actually an absolute path, it will be treated as such, e.g.
  4842. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4843. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4844. */
  4845. const File getChildFile (String relativePath) const throw();
  4846. /** Returns a file which is in the same directory as this one.
  4847. This is equivalent to getParentDirectory().getChildFile (name).
  4848. @see getChildFile, getParentDirectory
  4849. */
  4850. const File getSiblingFile (const String& siblingFileName) const throw();
  4851. /** Returns the directory that contains this file or directory.
  4852. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4853. */
  4854. const File getParentDirectory() const throw();
  4855. /** Checks whether a file is somewhere inside a directory.
  4856. Returns true if this file is somewhere inside a subdirectory of the directory
  4857. that is passed in. Neither file actually has to exist, because the function
  4858. just checks the paths for similarities.
  4859. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4860. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4861. */
  4862. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4863. /** Chooses a filename relative to this one that doesn't already exist.
  4864. If this file is a directory, this will return a child file of this
  4865. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4866. it finds one that isn't already there.
  4867. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4868. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4869. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4870. @param prefix the string to use for the filename before the number
  4871. @param suffix the string to add to the filename after the number
  4872. @param putNumbersInBrackets if true, this will create filenames in the
  4873. format "prefix(number)suffix", if false, it will leave the
  4874. brackets out.
  4875. */
  4876. const File getNonexistentChildFile (const String& prefix,
  4877. const String& suffix,
  4878. bool putNumbersInBrackets = true) const throw();
  4879. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4880. If this file doesn't exist, this will just return itself, otherwise it
  4881. will return an appropriate sibling that doesn't exist, e.g. if a file
  4882. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4883. @param putNumbersInBrackets whether to add brackets around the numbers that
  4884. get appended to the new filename.
  4885. */
  4886. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4887. /** Compares the pathnames for two files. */
  4888. bool operator== (const File& otherFile) const throw();
  4889. /** Compares the pathnames for two files. */
  4890. bool operator!= (const File& otherFile) const throw();
  4891. /** Checks whether a file can be created or written to.
  4892. @returns true if it's possible to create and write to this file. If the file
  4893. doesn't already exist, this will check its parent directory to
  4894. see if writing is allowed.
  4895. @see setReadOnly
  4896. */
  4897. bool hasWriteAccess() const throw();
  4898. /** Changes the write-permission of a file or directory.
  4899. @param shouldBeReadOnly whether to add or remove write-permission
  4900. @param applyRecursively if the file is a directory and this is true, it will
  4901. recurse through all the subfolders changing the permissions
  4902. of all files
  4903. @returns true if it manages to change the file's permissions.
  4904. @see hasWriteAccess
  4905. */
  4906. bool setReadOnly (const bool shouldBeReadOnly,
  4907. const bool applyRecursively = false) const throw();
  4908. /** Returns true if this file is a hidden or system file.
  4909. The criteria for deciding whether a file is hidden are platform-dependent.
  4910. */
  4911. bool isHidden() const throw();
  4912. /** If this file is a link, this returns the file that it points to.
  4913. If this file isn't actually link, it'll just return itself.
  4914. */
  4915. const File getLinkedTarget() const throw();
  4916. /** Returns the last modification time of this file.
  4917. @returns the time, or an invalid time if the file doesn't exist.
  4918. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4919. */
  4920. const Time getLastModificationTime() const throw();
  4921. /** Returns the last time this file was accessed.
  4922. @returns the time, or an invalid time if the file doesn't exist.
  4923. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4924. */
  4925. const Time getLastAccessTime() const throw();
  4926. /** Returns the time that this file was created.
  4927. @returns the time, or an invalid time if the file doesn't exist.
  4928. @see getLastModificationTime, getLastAccessTime
  4929. */
  4930. const Time getCreationTime() const throw();
  4931. /** Changes the modification time for this file.
  4932. @param newTime the time to apply to the file
  4933. @returns true if it manages to change the file's time.
  4934. @see getLastModificationTime, setLastAccessTime, setCreationTime
  4935. */
  4936. bool setLastModificationTime (const Time& newTime) const throw();
  4937. /** Changes the last-access time for this file.
  4938. @param newTime the time to apply to the file
  4939. @returns true if it manages to change the file's time.
  4940. @see getLastAccessTime, setLastModificationTime, setCreationTime
  4941. */
  4942. bool setLastAccessTime (const Time& newTime) const throw();
  4943. /** Changes the creation date for this file.
  4944. @param newTime the time to apply to the file
  4945. @returns true if it manages to change the file's time.
  4946. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4947. */
  4948. bool setCreationTime (const Time& newTime) const throw();
  4949. /** If possible, this will try to create a version string for the given file.
  4950. The OS may be able to look at the file and give a version for it - e.g. with
  4951. executables, bundles, dlls, etc. If no version is available, this will
  4952. return an empty string.
  4953. */
  4954. const String getVersion() const throw();
  4955. /** Creates an empty file if it doesn't already exist.
  4956. If the file that this object refers to doesn't exist, this will create a file
  4957. of zero size.
  4958. If it already exists or is a directory, this method will do nothing.
  4959. @returns true if the file has been created (or if it already existed).
  4960. @see createDirectory
  4961. */
  4962. bool create() const throw();
  4963. /** Creates a new directory for this filename.
  4964. This will try to create the file as a directory, and fill also create
  4965. any parent directories it needs in order to complete the operation.
  4966. @returns true if the directory has been created successfully, (or if it
  4967. already existed beforehand).
  4968. @see create
  4969. */
  4970. bool createDirectory() const throw();
  4971. /** Deletes a file.
  4972. If this file is actually a directory, it may not be deleted correctly if it
  4973. contains files. See deleteRecursively() as a better way of deleting directories.
  4974. @returns true if the file has been successfully deleted (or if it didn't exist to
  4975. begin with).
  4976. @see deleteRecursively
  4977. */
  4978. bool deleteFile() const throw();
  4979. /** Deletes a file or directory and all its subdirectories.
  4980. If this file is a directory, this will try to delete it and all its subfolders. If
  4981. it's just a file, it will just try to delete the file.
  4982. @returns true if the file and all its subfolders have been successfully deleted
  4983. (or if it didn't exist to begin with).
  4984. @see deleteFile
  4985. */
  4986. bool deleteRecursively() const throw();
  4987. /** Moves this file or folder to the trash.
  4988. @returns true if the operation succeeded. It could fail if the trash is full, or
  4989. if the file is write-protected, so you should check the return value
  4990. and act appropriately.
  4991. */
  4992. bool moveToTrash() const throw();
  4993. /** Moves or renames a file.
  4994. Tries to move a file to a different location.
  4995. If the target file already exists, this will attempt to delete it first, and
  4996. will fail if this can't be done.
  4997. Note that the destination file isn't the directory to put it in, it's the actual
  4998. filename that you want the new file to have.
  4999. @returns true if the operation succeeds
  5000. */
  5001. bool moveFileTo (const File& targetLocation) const throw();
  5002. /** Copies a file.
  5003. Tries to copy a file to a different location.
  5004. If the target file already exists, this will attempt to delete it first, and
  5005. will fail if this can't be done.
  5006. @returns true if the operation succeeds
  5007. */
  5008. bool copyFileTo (const File& targetLocation) const throw();
  5009. /** Copies a directory.
  5010. Tries to copy an entire directory, recursively.
  5011. If this file isn't a directory or if any target files can't be created, this
  5012. will return false.
  5013. @param newDirectory the directory that this one should be copied to. Note that this
  5014. is the name of the actual directory to create, not the directory
  5015. into which the new one should be placed, so there must be enough
  5016. write privileges to create it if it doesn't exist. Any files inside
  5017. it will be overwritten by similarly named ones that are copied.
  5018. */
  5019. bool copyDirectoryTo (const File& newDirectory) const throw();
  5020. /** Used in file searching, to specify whether to return files, directories, or both.
  5021. */
  5022. enum TypesOfFileToFind
  5023. {
  5024. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5025. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5026. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5027. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5028. };
  5029. /** Searches inside a directory for files matching a wildcard pattern.
  5030. Assuming that this file is a directory, this method will search it
  5031. for either files or subdirectories whose names match a filename pattern.
  5032. @param results an array to which File objects will be added for the
  5033. files that the search comes up with
  5034. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5035. return files, directories, or both. If the ignoreHiddenFiles flag
  5036. is also added to this value, hidden files won't be returned
  5037. @param searchRecursively if true, all subdirectories will be recursed into to do
  5038. an exhaustive search
  5039. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5040. @returns the number of results that have been found
  5041. @see getNumberOfChildFiles, DirectoryIterator
  5042. */
  5043. int findChildFiles (OwnedArray<File>& results,
  5044. const int whatToLookFor,
  5045. const bool searchRecursively,
  5046. const String& wildCardPattern = JUCE_T("*")) const throw();
  5047. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5048. Assuming that this file is a directory, this method will search it
  5049. for either files or subdirectories whose names match a filename pattern,
  5050. and will return the number of matches found.
  5051. This isn't a recursive call, and will only search this directory, not
  5052. its children.
  5053. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5054. count files, directories, or both. If the ignoreHiddenFiles flag
  5055. is also added to this value, hidden files won't be counted
  5056. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5057. @returns the number of matches found
  5058. @see findChildFiles, DirectoryIterator
  5059. */
  5060. int getNumberOfChildFiles (const int whatToLookFor,
  5061. const String& wildCardPattern = JUCE_T("*")) const throw();
  5062. /** Returns true if this file is a directory that contains one or more subdirectories.
  5063. @see isDirectory, findChildFiles
  5064. */
  5065. bool containsSubDirectories() const throw();
  5066. /** Creates a stream to read from this file.
  5067. @returns a stream that will read from this file (initially positioned at the
  5068. start of the file), or 0 if the file can't be opened for some reason
  5069. @see createOutputStream, loadFileAsData
  5070. */
  5071. FileInputStream* createInputStream() const throw();
  5072. /** Creates a stream to write to this file.
  5073. If the file exists, the stream that is returned will be positioned ready for
  5074. writing at the end of the file, so you might want to use deleteFile() first
  5075. to write to an empty file.
  5076. @returns a stream that will write to this file (initially positioned at the
  5077. end of the file), or 0 if the file can't be opened for some reason
  5078. @see createInputStream, printf, appendData, appendText
  5079. */
  5080. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5081. /** Loads a file's contents into memory as a block of binary data.
  5082. Of course, trying to load a very large file into memory will blow up, so
  5083. it's better to check first.
  5084. @param result the data block to which the file's contents should be appended - note
  5085. that if the memory block might already contain some data, you
  5086. might want to clear it first
  5087. @returns true if the file could all be read into memory
  5088. */
  5089. bool loadFileAsData (MemoryBlock& result) const throw();
  5090. /** Reads a file into memory as a string.
  5091. Attempts to load the entire file as a zero-terminated string.
  5092. This makes use of InputStream::readEntireStreamAsString, which should
  5093. automatically cope with unicode/acsii file formats.
  5094. */
  5095. const String loadFileAsString() const throw();
  5096. /** Writes text to the end of the file.
  5097. This will try to do a printf to the file.
  5098. @returns false if it can't write to the file for some reason
  5099. */
  5100. bool printf (const tchar* format, ...) const throw();
  5101. /** Appends a block of binary data to the end of the file.
  5102. This will try to write the given buffer to the end of the file.
  5103. @returns false if it can't write to the file for some reason
  5104. */
  5105. bool appendData (const void* const dataToAppend,
  5106. const int numberOfBytes) const throw();
  5107. /** Replaces this file's contents with a given block of data.
  5108. This will delete the file and replace it with the given data.
  5109. A nice feature of this method is that it's safe - instead of deleting
  5110. the file first and then re-writing it, it creates a new temporary file,
  5111. writes the data to that, and then moves the new file to replace the existing
  5112. file. This means that if the power gets pulled out or something crashes,
  5113. you're a lot less likely to end up with an empty file..
  5114. Returns true if the operation succeeds, or false if it fails.
  5115. @see appendText
  5116. */
  5117. bool replaceWithData (const void* const dataToWrite,
  5118. const int numberOfBytes) const throw();
  5119. /** Appends a string to the end of the file.
  5120. This will try to append a text string to the file, as either 16-bit unicode
  5121. or 8-bit characters in the default system encoding.
  5122. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5123. the endianness of the file.
  5124. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5125. @see replaceWithText
  5126. */
  5127. bool appendText (const String& textToAppend,
  5128. const bool asUnicode = false,
  5129. const bool writeUnicodeHeaderBytes = false) const throw();
  5130. /** Replaces this file's contents with a given text string.
  5131. This will delete the file and replace it with the given text.
  5132. A nice feature of this method is that it's safe - instead of deleting
  5133. the file first and then re-writing it, it creates a new temporary file,
  5134. writes the text to that, and then moves the new file to replace the existing
  5135. file. This means that if the power gets pulled out or something crashes,
  5136. you're a lot less likely to end up with an empty file..
  5137. For an explanation of the parameters here, see the appendText() method.
  5138. Returns true if the operation succeeds, or false if it fails.
  5139. @see appendText
  5140. */
  5141. bool replaceWithText (const String& textToWrite,
  5142. const bool asUnicode = false,
  5143. const bool writeUnicodeHeaderBytes = false) const throw();
  5144. /** Creates a set of files to represent each file root.
  5145. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5146. to which ones are available. On the Mac/Linux, this will probably
  5147. just add a single entry for "/".
  5148. */
  5149. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5150. /** Finds the name of the drive on which this file lives.
  5151. @returns the volume label of the drive, or an empty string if this isn't possible
  5152. */
  5153. const String getVolumeLabel() const throw();
  5154. /** Returns the serial number of the volume on which this file lives.
  5155. @returns the serial number, or zero if there's a problem doing this
  5156. */
  5157. int getVolumeSerialNumber() const throw();
  5158. /** Returns the number of bytes free on the drive that this file lives on.
  5159. @returns the number of bytes free, or 0 if there's a problem finding this out
  5160. */
  5161. int64 getBytesFreeOnVolume() const throw();
  5162. /** Returns true if this file is on a CD or DVD drive. */
  5163. bool isOnCDRomDrive() const throw();
  5164. /** Returns true if this file is on a hard disk.
  5165. This will fail if it's a network drive, but will still be true for
  5166. removable hard-disks.
  5167. */
  5168. bool isOnHardDisk() const throw();
  5169. /** Returns true if this file is on a removable disk drive.
  5170. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5171. */
  5172. bool isOnRemovableDrive() const throw();
  5173. /** Launches the file as a process.
  5174. - if the file is executable, this will run it.
  5175. - if it's a document of some kind, it will launch the document with its
  5176. default viewer application.
  5177. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5178. */
  5179. bool startAsProcess (const String& parameters = String::empty) const throw();
  5180. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5181. */
  5182. enum SpecialLocationType
  5183. {
  5184. /** The user's home folder. This is the same as using File ("~"). */
  5185. userHomeDirectory,
  5186. /** The user's default documents folder. On Windows, this might be the user's
  5187. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5188. doesn't tend to have one of these, so it might just return their home folder.
  5189. */
  5190. userDocumentsDirectory,
  5191. /** The folder that contains the user's desktop objects. */
  5192. userDesktopDirectory,
  5193. /** The folder in which applications store their persistent user-specific settings.
  5194. On Windows, this might be "\Documents and Settings\username\Application Data".
  5195. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5196. always create your own sub-folder to put them in, to avoid making a mess.
  5197. */
  5198. userApplicationDataDirectory,
  5199. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5200. of the computer, rather than just the current user.
  5201. On the Mac it'll be "/Library", on Windows, it could be something like
  5202. "\Documents and Settings\All Users\Application Data".
  5203. Depending on the setup, this folder may be read-only.
  5204. */
  5205. commonApplicationDataDirectory,
  5206. /** The folder that should be used for temporary files.
  5207. Always delete them when you're finished, to keep the user's computer tidy!
  5208. */
  5209. tempDirectory,
  5210. /** Returns this application's executable file.
  5211. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5212. host app.
  5213. On the mac this will return the unix binary, not the package folder - see
  5214. currentApplicationFile for that.
  5215. */
  5216. currentExecutableFile,
  5217. /** Returns this application's location.
  5218. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5219. host app.
  5220. On the mac this will return the package folder (if it's in one), not the unix binary
  5221. that's inside it - compare with currentExecutableFile.
  5222. */
  5223. currentApplicationFile,
  5224. /** The directory in which applications normally get installed.
  5225. So on windows, this would be something like "c:\program files", on the
  5226. Mac "/Applications", or "/usr" on linux.
  5227. */
  5228. globalApplicationsDirectory,
  5229. /** The most likely place where a user might store their music files.
  5230. */
  5231. userMusicDirectory,
  5232. /** The most likely place where a user might store their movie files.
  5233. */
  5234. userMoviesDirectory,
  5235. };
  5236. /** Finds the location of a special type of file or directory, such as a home folder or
  5237. documents folder.
  5238. @see SpecialLocationType
  5239. */
  5240. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5241. /** Returns a temporary file in the system's temp directory.
  5242. This will try to return the name of a non-existent temp file.
  5243. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5244. */
  5245. static const File createTempFile (const String& fileNameEnding) throw();
  5246. /** Returns the current working directory.
  5247. @see setAsCurrentWorkingDirectory
  5248. */
  5249. static const File getCurrentWorkingDirectory() throw();
  5250. /** Sets the current working directory to be this file.
  5251. For this to work the file must point to a valid directory.
  5252. @returns true if the current directory has been changed.
  5253. @see getCurrentWorkingDirectory
  5254. */
  5255. bool setAsCurrentWorkingDirectory() const throw();
  5256. /** The system-specific file separator character.
  5257. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5258. */
  5259. static const tchar separator;
  5260. /** The system-specific file separator character, as a string.
  5261. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5262. */
  5263. static const tchar* separatorString;
  5264. /** Removes illegal characters from a filename.
  5265. This will return a copy of the given string after removing characters
  5266. that are not allowed in a legal filename, and possibly shortening the
  5267. string if it's too long.
  5268. Because this will remove slashes, don't use it on an absolute pathname.
  5269. @see createLegalPathName
  5270. */
  5271. static const String createLegalFileName (const String& fileNameToFix) throw();
  5272. /** Removes illegal characters from a pathname.
  5273. Similar to createLegalFileName(), but this won't remove slashes, so can
  5274. be used on a complete pathname.
  5275. @see createLegalFileName
  5276. */
  5277. static const String createLegalPathName (const String& pathNameToFix) throw();
  5278. /** Indicates whether filenames are case-sensitive on the current operating system.
  5279. */
  5280. static bool areFileNamesCaseSensitive();
  5281. /** Returns true if the string seems to be a fully-specified absolute path.
  5282. */
  5283. static bool isAbsolutePath (const String& path) throw();
  5284. juce_UseDebuggingNewOperator
  5285. private:
  5286. String fullPath;
  5287. // internal way of contructing a file without checking the path
  5288. friend class DirectoryIterator;
  5289. File (const String&, int) throw();
  5290. const String getPathUpToLastSlash() const throw();
  5291. };
  5292. #endif // __JUCE_FILE_JUCEHEADER__
  5293. /********* End of inlined file: juce_File.h *********/
  5294. /**
  5295. A simple implemenation of a Logger that writes to a file.
  5296. @see Logger
  5297. */
  5298. class JUCE_API FileLogger : public Logger
  5299. {
  5300. public:
  5301. /** Creates a FileLogger for a given file.
  5302. @param fileToWriteTo the file that to use - new messages will be appended
  5303. to the file. If the file doesn't exist, it will be created,
  5304. along with any parent directories that are needed.
  5305. @param welcomeMessage when opened, the logger will write a header to the log, along
  5306. with the current date and time, and this welcome message
  5307. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5308. but is larger than this number of bytes, then the start of the
  5309. file will be truncated to keep the size down. This prevents a log
  5310. file getting ridiculously large over time. The file will be truncated
  5311. at a new-line boundary. If this value is less than zero, no size limit
  5312. will be imposed; if it's zero, the file will always be deleted. Note that
  5313. the size is only checked once when this object is created - any logging
  5314. that is done later will be appended without any checking
  5315. */
  5316. FileLogger (const File& fileToWriteTo,
  5317. const String& welcomeMessage,
  5318. const int maxInitialFileSizeBytes = 128 * 1024);
  5319. /** Destructor. */
  5320. ~FileLogger();
  5321. void logMessage (const String& message);
  5322. /** Helper function to create a log file in the correct place for this platform.
  5323. On Windows this will return a logger with a path such as:
  5324. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5325. On the Mac it'll create something like:
  5326. ~/Library/Logs/[logFileName]
  5327. The method might return 0 if the file can't be created for some reason.
  5328. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5329. it's best to use the something like the name of your application here.
  5330. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5331. call it "log.txt" because if it goes in a directory with logs
  5332. from other applications (as it will do on the Mac) then no-one
  5333. will know which one is yours!
  5334. @param welcomeMessage a message that will be written to the log when it's opened.
  5335. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5336. */
  5337. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5338. const String& logFileName,
  5339. const String& welcomeMessage,
  5340. const int maxInitialFileSizeBytes = 128 * 1024);
  5341. juce_UseDebuggingNewOperator
  5342. private:
  5343. File logFile;
  5344. CriticalSection logLock;
  5345. FileOutputStream* logStream;
  5346. void trimFileSize (int maxFileSizeBytes) const;
  5347. FileLogger (const FileLogger&);
  5348. const FileLogger& operator= (const FileLogger&);
  5349. };
  5350. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5351. /********* End of inlined file: juce_FileLogger.h *********/
  5352. #endif
  5353. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5354. /********* Start of inlined file: juce_Initialisation.h *********/
  5355. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5356. #define __JUCE_INITIALISATION_JUCEHEADER__
  5357. /** Initialises Juce's GUI classes.
  5358. If you're embedding Juce into an application that uses its own event-loop rather
  5359. than using the START_JUCE_APPLICATION macro, call this function before making any
  5360. Juce calls, to make sure things are initialised correctly.
  5361. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5362. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5363. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5364. */
  5365. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5366. /** Clears up any static data being used by Juce's GUI classes.
  5367. If you're embedding Juce into an application that uses its own event-loop rather
  5368. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5369. code to clean up any juce objects that might be lying around.
  5370. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5371. */
  5372. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5373. /** Initialises the core parts of Juce.
  5374. If you're embedding Juce into either a command-line program, call this function
  5375. at the start of your main() function to make sure that Juce is initialised correctly.
  5376. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5377. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5378. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5379. */
  5380. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5381. /** Clears up any static data being used by Juce's non-gui core classes.
  5382. If you're embedding Juce into either a command-line program, call this function
  5383. at the end of your main() function if you want to make sure any Juce objects are
  5384. cleaned up correctly.
  5385. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5386. */
  5387. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5388. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5389. /********* End of inlined file: juce_Initialisation.h *********/
  5390. #endif
  5391. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5392. #endif
  5393. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  5394. #endif
  5395. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5396. #endif
  5397. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5398. #endif
  5399. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5400. /********* Start of inlined file: juce_Random.h *********/
  5401. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5402. #define __JUCE_RANDOM_JUCEHEADER__
  5403. /********* Start of inlined file: juce_BitArray.h *********/
  5404. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5405. #define __JUCE_BITARRAY_JUCEHEADER__
  5406. class MemoryBlock;
  5407. /**
  5408. An array of on/off bits, also usable to store large binary integers.
  5409. A BitArray acts like an arbitrarily large integer whose bits can be set or
  5410. cleared, and some basic mathematical operations can be done on the number as
  5411. a whole.
  5412. */
  5413. class JUCE_API BitArray
  5414. {
  5415. public:
  5416. /** Creates an empty BitArray */
  5417. BitArray() throw();
  5418. /** Creates a BitArray containing an integer value in its low bits.
  5419. The low 32 bits of the array are initialised with this value.
  5420. */
  5421. BitArray (const unsigned int value) throw();
  5422. /** Creates a BitArray containing an integer value in its low bits.
  5423. The low 32 bits of the array are initialised with the absolute value
  5424. passed in, and its sign is set to reflect the sign of the number.
  5425. */
  5426. BitArray (const int value) throw();
  5427. /** Creates a BitArray containing an integer value in its low bits.
  5428. The low 64 bits of the array are initialised with the absolute value
  5429. passed in, and its sign is set to reflect the sign of the number.
  5430. */
  5431. BitArray (int64 value) throw();
  5432. /** Creates a copy of another BitArray. */
  5433. BitArray (const BitArray& other) throw();
  5434. /** Destructor. */
  5435. ~BitArray() throw();
  5436. /** Copies another BitArray onto this one. */
  5437. const BitArray& operator= (const BitArray& other) throw();
  5438. /** Two arrays are the same if the same bits are set. */
  5439. bool operator== (const BitArray& other) const throw();
  5440. /** Two arrays are the same if the same bits are set. */
  5441. bool operator!= (const BitArray& other) const throw();
  5442. /** Clears all bits in the BitArray to 0. */
  5443. void clear() throw();
  5444. /** Clears a particular bit in the array. */
  5445. void clearBit (const int bitNumber) throw();
  5446. /** Sets a specified bit to 1.
  5447. If the bit number is high, this will grow the array to accomodate it.
  5448. */
  5449. void setBit (const int bitNumber) throw();
  5450. /** Sets or clears a specified bit. */
  5451. void setBit (const int bitNumber,
  5452. const bool shouldBeSet) throw();
  5453. /** Sets a range of bits to be either on or off.
  5454. @param startBit the first bit to change
  5455. @param numBits the number of bits to change
  5456. @param shouldBeSet whether to turn these bits on or off
  5457. */
  5458. void setRange (int startBit,
  5459. int numBits,
  5460. const bool shouldBeSet) throw();
  5461. /** Inserts a bit an a given position, shifting up any bits above it. */
  5462. void insertBit (const int bitNumber,
  5463. const bool shouldBeSet) throw();
  5464. /** Returns the value of a specified bit in the array.
  5465. If the index is out-of-range, the result will be false.
  5466. */
  5467. bool operator[] (const int bit) const throw();
  5468. /** Returns true if no bits are set. */
  5469. bool isEmpty() const throw();
  5470. /** Returns a range of bits in the array as a new BitArray.
  5471. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  5472. @see getBitRangeAsInt
  5473. */
  5474. const BitArray getBitRange (int startBit, int numBits) const throw();
  5475. /** Returns a range of bits in the array as an integer value.
  5476. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  5477. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  5478. getBitRange().
  5479. */
  5480. int getBitRangeAsInt (int startBit, int numBits) const throw();
  5481. /** Sets a range of bits in the array based on an integer value.
  5482. Copies the given integer into the array, starting at startBit,
  5483. and only using up to numBits of the available bits.
  5484. */
  5485. void setBitRangeAsInt (int startBit, int numBits,
  5486. unsigned int valueToSet) throw();
  5487. /** Performs a bitwise OR with another BitArray.
  5488. The result ends up in this array.
  5489. */
  5490. void orWith (const BitArray& other) throw();
  5491. /** Performs a bitwise AND with another BitArray.
  5492. The result ends up in this array.
  5493. */
  5494. void andWith (const BitArray& other) throw();
  5495. /** Performs a bitwise XOR with another BitArray.
  5496. The result ends up in this array.
  5497. */
  5498. void xorWith (const BitArray& other) throw();
  5499. /** Adds another BitArray's value to this one.
  5500. Treating the two arrays as large positive integers, this
  5501. adds them up and puts the result in this array.
  5502. */
  5503. void add (const BitArray& other) throw();
  5504. /** Subtracts another BitArray's value from this one.
  5505. Treating the two arrays as large positive integers, this
  5506. subtracts them and puts the result in this array.
  5507. Note that if the result should be negative, this won't be
  5508. handled correctly.
  5509. */
  5510. void subtract (const BitArray& other) throw();
  5511. /** Multiplies another BitArray's value with this one.
  5512. Treating the two arrays as large positive integers, this
  5513. multiplies them and puts the result in this array.
  5514. */
  5515. void multiplyBy (const BitArray& other) throw();
  5516. /** Divides another BitArray's value into this one and also produces a remainder.
  5517. Treating the two arrays as large positive integers, this
  5518. divides this value by the other, leaving the quotient in this
  5519. array, and the remainder is copied into the other BitArray passed in.
  5520. */
  5521. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  5522. /** Returns the largest value that will divide both this value and the one
  5523. passed-in.
  5524. */
  5525. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  5526. /** Performs a modulo operation on this value.
  5527. The result is stored in this value.
  5528. */
  5529. void modulo (const BitArray& divisor) throw();
  5530. /** Performs a combined exponent and modulo operation.
  5531. This BitArray's value becomes (this ^ exponent) % modulus.
  5532. */
  5533. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  5534. /** Performs an inverse modulo on the value.
  5535. i.e. the result is (this ^ -1) mod (modulus).
  5536. */
  5537. void inverseModulo (const BitArray& modulus) throw();
  5538. /** Shifts a section of bits left or right.
  5539. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  5540. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  5541. */
  5542. void shiftBits (int howManyBitsLeft,
  5543. int startBit = 0) throw();
  5544. /** Does a signed comparison of two BitArrays.
  5545. Return values are:
  5546. - 0 if the numbers are the same
  5547. - < 0 if this number is smaller than the other
  5548. - > 0 if this number is bigger than the other
  5549. */
  5550. int compare (const BitArray& other) const throw();
  5551. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  5552. Return values are:
  5553. - 0 if the numbers are the same
  5554. - < 0 if this number is smaller than the other
  5555. - > 0 if this number is bigger than the other
  5556. */
  5557. int compareAbsolute (const BitArray& other) const throw();
  5558. /** Returns true if the value is less than zero.
  5559. @see setNegative, negate
  5560. */
  5561. bool isNegative() const throw();
  5562. /** Changes the sign of the number to be positive or negative.
  5563. @see isNegative, negate
  5564. */
  5565. void setNegative (const bool shouldBeNegative) throw();
  5566. /** Inverts the sign of the number.
  5567. @see isNegative, setNegative
  5568. */
  5569. void negate() throw();
  5570. /** Counts the total number of set bits in the array. */
  5571. int countNumberOfSetBits() const throw();
  5572. /** Looks for the index of the next set bit after a given starting point.
  5573. searches from startIndex (inclusive) upwards for the first set bit,
  5574. and returns its index.
  5575. If no set bits are found, it returns -1.
  5576. */
  5577. int findNextSetBit (int startIndex = 0) const throw();
  5578. /** Looks for the index of the next clear bit after a given starting point.
  5579. searches from startIndex (inclusive) upwards for the first clear bit,
  5580. and returns its index.
  5581. */
  5582. int findNextClearBit (int startIndex = 0) const throw();
  5583. /** Returns the index of the highest set bit in the array.
  5584. If the array is empty, this will return -1.
  5585. */
  5586. int getHighestBit() const throw();
  5587. /** Converts the array to a number string.
  5588. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5589. If minuimumNumCharacters is greater than 0, the returned string will be
  5590. padded with leading zeros to reach at least that length.
  5591. */
  5592. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  5593. /** Converts a number string to an array.
  5594. Any non-valid characters will be ignored.
  5595. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5596. */
  5597. void parseString (const String& text,
  5598. const int base) throw();
  5599. /** Turns the array into a block of binary data.
  5600. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5601. of the array, and so on.
  5602. @see loadFromMemoryBlock
  5603. */
  5604. const MemoryBlock toMemoryBlock() const throw();
  5605. /** Copies a block of raw data onto this array.
  5606. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5607. of the array, and so on.
  5608. @see toMemoryBlock
  5609. */
  5610. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  5611. juce_UseDebuggingNewOperator
  5612. private:
  5613. void ensureSize (const int numVals) throw();
  5614. unsigned int* values;
  5615. int numValues, highestBit;
  5616. bool negative;
  5617. };
  5618. #endif // __JUCE_BITARRAY_JUCEHEADER__
  5619. /********* End of inlined file: juce_BitArray.h *********/
  5620. /**
  5621. A simple pseudo-random number generator.
  5622. */
  5623. class JUCE_API Random
  5624. {
  5625. public:
  5626. /** Creates a Random object based on a seed value.
  5627. For a given seed value, the subsequent numbers generated by this object
  5628. will be predictable, so a good idea is to set this value based
  5629. on the time, e.g.
  5630. new Random (Time::currentTimeMillis())
  5631. */
  5632. Random (const int64 seedValue) throw();
  5633. /** Destructor. */
  5634. ~Random() throw();
  5635. /** Returns the next random 32 bit integer.
  5636. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5637. */
  5638. int nextInt() throw();
  5639. /** Returns the next random number, limited to a given range.
  5640. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5641. */
  5642. int nextInt (const int maxValue) throw();
  5643. /** Returns the next 64-bit random number.
  5644. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5645. */
  5646. int64 nextInt64() throw();
  5647. /** Returns the next random floating-point number.
  5648. @returns a random value in the range 0 to 1.0
  5649. */
  5650. float nextFloat() throw();
  5651. /** Returns the next random floating-point number.
  5652. @returns a random value in the range 0 to 1.0
  5653. */
  5654. double nextDouble() throw();
  5655. /** Returns the next random boolean value.
  5656. */
  5657. bool nextBool() throw();
  5658. /** Returns a BitArray containing a random number.
  5659. @returns a random value in the range 0 to (maximumValue - 1).
  5660. */
  5661. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  5662. /** Sets a range of bits in a BitArray to random values. */
  5663. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  5664. /** To avoid the overhead of having to create a new Random object whenever
  5665. you need a number, this is a shared application-wide object that
  5666. can be used.
  5667. It's not thread-safe though, so threads should use their own Random object.
  5668. */
  5669. static Random& getSystemRandom() throw();
  5670. /** Resets this Random object to a given seed value. */
  5671. void setSeed (const int64 newSeed) throw();
  5672. /** Reseeds this generator using a value generated from various semi-random system
  5673. properties like the current time, etc.
  5674. Because this function convolves the time with the last seed value, calling
  5675. it repeatedly will increase the randomness of the final result.
  5676. */
  5677. void setSeedRandomly();
  5678. juce_UseDebuggingNewOperator
  5679. private:
  5680. int64 seed;
  5681. };
  5682. #endif // __JUCE_RANDOM_JUCEHEADER__
  5683. /********* End of inlined file: juce_Random.h *********/
  5684. #endif
  5685. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5686. #endif
  5687. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5688. /********* Start of inlined file: juce_Singleton.h *********/
  5689. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5690. #define __JUCE_SINGLETON_JUCEHEADER__
  5691. /********* Start of inlined file: juce_ScopedLock.h *********/
  5692. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5693. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5694. /**
  5695. Automatically locks and unlocks a CriticalSection object.
  5696. Use one of these as a local variable to control access to a CriticalSection.
  5697. e.g. @code
  5698. CriticalSection myCriticalSection;
  5699. for (;;)
  5700. {
  5701. const ScopedLock myScopedLock (myCriticalSection);
  5702. // myCriticalSection is now locked
  5703. ...do some stuff...
  5704. // myCriticalSection gets unlocked here.
  5705. }
  5706. @endcode
  5707. @see CriticalSection, ScopedUnlock
  5708. */
  5709. class JUCE_API ScopedLock
  5710. {
  5711. public:
  5712. /** Creates a ScopedLock.
  5713. As soon as it is created, this will lock the CriticalSection, and
  5714. when the ScopedLock object is deleted, the CriticalSection will
  5715. be unlocked.
  5716. Make sure this object is created and deleted by the same thread,
  5717. otherwise there are no guarantees what will happen! Best just to use it
  5718. as a local stack object, rather than creating one with the new() operator.
  5719. */
  5720. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5721. /** Destructor.
  5722. The CriticalSection will be unlocked when the destructor is called.
  5723. Make sure this object is created and deleted by the same thread,
  5724. otherwise there are no guarantees what will happen!
  5725. */
  5726. inline ~ScopedLock() throw() { lock_.exit(); }
  5727. private:
  5728. const CriticalSection& lock_;
  5729. ScopedLock (const ScopedLock&);
  5730. const ScopedLock& operator= (const ScopedLock&);
  5731. };
  5732. /**
  5733. Automatically unlocks and re-locks a CriticalSection object.
  5734. This is the reverse of a ScopedLock object - instead of locking the critical
  5735. section for the lifetime of this object, it unlocks it.
  5736. Make sure you don't try to unlock critical sections that aren't actually locked!
  5737. e.g. @code
  5738. CriticalSection myCriticalSection;
  5739. for (;;)
  5740. {
  5741. const ScopedLock myScopedLock (myCriticalSection);
  5742. // myCriticalSection is now locked
  5743. ... do some stuff with it locked ..
  5744. while (xyz)
  5745. {
  5746. ... do some stuff with it locked ..
  5747. const ScopedUnlock unlocker (myCriticalSection);
  5748. // myCriticalSection is now unlocked for the remainder of this block,
  5749. // and re-locked at the end.
  5750. ...do some stuff with it unlocked ...
  5751. }
  5752. // myCriticalSection gets unlocked here.
  5753. }
  5754. @endcode
  5755. @see CriticalSection, ScopedLock
  5756. */
  5757. class ScopedUnlock
  5758. {
  5759. public:
  5760. /** Creates a ScopedUnlock.
  5761. As soon as it is created, this will unlock the CriticalSection, and
  5762. when the ScopedLock object is deleted, the CriticalSection will
  5763. be re-locked.
  5764. Make sure this object is created and deleted by the same thread,
  5765. otherwise there are no guarantees what will happen! Best just to use it
  5766. as a local stack object, rather than creating one with the new() operator.
  5767. */
  5768. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5769. /** Destructor.
  5770. The CriticalSection will be unlocked when the destructor is called.
  5771. Make sure this object is created and deleted by the same thread,
  5772. otherwise there are no guarantees what will happen!
  5773. */
  5774. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5775. private:
  5776. const CriticalSection& lock_;
  5777. ScopedUnlock (const ScopedLock&);
  5778. const ScopedUnlock& operator= (const ScopedUnlock&);
  5779. };
  5780. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5781. /********* End of inlined file: juce_ScopedLock.h *********/
  5782. /**
  5783. Macro to declare member variables and methods for a singleton class.
  5784. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  5785. to the class's definition.
  5786. If allowOnlyOneInstance == true, it won't allow the object to be created
  5787. more than once in the process's lifetime.
  5788. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5789. implementation code.
  5790. Clients can then call the static MyClass::getInstance() to get a pointer to the
  5791. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  5792. is currently extant
  5793. it's a very good idea to also add the call clearSingletonInstance() to the
  5794. destructor of the class, in case it is deleted by other means than deleteInstance()
  5795. e.g. @code
  5796. class MySingleton
  5797. {
  5798. public:
  5799. MySingleton()
  5800. {
  5801. }
  5802. ~MySingleton()
  5803. {
  5804. // this ensures that no dangling pointers are left when the
  5805. // singleton is deleted.
  5806. clearSingletonInstance();
  5807. }
  5808. juce_DeclareSingleton (MySingleton, false)
  5809. };
  5810. juce_ImplementSingleton (MySingleton)
  5811. // example of usage:
  5812. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5813. ...
  5814. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5815. @endcode
  5816. If you know that your object will only be created and deleted by a single thread, you
  5817. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5818. of this one.
  5819. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5820. */
  5821. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  5822. \
  5823. static classname* _singletonInstance; \
  5824. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5825. \
  5826. static classname* getInstance() \
  5827. { \
  5828. if (_singletonInstance == 0) \
  5829. {\
  5830. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5831. \
  5832. if (_singletonInstance == 0) \
  5833. { \
  5834. static bool alreadyInside = false; \
  5835. static bool createdOnceAlready = false; \
  5836. \
  5837. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5838. jassert (! problem); \
  5839. if (! problem) \
  5840. { \
  5841. createdOnceAlready = true; \
  5842. alreadyInside = true; \
  5843. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5844. alreadyInside = false; \
  5845. \
  5846. _singletonInstance = newObject; \
  5847. } \
  5848. } \
  5849. } \
  5850. \
  5851. return _singletonInstance; \
  5852. } \
  5853. \
  5854. static inline classname* getInstanceWithoutCreating() throw() \
  5855. { \
  5856. return _singletonInstance; \
  5857. } \
  5858. \
  5859. static void deleteInstance() \
  5860. { \
  5861. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5862. if (_singletonInstance != 0) \
  5863. { \
  5864. classname* const old = _singletonInstance; \
  5865. _singletonInstance = 0; \
  5866. delete old; \
  5867. } \
  5868. } \
  5869. \
  5870. void clearSingletonInstance() throw() \
  5871. { \
  5872. if (_singletonInstance == this) \
  5873. _singletonInstance = 0; \
  5874. }
  5875. /** This is a counterpart to the juce_DeclareSingleton macro.
  5876. After adding the juce_DeclareSingleton to the class definition, this macro has
  5877. to be used in the cpp file.
  5878. */
  5879. #define juce_ImplementSingleton(classname) \
  5880. \
  5881. classname* classname::_singletonInstance = 0; \
  5882. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5883. /**
  5884. Macro to declare member variables and methods for a singleton class.
  5885. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5886. section to make access to it thread-safe. If you know that your object will
  5887. only ever be created or deleted by a single thread, then this is a
  5888. more efficient version to use.
  5889. See the documentation for juce_DeclareSingleton for more information about
  5890. how to use it, the only difference being that you have to use
  5891. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5892. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5893. */
  5894. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  5895. \
  5896. static classname* _singletonInstance; \
  5897. \
  5898. static classname* getInstance() \
  5899. { \
  5900. if (_singletonInstance == 0) \
  5901. { \
  5902. static bool alreadyInside = false; \
  5903. static bool createdOnceAlready = false; \
  5904. \
  5905. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5906. jassert (! problem); \
  5907. if (! problem) \
  5908. { \
  5909. createdOnceAlready = true; \
  5910. alreadyInside = true; \
  5911. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5912. alreadyInside = false; \
  5913. \
  5914. _singletonInstance = newObject; \
  5915. } \
  5916. } \
  5917. \
  5918. return _singletonInstance; \
  5919. } \
  5920. \
  5921. static inline classname* getInstanceWithoutCreating() throw() \
  5922. { \
  5923. return _singletonInstance; \
  5924. } \
  5925. \
  5926. static void deleteInstance() \
  5927. { \
  5928. if (_singletonInstance != 0) \
  5929. { \
  5930. classname* const old = _singletonInstance; \
  5931. _singletonInstance = 0; \
  5932. delete old; \
  5933. } \
  5934. } \
  5935. \
  5936. void clearSingletonInstance() throw() \
  5937. { \
  5938. if (_singletonInstance == this) \
  5939. _singletonInstance = 0; \
  5940. }
  5941. /**
  5942. Macro to declare member variables and methods for a singleton class.
  5943. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5944. for recursion or repeated instantiation. It's intended for use as a lightweight
  5945. version of a singleton, where you're using it in very straightforward
  5946. circumstances and don't need the extra checking.
  5947. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  5948. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  5949. See the documentation for juce_DeclareSingleton for more information about
  5950. how to use it, the only difference being that you have to use
  5951. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5952. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  5953. */
  5954. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  5955. \
  5956. static classname* _singletonInstance; \
  5957. \
  5958. static classname* getInstance() \
  5959. { \
  5960. if (_singletonInstance == 0) \
  5961. _singletonInstance = new classname(); \
  5962. \
  5963. return _singletonInstance; \
  5964. } \
  5965. \
  5966. static inline classname* getInstanceWithoutCreating() throw() \
  5967. { \
  5968. return _singletonInstance; \
  5969. } \
  5970. \
  5971. static void deleteInstance() \
  5972. { \
  5973. if (_singletonInstance != 0) \
  5974. { \
  5975. classname* const old = _singletonInstance; \
  5976. _singletonInstance = 0; \
  5977. delete old; \
  5978. } \
  5979. } \
  5980. \
  5981. void clearSingletonInstance() throw() \
  5982. { \
  5983. if (_singletonInstance == this) \
  5984. _singletonInstance = 0; \
  5985. }
  5986. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  5987. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  5988. to the class definition, this macro has to be used somewhere in the cpp file.
  5989. */
  5990. #define juce_ImplementSingleton_SingleThreaded(classname) \
  5991. \
  5992. classname* classname::_singletonInstance = 0;
  5993. #endif // __JUCE_SINGLETON_JUCEHEADER__
  5994. /********* End of inlined file: juce_Singleton.h *********/
  5995. #endif
  5996. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  5997. #endif
  5998. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5999. /********* Start of inlined file: juce_SystemStats.h *********/
  6000. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6001. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  6002. /**
  6003. Contains methods for finding out about the current hardware and OS configuration.
  6004. */
  6005. class JUCE_API SystemStats
  6006. {
  6007. public:
  6008. /** Returns the current version of JUCE,
  6009. (just in case you didn't already know at compile-time.)
  6010. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  6011. */
  6012. static const String getJUCEVersion() throw();
  6013. /** The set of possible results of the getOperatingSystemType() method.
  6014. */
  6015. enum OperatingSystemType
  6016. {
  6017. UnknownOS = 0,
  6018. MacOSX = 0x1000,
  6019. Linux = 0x2000,
  6020. Win95 = 0x4001,
  6021. Win98 = 0x4002,
  6022. WinNT351 = 0x4103,
  6023. WinNT40 = 0x4104,
  6024. Win2000 = 0x4105,
  6025. WinXP = 0x4106,
  6026. WinVista = 0x4107,
  6027. Windows = 0x4000, /**< To test whether any version of Windows is running,
  6028. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  6029. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  6030. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  6031. };
  6032. /** Returns the type of operating system we're running on.
  6033. @returns one of the values from the OperatingSystemType enum.
  6034. @see getOperatingSystemName
  6035. */
  6036. static OperatingSystemType getOperatingSystemType() throw();
  6037. /** Returns the name of the type of operating system we're running on.
  6038. @returns a string describing the OS type.
  6039. @see getOperatingSystemType
  6040. */
  6041. static const String getOperatingSystemName() throw();
  6042. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  6043. */
  6044. static bool isOperatingSystem64Bit() throw();
  6045. // CPU and memory information..
  6046. /** Returns the approximate CPU speed.
  6047. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6048. what year you're reading this...)
  6049. */
  6050. static int getCpuSpeedInMegaherz() throw();
  6051. /** Returns a string to indicate the CPU vendor.
  6052. Might not be known on some systems.
  6053. */
  6054. static const String getCpuVendor() throw();
  6055. /** Checks whether Intel MMX instructions are available. */
  6056. static bool hasMMX() throw();
  6057. /** Checks whether Intel SSE instructions are available. */
  6058. static bool hasSSE() throw();
  6059. /** Checks whether Intel SSE2 instructions are available. */
  6060. static bool hasSSE2() throw();
  6061. /** Checks whether AMD 3DNOW instructions are available. */
  6062. static bool has3DNow() throw();
  6063. /** Returns the number of CPUs.
  6064. */
  6065. static int getNumCpus() throw();
  6066. /** Returns a clock-cycle tick counter, if available.
  6067. If the machine can do it, this will return a tick-count
  6068. where each tick is one cpu clock cycle - used for profiling
  6069. code.
  6070. @returns the tick count, or zero if not available.
  6071. */
  6072. static int64 getClockCycleCounter() throw();
  6073. /** Finds out how much RAM is in the machine.
  6074. @returns the approximate number of megabytes of memory, or zero if
  6075. something goes wrong when finding out.
  6076. */
  6077. static int getMemorySizeInMegabytes() throw();
  6078. /** Returns the system page-size.
  6079. This is only used by programmers with beards.
  6080. */
  6081. static int getPageSize() throw();
  6082. /** Returns a list of MAC addresses found on this machine.
  6083. @param addresses an array into which the MAC addresses should be copied
  6084. @param maxNum the number of elements in this array
  6085. @param littleEndian the endianness of the numbers to return. Note that
  6086. the default values of this parameter are different on
  6087. Mac/PC to avoid breaking old software that was written
  6088. before this parameter was added (when the two systems
  6089. defaulted to using different endiannesses). In newer
  6090. software you probably want to specify an explicit value
  6091. for this.
  6092. @returns the number of MAC addresses that were found
  6093. */
  6094. static int getMACAddresses (int64* addresses, int maxNum,
  6095. #if JUCE_MAC
  6096. const bool littleEndian = true) throw();
  6097. #else
  6098. const bool littleEndian = false) throw();
  6099. #endif
  6100. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6101. static void initialiseStats() throw();
  6102. };
  6103. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6104. /********* End of inlined file: juce_SystemStats.h *********/
  6105. #endif
  6106. #ifndef __JUCE_TIME_JUCEHEADER__
  6107. #endif
  6108. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6109. #endif
  6110. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6111. #endif
  6112. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6113. #endif
  6114. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6115. #endif
  6116. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6117. #endif
  6118. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6119. #endif
  6120. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6121. /********* Start of inlined file: juce_PropertySet.h *********/
  6122. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6123. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6124. /********* Start of inlined file: juce_StringPairArray.h *********/
  6125. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6126. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6127. /**
  6128. A container for holding a set of strings which are keyed by another string.
  6129. @see StringArray
  6130. */
  6131. class JUCE_API StringPairArray
  6132. {
  6133. public:
  6134. /** Creates an empty array */
  6135. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6136. /** Creates a copy of another array */
  6137. StringPairArray (const StringPairArray& other) throw();
  6138. /** Destructor. */
  6139. ~StringPairArray() throw();
  6140. /** Copies the contents of another string array into this one */
  6141. const StringPairArray& operator= (const StringPairArray& other) throw();
  6142. /** Compares two arrays.
  6143. Comparisons are case-sensitive.
  6144. @returns true only if the other array contains exactly the same strings with the same keys
  6145. */
  6146. bool operator== (const StringPairArray& other) const throw();
  6147. /** Compares two arrays.
  6148. Comparisons are case-sensitive.
  6149. @returns false if the other array contains exactly the same strings with the same keys
  6150. */
  6151. bool operator!= (const StringPairArray& other) const throw();
  6152. /** Finds the value corresponding to a key string.
  6153. If no such key is found, this will just return an empty string. To check whether
  6154. a given key actually exists (because it might actually be paired with an empty string), use
  6155. the getAllKeys() method to obtain a list.
  6156. Obviously the reference returned shouldn't be stored for later use, as the
  6157. string it refers to may disappear when the array changes.
  6158. @see getValue
  6159. */
  6160. const String& operator[] (const String& key) const throw();
  6161. /** Finds the value corresponding to a key string.
  6162. If no such key is found, this will just return the value provided as a default.
  6163. @see operator[]
  6164. */
  6165. const String getValue (const String& key, const String& defaultReturnValue) const;
  6166. /** Returns a list of all keys in the array. */
  6167. const StringArray& getAllKeys() const throw() { return keys; }
  6168. /** Returns a list of all values in the array. */
  6169. const StringArray& getAllValues() const throw() { return values; }
  6170. /** Returns the number of strings in the array */
  6171. inline int size() const throw() { return keys.size(); };
  6172. /** Adds or amends a key/value pair.
  6173. If a value already exists with this key, its value will be overwritten,
  6174. otherwise the key/value pair will be added to the array.
  6175. */
  6176. void set (const String& key,
  6177. const String& value) throw();
  6178. /** Adds the items from another array to this one.
  6179. This is equivalent to using set() to add each of the pairs from the other array.
  6180. */
  6181. void addArray (const StringPairArray& other);
  6182. /** Removes all elements from the array. */
  6183. void clear() throw();
  6184. /** Removes a string from the array based on its key.
  6185. If the key isn't found, nothing will happen.
  6186. */
  6187. void remove (const String& key) throw();
  6188. /** Removes a string from the array based on its index.
  6189. If the index is out-of-range, no action will be taken.
  6190. */
  6191. void remove (const int index) throw();
  6192. /** Indicates whether to use a case-insensitive search when looking up a key string.
  6193. */
  6194. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  6195. /** Returns a descriptive string containing the items.
  6196. This is handy for dumping the contents of an array.
  6197. */
  6198. const String getDescription() const;
  6199. /** Reduces the amount of storage being used by the array.
  6200. Arrays typically allocate slightly more storage than they need, and after
  6201. removing elements, they may have quite a lot of unused space allocated.
  6202. This method will reduce the amount of allocated storage to a minimum.
  6203. */
  6204. void minimiseStorageOverheads() throw();
  6205. juce_UseDebuggingNewOperator
  6206. private:
  6207. StringArray keys, values;
  6208. bool ignoreCase;
  6209. };
  6210. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6211. /********* End of inlined file: juce_StringPairArray.h *********/
  6212. /********* Start of inlined file: juce_XmlElement.h *********/
  6213. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6214. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6215. /********* Start of inlined file: juce_OutputStream.h *********/
  6216. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6217. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6218. /********* Start of inlined file: juce_InputStream.h *********/
  6219. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6220. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6221. /** The base class for streams that read data.
  6222. Input and output streams are used throughout the library - subclasses can override
  6223. some or all of the virtual functions to implement their behaviour.
  6224. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6225. */
  6226. class JUCE_API InputStream
  6227. {
  6228. public:
  6229. /** Destructor. */
  6230. virtual ~InputStream() {}
  6231. /** Returns the total number of bytes available for reading in this stream.
  6232. Note that this is the number of bytes available from the start of the
  6233. stream, not from the current position.
  6234. If the size of the stream isn't actually known, this may return -1.
  6235. */
  6236. virtual int64 getTotalLength() = 0;
  6237. /** Returns true if the stream has no more data to read. */
  6238. virtual bool isExhausted() = 0;
  6239. /** Reads a set of bytes from the stream into a memory buffer.
  6240. This is the only read method that subclasses actually need to implement, as the
  6241. InputStream base class implements the other read methods in terms of this one (although
  6242. it's often more efficient for subclasses to implement them directly).
  6243. @param destBuffer the destination buffer for the data
  6244. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6245. memory block passed in is big enough to contain this
  6246. many bytes.
  6247. @returns the actual number of bytes that were read, which may be less than
  6248. maxBytesToRead if the stream is exhausted before it gets that far
  6249. */
  6250. virtual int read (void* destBuffer,
  6251. int maxBytesToRead) = 0;
  6252. /** Reads a byte from the stream.
  6253. If the stream is exhausted, this will return zero.
  6254. @see OutputStream::writeByte
  6255. */
  6256. virtual char readByte();
  6257. /** Reads a boolean from the stream.
  6258. The bool is encoded as a single byte - 1 for true, 0 for false.
  6259. If the stream is exhausted, this will return false.
  6260. @see OutputStream::writeBool
  6261. */
  6262. virtual bool readBool();
  6263. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6264. If the next two bytes read are byte1 and byte2, this returns
  6265. (byte1 | (byte2 << 8)).
  6266. If the stream is exhausted partway through reading the bytes, this will return zero.
  6267. @see OutputStream::writeShort, readShortBigEndian
  6268. */
  6269. virtual short readShort();
  6270. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6271. If the next two bytes read are byte1 and byte2, this returns
  6272. (byte2 | (byte1 << 8)).
  6273. If the stream is exhausted partway through reading the bytes, this will return zero.
  6274. @see OutputStream::writeShortBigEndian, readShort
  6275. */
  6276. virtual short readShortBigEndian();
  6277. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6278. If the next four bytes are byte1 to byte4, this returns
  6279. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6280. If the stream is exhausted partway through reading the bytes, this will return zero.
  6281. @see OutputStream::writeInt, readIntBigEndian
  6282. */
  6283. virtual int readInt();
  6284. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6285. If the next four bytes are byte1 to byte4, this returns
  6286. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6287. If the stream is exhausted partway through reading the bytes, this will return zero.
  6288. @see OutputStream::writeIntBigEndian, readInt
  6289. */
  6290. virtual int readIntBigEndian();
  6291. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6292. If the next eight bytes are byte1 to byte8, this returns
  6293. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6294. If the stream is exhausted partway through reading the bytes, this will return zero.
  6295. @see OutputStream::writeInt64, readInt64BigEndian
  6296. */
  6297. virtual int64 readInt64();
  6298. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6299. If the next eight bytes are byte1 to byte8, this returns
  6300. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6301. If the stream is exhausted partway through reading the bytes, this will return zero.
  6302. @see OutputStream::writeInt64BigEndian, readInt64
  6303. */
  6304. virtual int64 readInt64BigEndian();
  6305. /** Reads four bytes as a 32-bit floating point value.
  6306. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6307. If the stream is exhausted partway through reading the bytes, this will return zero.
  6308. @see OutputStream::writeFloat, readDouble
  6309. */
  6310. virtual float readFloat();
  6311. /** Reads four bytes as a 32-bit floating point value.
  6312. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6313. If the stream is exhausted partway through reading the bytes, this will return zero.
  6314. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6315. */
  6316. virtual float readFloatBigEndian();
  6317. /** Reads eight bytes as a 64-bit floating point value.
  6318. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6319. If the stream is exhausted partway through reading the bytes, this will return zero.
  6320. @see OutputStream::writeDouble, readFloat
  6321. */
  6322. virtual double readDouble();
  6323. /** Reads eight bytes as a 64-bit floating point value.
  6324. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6325. If the stream is exhausted partway through reading the bytes, this will return zero.
  6326. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6327. */
  6328. virtual double readDoubleBigEndian();
  6329. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6330. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6331. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6332. @see OutputStream::writeCompressedInt()
  6333. */
  6334. virtual int readCompressedInt();
  6335. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6336. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6337. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6338. After this call, the stream's position will be left pointing to the character
  6339. following the line-feed, but the linefeeds aren't included in the string that
  6340. is returned.
  6341. */
  6342. virtual const String readNextLine();
  6343. /** Reads a zero-terminated string from the stream.
  6344. This will read characters from the stream until it hits a zero character or
  6345. end-of-stream.
  6346. @see OutputStream::writeString, readEntireStreamAsString
  6347. */
  6348. virtual const String readString();
  6349. /** Tries to read the whole stream and turn it into a string.
  6350. This will read from the stream's current position until the end-of-stream, and
  6351. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6352. */
  6353. virtual const String readEntireStreamAsString();
  6354. /** Reads from the stream and appends the data to a MemoryBlock.
  6355. @param destBlock the block to append the data onto
  6356. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6357. of bytes that will be read - if it's negative, data
  6358. will be read until the stream is exhausted.
  6359. @returns the number of bytes that were added to the memory block
  6360. */
  6361. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6362. int maxNumBytesToRead = -1);
  6363. /** Returns the offset of the next byte that will be read from the stream.
  6364. @see setPosition
  6365. */
  6366. virtual int64 getPosition() = 0;
  6367. /** Tries to move the current read position of the stream.
  6368. The position is an absolute number of bytes from the stream's start.
  6369. Some streams might not be able to do this, in which case they should do
  6370. nothing and return false. Others might be able to manage it by resetting
  6371. themselves and skipping to the correct position, although this is
  6372. obviously a bit slow.
  6373. @returns true if the stream manages to reposition itself correctly
  6374. @see getPosition
  6375. */
  6376. virtual bool setPosition (int64 newPosition) = 0;
  6377. /** Reads and discards a number of bytes from the stream.
  6378. Some input streams might implement this efficiently, but the base
  6379. class will just keep reading data until the requisite number of bytes
  6380. have been done.
  6381. */
  6382. virtual void skipNextBytes (int64 numBytesToSkip);
  6383. juce_UseDebuggingNewOperator
  6384. protected:
  6385. InputStream() throw() {}
  6386. };
  6387. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6388. /********* End of inlined file: juce_InputStream.h *********/
  6389. /**
  6390. The base class for streams that write data to some kind of destination.
  6391. Input and output streams are used throughout the library - subclasses can override
  6392. some or all of the virtual functions to implement their behaviour.
  6393. @see InputStream, MemoryOutputStream, FileOutputStream
  6394. */
  6395. class JUCE_API OutputStream
  6396. {
  6397. public:
  6398. /** Destructor.
  6399. Some subclasses might want to do things like call flush() during their
  6400. destructors.
  6401. */
  6402. virtual ~OutputStream();
  6403. /** If the stream is using a buffer, this will ensure it gets written
  6404. out to the destination. */
  6405. virtual void flush() = 0;
  6406. /** Tries to move the stream's output position.
  6407. Not all streams will be able to seek to a new position - this will return
  6408. false if it fails to work.
  6409. @see getPosition
  6410. */
  6411. virtual bool setPosition (int64 newPosition) = 0;
  6412. /** Returns the stream's current position.
  6413. @see setPosition
  6414. */
  6415. virtual int64 getPosition() = 0;
  6416. /** Writes a block of data to the stream.
  6417. When creating a subclass of OutputStream, this is the only write method
  6418. that needs to be overloaded - the base class has methods for writing other
  6419. types of data which use this to do the work.
  6420. @returns false if the write operation fails for some reason
  6421. */
  6422. virtual bool write (const void* dataToWrite,
  6423. int howManyBytes) = 0;
  6424. /** Writes a single byte to the stream.
  6425. @see InputStream::readByte
  6426. */
  6427. virtual void writeByte (char byte);
  6428. /** Writes a boolean to the stream.
  6429. This is encoded as a byte - either 1 or 0.
  6430. @see InputStream::readBool
  6431. */
  6432. virtual void writeBool (bool boolValue);
  6433. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6434. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6435. @see InputStream::readShort
  6436. */
  6437. virtual void writeShort (short value);
  6438. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6439. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6440. @see InputStream::readShortBigEndian
  6441. */
  6442. virtual void writeShortBigEndian (short value);
  6443. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6444. @see InputStream::readInt
  6445. */
  6446. virtual void writeInt (int value);
  6447. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6448. @see InputStream::readIntBigEndian
  6449. */
  6450. virtual void writeIntBigEndian (int value);
  6451. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6452. @see InputStream::readInt64
  6453. */
  6454. virtual void writeInt64 (int64 value);
  6455. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6456. @see InputStream::readInt64BigEndian
  6457. */
  6458. virtual void writeInt64BigEndian (int64 value);
  6459. /** Writes a 32-bit floating point value to the stream.
  6460. The binary 32-bit encoding of the float is written as a little-endian int.
  6461. @see InputStream::readFloat
  6462. */
  6463. virtual void writeFloat (float value);
  6464. /** Writes a 32-bit floating point value to the stream.
  6465. The binary 32-bit encoding of the float is written as a big-endian int.
  6466. @see InputStream::readFloatBigEndian
  6467. */
  6468. virtual void writeFloatBigEndian (float value);
  6469. /** Writes a 64-bit floating point value to the stream.
  6470. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6471. @see InputStream::readDouble
  6472. */
  6473. virtual void writeDouble (double value);
  6474. /** Writes a 64-bit floating point value to the stream.
  6475. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6476. @see InputStream::readDoubleBigEndian
  6477. */
  6478. virtual void writeDoubleBigEndian (double value);
  6479. /** Writes a condensed encoding of a 32-bit integer.
  6480. If you're storing a lot of integers which are unlikely to have very large values,
  6481. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6482. under 0xffff only 3 bytes, etc.
  6483. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6484. @see InputStream::readCompressedInt
  6485. */
  6486. virtual void writeCompressedInt (int value);
  6487. /** Stores a string in the stream.
  6488. This isn't the method to use if you're trying to append text to the end of a
  6489. text-file! It's intended for storing a string for later retrieval
  6490. by InputStream::readString.
  6491. For appending text to a file, instead use writeText, printf, or operator<<
  6492. @see InputStream::readString, writeText, printf, operator<<
  6493. */
  6494. virtual void writeString (const String& text);
  6495. /** Writes a string of text to the stream.
  6496. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6497. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6498. should only be done at the start of a file).
  6499. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6500. */
  6501. virtual void writeText (const String& text,
  6502. const bool asUnicode,
  6503. const bool writeUnicodeHeaderBytes);
  6504. /** Writes a string of text to the stream.
  6505. @see writeText
  6506. */
  6507. virtual void printf (const char* format, ...);
  6508. /** Reads data from an input stream and writes it to this stream.
  6509. @param source the stream to read from
  6510. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6511. less than zero, it will keep reading until the input
  6512. is exhausted)
  6513. */
  6514. virtual int writeFromInputStream (InputStream& source,
  6515. int maxNumBytesToWrite);
  6516. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6517. virtual OutputStream& operator<< (const int number);
  6518. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6519. virtual OutputStream& operator<< (const double number);
  6520. /** Writes a character to the stream. */
  6521. virtual OutputStream& operator<< (const char character);
  6522. /** Writes a null-terminated string to the stream. */
  6523. virtual OutputStream& operator<< (const char* const text);
  6524. /** Writes a null-terminated unicode text string to the stream, converting it
  6525. to 8-bit characters in the default system encoding. */
  6526. virtual OutputStream& operator<< (const juce_wchar* const text);
  6527. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6528. virtual OutputStream& operator<< (const String& text);
  6529. juce_UseDebuggingNewOperator
  6530. protected:
  6531. OutputStream() throw();
  6532. };
  6533. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6534. /********* End of inlined file: juce_OutputStream.h *********/
  6535. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6536. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6537. will be the name of a pointer to each child element.
  6538. E.g. @code
  6539. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6540. forEachXmlChildElement (*myParentXml, child)
  6541. {
  6542. if (child->hasTagName ("FOO"))
  6543. doSomethingWithXmlElement (child);
  6544. }
  6545. @endcode
  6546. @see forEachXmlChildElementWithTagName
  6547. */
  6548. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6549. \
  6550. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6551. childElementVariableName != 0; \
  6552. childElementVariableName = childElementVariableName->getNextElement())
  6553. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6554. which have a specified tag.
  6555. This does the same job as the forEachXmlChildElement macro, but only for those
  6556. elements that have a particular tag name.
  6557. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6558. will be the name of a pointer to each child element. The requiredTagName is the
  6559. tag name to match.
  6560. E.g. @code
  6561. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6562. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6563. {
  6564. // the child object is now guaranteed to be a <MYTAG> element..
  6565. doSomethingWithMYTAGElement (child);
  6566. }
  6567. @endcode
  6568. @see forEachXmlChildElement
  6569. */
  6570. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6571. \
  6572. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6573. childElementVariableName != 0; \
  6574. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6575. /** Used to build a tree of elements representing an XML document.
  6576. An XML document can be parsed into a tree of XmlElements, each of which
  6577. represents an XML tag structure, and which may itself contain other
  6578. nested elements.
  6579. An XmlElement can also be converted back into a text document, and has
  6580. lots of useful methods for manipulating its attributes and sub-elements,
  6581. so XmlElements can actually be used as a handy general-purpose data
  6582. structure.
  6583. Here's an example of parsing some elements: @code
  6584. // check we're looking at the right kind of document..
  6585. if (myElement->hasTagName ("ANIMALS"))
  6586. {
  6587. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6588. forEachXmlChildElement (*myElement, e)
  6589. {
  6590. if (e->hasTagName ("GIRAFFE"))
  6591. {
  6592. // found a giraffe, so use some of its attributes..
  6593. String giraffeName = e->getStringAttribute ("name");
  6594. int giraffeAge = e->getIntAttribute ("age");
  6595. bool isFriendly = e->getBoolAttribute ("friendly");
  6596. }
  6597. }
  6598. }
  6599. @endcode
  6600. And here's an example of how to create an XML document from scratch: @code
  6601. // create an outer node called "ANIMALS"
  6602. XmlElement animalsList ("ANIMALS");
  6603. for (int i = 0; i < numAnimals; ++i)
  6604. {
  6605. // create an inner element..
  6606. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6607. giraffe->setAttribute ("name", "nigel");
  6608. giraffe->setAttribute ("age", 10);
  6609. giraffe->setAttribute ("friendly", true);
  6610. // ..and add our new element to the parent node
  6611. animalsList.addChildElement (giraffe);
  6612. }
  6613. // now we can turn the whole thing into a text document..
  6614. String myXmlDoc = animalsList.createDocument (String::empty);
  6615. @endcode
  6616. @see XmlDocument
  6617. */
  6618. class JUCE_API XmlElement
  6619. {
  6620. public:
  6621. /** Creates an XmlElement with this tag name. */
  6622. XmlElement (const String& tagName) throw();
  6623. /** Creates a (deep) copy of another element. */
  6624. XmlElement (const XmlElement& other) throw();
  6625. /** Creates a (deep) copy of another element. */
  6626. const XmlElement& operator= (const XmlElement& other) throw();
  6627. /** Deleting an XmlElement will also delete all its child elements. */
  6628. ~XmlElement() throw();
  6629. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6630. The elements are only considered equivalent if they contain the same attiributes
  6631. with the same values, and have the same sub-nodes.
  6632. @param other the other element to compare to
  6633. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6634. same attributes in a different order will be
  6635. considered the same; if false, the attributes must
  6636. be in the same order as well
  6637. */
  6638. bool isEquivalentTo (const XmlElement* const other,
  6639. const bool ignoreOrderOfAttributes) const throw();
  6640. /** Returns an XML text document that represents this element.
  6641. The string returned can be parsed to recreate the same XmlElement that
  6642. was used to create it.
  6643. @param dtdToUse the DTD to add to the document
  6644. @param allOnOneLine if true, this means that the document will not contain any
  6645. linefeeds, so it'll be smaller but not very easy to read.
  6646. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6647. document
  6648. @param encodingType the character encoding format string to put into the xml
  6649. header
  6650. @param lineWrapLength the line length that will be used before items get placed on
  6651. a new line. This isn't an absolute maximum length, it just
  6652. determines how lists of attributes get broken up
  6653. @see writeToFile
  6654. */
  6655. const String createDocument (const String& dtdToUse,
  6656. const bool allOnOneLine = false,
  6657. const bool includeXmlHeader = true,
  6658. const tchar* const encodingType = JUCE_T("UTF-8"),
  6659. const int lineWrapLength = 60) const throw();
  6660. /** Writes the element to a file as an XML document.
  6661. To improve safety in case something goes wrong while writing the file, this
  6662. will actually write the document to a new temporary file in the same
  6663. directory as the destination file, and if this succeeds, it will rename this
  6664. new file as the destination file (overwriting any existing file that was there).
  6665. @param destinationFile the file to write to. If this already exists, it will be
  6666. overwritten.
  6667. @param dtdToUse the DTD to add to the document
  6668. @param encodingType the character encoding format string to put into the xml
  6669. header
  6670. @param lineWrapLength the line length that will be used before items get placed on
  6671. a new line. This isn't an absolute maximum length, it just
  6672. determines how lists of attributes get broken up
  6673. @returns true if the file is written successfully; false if something goes wrong
  6674. in the process
  6675. @see createDocument
  6676. */
  6677. bool writeToFile (const File& destinationFile,
  6678. const String& dtdToUse,
  6679. const tchar* const encodingType = JUCE_T("UTF-8"),
  6680. const int lineWrapLength = 60) const throw();
  6681. /** Returns this element's tag type name.
  6682. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6683. "MOOSE".
  6684. @see hasTagName
  6685. */
  6686. inline const String& getTagName() const throw() { return tagName; }
  6687. /** Tests whether this element has a particular tag name.
  6688. @param possibleTagName the tag name you're comparing it with
  6689. @see getTagName
  6690. */
  6691. bool hasTagName (const tchar* const possibleTagName) const throw();
  6692. /** Returns the number of XML attributes this element contains.
  6693. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6694. return 2.
  6695. */
  6696. int getNumAttributes() const throw();
  6697. /** Returns the name of one of the elements attributes.
  6698. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6699. getAttributeName(1) would return "antlers".
  6700. @see getAttributeValue, getStringAttribute
  6701. */
  6702. const String& getAttributeName (const int attributeIndex) const throw();
  6703. /** Returns the value of one of the elements attributes.
  6704. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6705. getAttributeName(1) would return "2".
  6706. @see getAttributeName, getStringAttribute
  6707. */
  6708. const String& getAttributeValue (const int attributeIndex) const throw();
  6709. // Attribute-handling methods..
  6710. /** Checks whether the element contains an attribute with a certain name. */
  6711. bool hasAttribute (const tchar* const attributeName) const throw();
  6712. /** Returns the value of a named attribute.
  6713. @param attributeName the name of the attribute to look up
  6714. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6715. with this name
  6716. */
  6717. const String getStringAttribute (const tchar* const attributeName,
  6718. const tchar* const defaultReturnValue = 0) const throw();
  6719. /** Compares the value of a named attribute with a value passed-in.
  6720. @param attributeName the name of the attribute to look up
  6721. @param stringToCompareAgainst the value to compare it with
  6722. @param ignoreCase whether the comparison should be case-insensitive
  6723. @returns true if the value of the attribute is the same as the string passed-in;
  6724. false if it's different (or if no such attribute exists)
  6725. */
  6726. bool compareAttribute (const tchar* const attributeName,
  6727. const tchar* const stringToCompareAgainst,
  6728. const bool ignoreCase = false) const throw();
  6729. /** Returns the value of a named attribute as an integer.
  6730. This will try to find the attribute and convert it to an integer (using
  6731. the String::getIntValue() method).
  6732. @param attributeName the name of the attribute to look up
  6733. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6734. with this name
  6735. @see setAttribute (const tchar* const, int)
  6736. */
  6737. int getIntAttribute (const tchar* const attributeName,
  6738. const int defaultReturnValue = 0) const throw();
  6739. /** Returns the value of a named attribute as floating-point.
  6740. This will try to find the attribute and convert it to an integer (using
  6741. the String::getDoubleValue() method).
  6742. @param attributeName the name of the attribute to look up
  6743. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6744. with this name
  6745. @see setAttribute (const tchar* const, double)
  6746. */
  6747. double getDoubleAttribute (const tchar* const attributeName,
  6748. const double defaultReturnValue = 0.0) const throw();
  6749. /** Returns the value of a named attribute as a boolean.
  6750. This will try to find the attribute and interpret it as a boolean. To do this,
  6751. it'll return true if the value is "1", "true", "y", etc, or false for other
  6752. values.
  6753. @param attributeName the name of the attribute to look up
  6754. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6755. with this name
  6756. */
  6757. bool getBoolAttribute (const tchar* const attributeName,
  6758. const bool defaultReturnValue = false) const throw();
  6759. /** Adds a named attribute to the element.
  6760. If the element already contains an attribute with this name, it's value will
  6761. be updated to the new value. If there's no such attribute yet, a new one will
  6762. be added.
  6763. Note that there are other setAttribute() methods that take integers,
  6764. doubles, etc. to make it easy to store numbers.
  6765. @param attributeName the name of the attribute to set
  6766. @param newValue the value to set it to
  6767. @see removeAttribute
  6768. */
  6769. void setAttribute (const tchar* const attributeName,
  6770. const String& newValue) throw();
  6771. /** Adds a named attribute to the element.
  6772. If the element already contains an attribute with this name, it's value will
  6773. be updated to the new value. If there's no such attribute yet, a new one will
  6774. be added.
  6775. Note that there are other setAttribute() methods that take integers,
  6776. doubles, etc. to make it easy to store numbers.
  6777. @param attributeName the name of the attribute to set
  6778. @param newValue the value to set it to
  6779. */
  6780. void setAttribute (const tchar* const attributeName,
  6781. const tchar* const newValue) throw();
  6782. /** Adds a named attribute to the element, setting it to an integer value.
  6783. If the element already contains an attribute with this name, it's value will
  6784. be updated to the new value. If there's no such attribute yet, a new one will
  6785. be added.
  6786. Note that there are other setAttribute() methods that take integers,
  6787. doubles, etc. to make it easy to store numbers.
  6788. @param attributeName the name of the attribute to set
  6789. @param newValue the value to set it to
  6790. */
  6791. void setAttribute (const tchar* const attributeName,
  6792. const int newValue) throw();
  6793. /** Adds a named attribute to the element, setting it to a floating-point value.
  6794. If the element already contains an attribute with this name, it's value will
  6795. be updated to the new value. If there's no such attribute yet, a new one will
  6796. be added.
  6797. Note that there are other setAttribute() methods that take integers,
  6798. doubles, etc. to make it easy to store numbers.
  6799. @param attributeName the name of the attribute to set
  6800. @param newValue the value to set it to
  6801. */
  6802. void setAttribute (const tchar* const attributeName,
  6803. const double newValue) throw();
  6804. /** Removes a named attribute from the element.
  6805. @param attributeName the name of the attribute to remove
  6806. @see removeAllAttributes
  6807. */
  6808. void removeAttribute (const tchar* const attributeName) throw();
  6809. /** Removes all attributes from this element.
  6810. */
  6811. void removeAllAttributes() throw();
  6812. // Child element methods..
  6813. /** Returns the first of this element's sub-elements.
  6814. see getNextElement() for an example of how to iterate the sub-elements.
  6815. @see forEachXmlChildElement
  6816. */
  6817. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6818. /** Returns the next of this element's siblings.
  6819. This can be used for iterating an element's sub-elements, e.g.
  6820. @code
  6821. XmlElement* child = myXmlDocument->getFirstChildElement();
  6822. while (child != 0)
  6823. {
  6824. ...do stuff with this child..
  6825. child = child->getNextElement();
  6826. }
  6827. @endcode
  6828. Note that when iterating the child elements, some of them might be
  6829. text elements as well as XML tags - use isTextElement() to work this
  6830. out.
  6831. Also, it's much easier and neater to use this method indirectly via the
  6832. forEachXmlChildElement macro.
  6833. @returns the sibling element that follows this one, or zero if this is the last
  6834. element in its parent
  6835. @see getNextElement, isTextElement, forEachXmlChildElement
  6836. */
  6837. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6838. /** Returns the next of this element's siblings which has the specified tag
  6839. name.
  6840. This is like getNextElement(), but will scan through the list until it
  6841. finds an element with the given tag name.
  6842. @see getNextElement, forEachXmlChildElementWithTagName
  6843. */
  6844. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6845. /** Returns the number of sub-elements in this element.
  6846. @see getChildElement
  6847. */
  6848. int getNumChildElements() const throw();
  6849. /** Returns the sub-element at a certain index.
  6850. It's not very efficient to iterate the sub-elements by index - see
  6851. getNextElement() for an example of how best to iterate.
  6852. @returns the n'th child of this element, or 0 if the index is out-of-range
  6853. @see getNextElement, isTextElement, getChildByName
  6854. */
  6855. XmlElement* getChildElement (const int index) const throw();
  6856. /** Returns the first sub-element with a given tag-name.
  6857. @param tagNameToLookFor the tag name of the element you want to find
  6858. @returns the first element with this tag name, or 0 if none is found
  6859. @see getNextElement, isTextElement, getChildElement
  6860. */
  6861. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6862. /** Appends an element to this element's list of children.
  6863. Child elements are deleted automatically when their parent is deleted, so
  6864. make sure the object that you pass in will not be deleted by anything else,
  6865. and make sure it's not already the child of another element.
  6866. @see getFirstChildElement, getNextElement, getNumChildElements,
  6867. getChildElement, removeChildElement
  6868. */
  6869. void addChildElement (XmlElement* const newChildElement) throw();
  6870. /** Inserts an element into this element's list of children.
  6871. Child elements are deleted automatically when their parent is deleted, so
  6872. make sure the object that you pass in will not be deleted by anything else,
  6873. and make sure it's not already the child of another element.
  6874. @param newChildNode the element to add
  6875. @param indexToInsertAt the index at which to insert the new element - if this is
  6876. below zero, it will be added to the end of the list
  6877. @see addChildElement, insertChildElement
  6878. */
  6879. void insertChildElement (XmlElement* const newChildNode,
  6880. int indexToInsertAt) throw();
  6881. /** Replaces one of this element's children with another node.
  6882. If the current element passed-in isn't actually a child of this element,
  6883. this will return false and the new one won't be added. Otherwise, the
  6884. existing element will be deleted, replaced with the new one, and it
  6885. will return true.
  6886. */
  6887. bool replaceChildElement (XmlElement* const currentChildElement,
  6888. XmlElement* const newChildNode) throw();
  6889. /** Removes a child element.
  6890. @param childToRemove the child to look for and remove
  6891. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6892. just remove it
  6893. */
  6894. void removeChildElement (XmlElement* const childToRemove,
  6895. const bool shouldDeleteTheChild) throw();
  6896. /** Deletes all the child elements in the element.
  6897. @see removeChildElement, deleteAllChildElementsWithTagName
  6898. */
  6899. void deleteAllChildElements() throw();
  6900. /** Deletes all the child elements with a given tag name.
  6901. @see removeChildElement
  6902. */
  6903. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6904. /** Returns true if the given element is a child of this one. */
  6905. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6906. /** Recursively searches all sub-elements to find one that contains the specified
  6907. child element.
  6908. */
  6909. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6910. /** Sorts the child elements using a comparator.
  6911. This will use a comparator object to sort the elements into order. The object
  6912. passed must have a method of the form:
  6913. @code
  6914. int compareElements (const XmlElement* first, const XmlElement* second);
  6915. @endcode
  6916. ..and this method must return:
  6917. - a value of < 0 if the first comes before the second
  6918. - a value of 0 if the two objects are equivalent
  6919. - a value of > 0 if the second comes before the first
  6920. To improve performance, the compareElements() method can be declared as static or const.
  6921. @param comparator the comparator to use for comparing elements.
  6922. @param retainOrderOfEquivalentItems if this is true, then items
  6923. which the comparator says are equivalent will be
  6924. kept in the order in which they currently appear
  6925. in the array. This is slower to perform, but may
  6926. be important in some cases. If it's false, a faster
  6927. algorithm is used, but equivalent elements may be
  6928. rearranged.
  6929. */
  6930. template <class ElementComparator>
  6931. void sortChildElements (ElementComparator& comparator,
  6932. const bool retainOrderOfEquivalentItems = false) throw()
  6933. {
  6934. const int num = getNumChildElements();
  6935. if (num > 1)
  6936. {
  6937. XmlElement** const elems = getChildElementsAsArray (num);
  6938. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  6939. reorderChildElements (elems, num);
  6940. delete[] elems;
  6941. }
  6942. }
  6943. /** Returns true if this element is a section of text.
  6944. Elements can either be an XML tag element or a secton of text, so this
  6945. is used to find out what kind of element this one is.
  6946. @see getAllText, addTextElement, deleteAllTextElements
  6947. */
  6948. bool isTextElement() const throw();
  6949. /** Returns the text for a text element.
  6950. Note that if you have an element like this:
  6951. @code<xyz>hello</xyz>@endcode
  6952. then calling getText on the "xyz" element won't return "hello", because that is
  6953. actually stored in a special text sub-element inside the xyz element. To get the
  6954. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6955. use getAllSubText() to do this automatically.
  6956. @see isTextElement, getAllSubText, getChildElementAllSubText
  6957. */
  6958. const String getText() const throw();
  6959. /** Sets the text in a text element.
  6960. Note that this is only a valid call if this element is a text element. If it's
  6961. not, then no action will be performed.
  6962. */
  6963. void setText (const String& newText) throw();
  6964. /** Returns all the text from this element's child nodes.
  6965. This iterates all the child elements and when it finds text elements,
  6966. it concatenates their text into a big string which it returns.
  6967. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6968. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6969. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6970. */
  6971. const String getAllSubText() const throw();
  6972. /** Returns all the sub-text of a named child element.
  6973. If there is a child element with the given tag name, this will return
  6974. all of its sub-text (by calling getAllSubText() on it). If there is
  6975. no such child element, this will return the default string passed-in.
  6976. @see getAllSubText
  6977. */
  6978. const String getChildElementAllSubText (const tchar* const childTagName,
  6979. const String& defaultReturnValue) const throw();
  6980. /** Appends a section of text to this element.
  6981. @see isTextElement, getText, getAllSubText
  6982. */
  6983. void addTextElement (const String& text) throw();
  6984. /** Removes all the text elements from this element.
  6985. @see isTextElement, getText, getAllSubText, addTextElement
  6986. */
  6987. void deleteAllTextElements() throw();
  6988. /** Creates a text element that can be added to a parent element.
  6989. */
  6990. static XmlElement* createTextElement (const String& text) throw();
  6991. juce_UseDebuggingNewOperator
  6992. private:
  6993. friend class XmlDocument;
  6994. String tagName;
  6995. XmlElement* firstChildElement;
  6996. XmlElement* nextElement;
  6997. struct XmlAttributeNode
  6998. {
  6999. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7000. XmlAttributeNode (const String& name, const String& value) throw();
  7001. String name, value;
  7002. XmlAttributeNode* next;
  7003. };
  7004. XmlAttributeNode* attributes;
  7005. XmlElement (int) throw(); // for internal use
  7006. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  7007. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  7008. void writeElementAsText (OutputStream& out,
  7009. const int indentationLevel,
  7010. const int lineWrapLength) const throw();
  7011. XmlElement** getChildElementsAsArray (const int) const throw();
  7012. void reorderChildElements (XmlElement** const, const int) throw();
  7013. };
  7014. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7015. /********* End of inlined file: juce_XmlElement.h *********/
  7016. /**
  7017. A set of named property values, which can be strings, integers, floating point, etc.
  7018. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7019. to load and save types other than strings.
  7020. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7021. messages and saves/loads the list from a file.
  7022. */
  7023. class JUCE_API PropertySet
  7024. {
  7025. public:
  7026. /** Creates an empty PropertySet.
  7027. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7028. case-insensitive way
  7029. */
  7030. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7031. /** Creates a copy of another PropertySet.
  7032. */
  7033. PropertySet (const PropertySet& other) throw();
  7034. /** Copies another PropertySet over this one.
  7035. */
  7036. const PropertySet& operator= (const PropertySet& other) throw();
  7037. /** Destructor. */
  7038. virtual ~PropertySet();
  7039. /** Returns one of the properties as a string.
  7040. If the value isn't found in this set, then this will look for it in a fallback
  7041. property set (if you've specified one with the setFallbackPropertySet() method),
  7042. and if it can't find one there, it'll return the default value passed-in.
  7043. @param keyName the name of the property to retrieve
  7044. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7045. */
  7046. const String getValue (const String& keyName,
  7047. const String& defaultReturnValue = String::empty) const throw();
  7048. /** Returns one of the properties as an integer.
  7049. If the value isn't found in this set, then this will look for it in a fallback
  7050. property set (if you've specified one with the setFallbackPropertySet() method),
  7051. and if it can't find one there, it'll return the default value passed-in.
  7052. @param keyName the name of the property to retrieve
  7053. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7054. */
  7055. int getIntValue (const String& keyName,
  7056. const int defaultReturnValue = 0) const throw();
  7057. /** Returns one of the properties as an double.
  7058. If the value isn't found in this set, then this will look for it in a fallback
  7059. property set (if you've specified one with the setFallbackPropertySet() method),
  7060. and if it can't find one there, it'll return the default value passed-in.
  7061. @param keyName the name of the property to retrieve
  7062. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7063. */
  7064. double getDoubleValue (const String& keyName,
  7065. const double defaultReturnValue = 0.0) const throw();
  7066. /** Returns one of the properties as an boolean.
  7067. The result will be true if the string found for this key name can be parsed as a non-zero
  7068. integer.
  7069. If the value isn't found in this set, then this will look for it in a fallback
  7070. property set (if you've specified one with the setFallbackPropertySet() method),
  7071. and if it can't find one there, it'll return the default value passed-in.
  7072. @param keyName the name of the property to retrieve
  7073. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7074. */
  7075. bool getBoolValue (const String& keyName,
  7076. const bool defaultReturnValue = false) const throw();
  7077. /** Returns one of the properties as an XML element.
  7078. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7079. key isn't found, or if the entry contains an string that isn't valid XML.
  7080. If the value isn't found in this set, then this will look for it in a fallback
  7081. property set (if you've specified one with the setFallbackPropertySet() method),
  7082. and if it can't find one there, it'll return the default value passed-in.
  7083. @param keyName the name of the property to retrieve
  7084. */
  7085. XmlElement* getXmlValue (const String& keyName) const;
  7086. /** Sets a named property as a string.
  7087. @param keyName the name of the property to set. (This mustn't be an empty string)
  7088. @param value the new value to set it to
  7089. */
  7090. void setValue (const String& keyName, const String& value) throw();
  7091. /** Sets a named property as a string.
  7092. @param keyName the name of the property to set. (This mustn't be an empty string)
  7093. @param value the new value to set it to
  7094. */
  7095. void setValue (const String& keyName, const tchar* const value) throw();
  7096. /** Sets a named property to an integer.
  7097. @param keyName the name of the property to set. (This mustn't be an empty string)
  7098. @param value the new value to set it to
  7099. */
  7100. void setValue (const String& keyName, const int value) throw();
  7101. /** Sets a named property to a double.
  7102. @param keyName the name of the property to set. (This mustn't be an empty string)
  7103. @param value the new value to set it to
  7104. */
  7105. void setValue (const String& keyName, const double value) throw();
  7106. /** Sets a named property to a boolean.
  7107. @param keyName the name of the property to set. (This mustn't be an empty string)
  7108. @param value the new value to set it to
  7109. */
  7110. void setValue (const String& keyName, const bool value) throw();
  7111. /** Sets a named property to an XML element.
  7112. @param keyName the name of the property to set. (This mustn't be an empty string)
  7113. @param xml the new element to set it to. If this is zero, the value will be set to
  7114. an empty string
  7115. @see getXmlValue
  7116. */
  7117. void setValue (const String& keyName, const XmlElement* const xml);
  7118. /** Deletes a property.
  7119. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7120. */
  7121. void removeValue (const String& keyName) throw();
  7122. /** Returns true if the properies include the given key. */
  7123. bool containsKey (const String& keyName) const throw();
  7124. /** Removes all values. */
  7125. void clear();
  7126. /** Returns the keys/value pair array containing all the properties. */
  7127. StringPairArray& getAllProperties() throw() { return properties; }
  7128. /** Returns the lock used when reading or writing to this set */
  7129. const CriticalSection& getLock() const throw() { return lock; }
  7130. /** Returns an XML element which encapsulates all the items in this property set.
  7131. The string parameter is the tag name that should be used for the node.
  7132. @see restoreFromXml
  7133. */
  7134. XmlElement* createXml (const String& nodeName) const throw();
  7135. /** Reloads a set of properties that were previously stored as XML.
  7136. The node passed in must have been created by the createXml() method.
  7137. @see createXml
  7138. */
  7139. void restoreFromXml (const XmlElement& xml) throw();
  7140. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7141. set in this one.
  7142. If you set this up to be a pointer to a second property set, then whenever one
  7143. of the getValue() methods fails to find an entry in this set, it will look up that
  7144. value in the fallback set, and if it finds it, it will return that.
  7145. Make sure that you don't delete the fallback set while it's still being used by
  7146. another set! To remove the fallback set, just call this method with a null pointer.
  7147. @see getFallbackPropertySet
  7148. */
  7149. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7150. /** Returns the fallback property set.
  7151. @see setFallbackPropertySet
  7152. */
  7153. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7154. juce_UseDebuggingNewOperator
  7155. protected:
  7156. /** Subclasses can override this to be told when one of the properies has been changed.
  7157. */
  7158. virtual void propertyChanged();
  7159. private:
  7160. StringPairArray properties;
  7161. PropertySet* fallbackProperties;
  7162. CriticalSection lock;
  7163. bool ignoreCaseOfKeys;
  7164. };
  7165. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7166. /********* End of inlined file: juce_PropertySet.h *********/
  7167. #endif
  7168. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7169. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7170. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7171. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7172. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7173. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7174. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7175. /**
  7176. Adds reference-counting to an object.
  7177. To add reference-counting to a class, derive it from this class, and
  7178. use the ReferenceCountedObjectPtr class to point to it.
  7179. e.g. @code
  7180. class MyClass : public ReferenceCountedObject
  7181. {
  7182. void foo();
  7183. // This is a neat way of declaring a typedef for a pointer class,
  7184. // rather than typing out the full templated name each time..
  7185. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7186. };
  7187. MyClass::Ptr p = new MyClass();
  7188. MyClass::Ptr p2 = p;
  7189. p = 0;
  7190. p2->foo();
  7191. @endcode
  7192. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7193. careful not to delete the object manually.
  7194. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7195. */
  7196. class JUCE_API ReferenceCountedObject
  7197. {
  7198. public:
  7199. /** Increments the object's reference count.
  7200. This is done automatically by the smart pointer, but is public just
  7201. in case it's needed for nefarious purposes.
  7202. */
  7203. inline void incReferenceCount() throw()
  7204. {
  7205. atomicIncrement (refCounts);
  7206. jassert (refCounts > 0);
  7207. }
  7208. /** Decreases the object's reference count.
  7209. If the count gets to zero, the object will be deleted.
  7210. */
  7211. inline void decReferenceCount() throw()
  7212. {
  7213. jassert (refCounts > 0);
  7214. if (atomicDecrementAndReturn (refCounts) == 0)
  7215. delete this;
  7216. }
  7217. /** Returns the object's current reference count. */
  7218. inline int getReferenceCount() const throw()
  7219. {
  7220. return refCounts;
  7221. }
  7222. protected:
  7223. /** Creates the reference-counted object (with an initial ref count of zero). */
  7224. ReferenceCountedObject()
  7225. : refCounts (0)
  7226. {
  7227. }
  7228. /** Destructor. */
  7229. virtual ~ReferenceCountedObject()
  7230. {
  7231. // it's dangerous to delete an object that's still referenced by something else!
  7232. jassert (refCounts == 0);
  7233. }
  7234. private:
  7235. int refCounts;
  7236. };
  7237. /**
  7238. Used to point to an object of type ReferenceCountedObject.
  7239. It's wise to use a typedef instead of typing out the templated name
  7240. each time - e.g.
  7241. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7242. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7243. */
  7244. template <class ReferenceCountedObjectClass>
  7245. class ReferenceCountedObjectPtr
  7246. {
  7247. public:
  7248. /** Creates a pointer to a null object. */
  7249. inline ReferenceCountedObjectPtr() throw()
  7250. : referencedObject (0)
  7251. {
  7252. }
  7253. /** Creates a pointer to an object.
  7254. This will increment the object's reference-count if it is non-null.
  7255. */
  7256. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7257. : referencedObject (refCountedObject)
  7258. {
  7259. if (refCountedObject != 0)
  7260. refCountedObject->incReferenceCount();
  7261. }
  7262. /** Copies another pointer.
  7263. This will increment the object's reference-count (if it is non-null).
  7264. */
  7265. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7266. : referencedObject (other.referencedObject)
  7267. {
  7268. if (referencedObject != 0)
  7269. referencedObject->incReferenceCount();
  7270. }
  7271. /** Changes this pointer to point at a different object.
  7272. The reference count of the old object is decremented, and it might be
  7273. deleted if it hits zero. The new object's count is incremented.
  7274. */
  7275. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7276. {
  7277. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7278. if (newObject != referencedObject)
  7279. {
  7280. if (newObject != 0)
  7281. newObject->incReferenceCount();
  7282. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7283. referencedObject = newObject;
  7284. if (oldObject != 0)
  7285. oldObject->decReferenceCount();
  7286. }
  7287. return *this;
  7288. }
  7289. /** Changes this pointer to point at a different object.
  7290. The reference count of the old object is decremented, and it might be
  7291. deleted if it hits zero. The new object's count is incremented.
  7292. */
  7293. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7294. {
  7295. if (referencedObject != newObject)
  7296. {
  7297. if (newObject != 0)
  7298. newObject->incReferenceCount();
  7299. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7300. referencedObject = newObject;
  7301. if (oldObject != 0)
  7302. oldObject->decReferenceCount();
  7303. }
  7304. return *this;
  7305. }
  7306. /** Destructor.
  7307. This will decrement the object's reference-count, and may delete it if it
  7308. gets to zero.
  7309. */
  7310. inline ~ReferenceCountedObjectPtr()
  7311. {
  7312. if (referencedObject != 0)
  7313. referencedObject->decReferenceCount();
  7314. }
  7315. /** Returns the object that this pointer references.
  7316. The pointer returned may be zero, of course.
  7317. */
  7318. inline operator ReferenceCountedObjectClass*() const throw()
  7319. {
  7320. return referencedObject;
  7321. }
  7322. /** Returns true if this pointer refers to the given object. */
  7323. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7324. {
  7325. return referencedObject == object;
  7326. }
  7327. /** Returns true if this pointer doesn't refer to the given object. */
  7328. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7329. {
  7330. return referencedObject != object;
  7331. }
  7332. // the -> operator is called on the referenced object
  7333. inline ReferenceCountedObjectClass* operator->() const throw()
  7334. {
  7335. return referencedObject;
  7336. }
  7337. private:
  7338. ReferenceCountedObjectClass* referencedObject;
  7339. };
  7340. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7341. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7342. /**
  7343. Holds a list of objects derived from ReferenceCountedObject.
  7344. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7345. and takes care of incrementing and decrementing their ref counts when they
  7346. are added and removed from the array.
  7347. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7348. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7349. @see Array, OwnedArray, StringArray
  7350. */
  7351. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7352. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7353. {
  7354. public:
  7355. /** Creates an empty array.
  7356. @param granularity this is the size of increment by which the internal storage
  7357. used by the array will grow. Only change it from the default if you know the
  7358. array is going to be very big and needs to be able to grow efficiently.
  7359. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7360. */
  7361. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7362. : ArrayAllocationBase <ObjectClass*> (granularity),
  7363. numUsed (0)
  7364. {
  7365. }
  7366. /** Creates a copy of another array */
  7367. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7368. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  7369. numUsed (other.numUsed)
  7370. {
  7371. other.lockArray();
  7372. this->setAllocatedSize (numUsed);
  7373. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7374. for (int i = numUsed; --i >= 0;)
  7375. if (this->elements[i] != 0)
  7376. this->elements[i]->incReferenceCount();
  7377. other.unlockArray();
  7378. }
  7379. /** Copies another array into this one.
  7380. Any existing objects in this array will first be released.
  7381. */
  7382. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7383. {
  7384. if (this != &other)
  7385. {
  7386. other.lockArray();
  7387. lock.enter();
  7388. clear();
  7389. this->granularity = other.granularity;
  7390. this->ensureAllocatedSize (other.numUsed);
  7391. numUsed = other.numUsed;
  7392. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7393. minimiseStorageOverheads();
  7394. for (int i = numUsed; --i >= 0;)
  7395. if (this->elements[i] != 0)
  7396. this->elements[i]->incReferenceCount();
  7397. lock.exit();
  7398. other.unlockArray();
  7399. }
  7400. return *this;
  7401. }
  7402. /** Destructor.
  7403. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7404. */
  7405. ~ReferenceCountedArray()
  7406. {
  7407. clear();
  7408. }
  7409. /** Removes all objects from the array.
  7410. Any objects in the array that are not referenced from elsewhere will be deleted.
  7411. */
  7412. void clear()
  7413. {
  7414. lock.enter();
  7415. while (numUsed > 0)
  7416. if (this->elements [--numUsed] != 0)
  7417. this->elements [numUsed]->decReferenceCount();
  7418. jassert (numUsed == 0);
  7419. this->setAllocatedSize (0);
  7420. lock.exit();
  7421. }
  7422. /** Returns the current number of objects in the array. */
  7423. inline int size() const throw()
  7424. {
  7425. return numUsed;
  7426. }
  7427. /** Returns a pointer to the object at this index in the array.
  7428. If the index is out-of-range, this will return a null pointer, (and
  7429. it could be null anyway, because it's ok for the array to hold null
  7430. pointers as well as objects).
  7431. @see getUnchecked
  7432. */
  7433. inline ObjectClass* operator[] (const int index) const throw()
  7434. {
  7435. lock.enter();
  7436. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  7437. ? this->elements [index]
  7438. : (ObjectClass*) 0;
  7439. lock.exit();
  7440. return result;
  7441. }
  7442. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7443. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7444. it can be used when you're sure the index if always going to be legal.
  7445. */
  7446. inline ObjectClass* getUnchecked (const int index) const throw()
  7447. {
  7448. lock.enter();
  7449. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7450. ObjectClass* const result = this->elements [index];
  7451. lock.exit();
  7452. return result;
  7453. }
  7454. /** Returns a pointer to the first object in the array.
  7455. This will return a null pointer if the array's empty.
  7456. @see getLast
  7457. */
  7458. inline ObjectClass* getFirst() const throw()
  7459. {
  7460. lock.enter();
  7461. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  7462. : (ObjectClass*) 0;
  7463. lock.exit();
  7464. return result;
  7465. }
  7466. /** Returns a pointer to the last object in the array.
  7467. This will return a null pointer if the array's empty.
  7468. @see getFirst
  7469. */
  7470. inline ObjectClass* getLast() const throw()
  7471. {
  7472. lock.enter();
  7473. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  7474. : (ObjectClass*) 0;
  7475. lock.exit();
  7476. return result;
  7477. }
  7478. /** Finds the index of the first occurrence of an object in the array.
  7479. @param objectToLookFor the object to look for
  7480. @returns the index at which the object was found, or -1 if it's not found
  7481. */
  7482. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7483. {
  7484. int result = -1;
  7485. lock.enter();
  7486. ObjectClass** e = this->elements;
  7487. for (int i = numUsed; --i >= 0;)
  7488. {
  7489. if (objectToLookFor == *e)
  7490. {
  7491. result = (int) (e - this->elements);
  7492. break;
  7493. }
  7494. ++e;
  7495. }
  7496. lock.exit();
  7497. return result;
  7498. }
  7499. /** Returns true if the array contains a specified object.
  7500. @param objectToLookFor the object to look for
  7501. @returns true if the object is in the array
  7502. */
  7503. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7504. {
  7505. lock.enter();
  7506. ObjectClass** e = this->elements;
  7507. for (int i = numUsed; --i >= 0;)
  7508. {
  7509. if (objectToLookFor == *e)
  7510. {
  7511. lock.exit();
  7512. return true;
  7513. }
  7514. ++e;
  7515. }
  7516. lock.exit();
  7517. return false;
  7518. }
  7519. /** Appends a new object to the end of the array.
  7520. This will increase the new object's reference count.
  7521. @param newObject the new object to add to the array
  7522. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7523. */
  7524. void add (ObjectClass* const newObject) throw()
  7525. {
  7526. lock.enter();
  7527. this->ensureAllocatedSize (numUsed + 1);
  7528. this->elements [numUsed++] = newObject;
  7529. if (newObject != 0)
  7530. newObject->incReferenceCount();
  7531. lock.exit();
  7532. }
  7533. /** Inserts a new object into the array at the given index.
  7534. If the index is less than 0 or greater than the size of the array, the
  7535. element will be added to the end of the array.
  7536. Otherwise, it will be inserted into the array, moving all the later elements
  7537. along to make room.
  7538. This will increase the new object's reference count.
  7539. @param indexToInsertAt the index at which the new element should be inserted
  7540. @param newObject the new object to add to the array
  7541. @see add, addSorted, addIfNotAlreadyThere, set
  7542. */
  7543. void insert (int indexToInsertAt,
  7544. ObjectClass* const newObject) throw()
  7545. {
  7546. if (indexToInsertAt >= 0)
  7547. {
  7548. lock.enter();
  7549. if (indexToInsertAt > numUsed)
  7550. indexToInsertAt = numUsed;
  7551. this->ensureAllocatedSize (numUsed + 1);
  7552. ObjectClass** const e = this->elements + indexToInsertAt;
  7553. const int numToMove = numUsed - indexToInsertAt;
  7554. if (numToMove > 0)
  7555. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7556. *e = newObject;
  7557. if (newObject != 0)
  7558. newObject->incReferenceCount();
  7559. ++numUsed;
  7560. lock.exit();
  7561. }
  7562. else
  7563. {
  7564. add (newObject);
  7565. }
  7566. }
  7567. /** Appends a new object at the end of the array as long as the array doesn't
  7568. already contain it.
  7569. If the array already contains a matching object, nothing will be done.
  7570. @param newObject the new object to add to the array
  7571. */
  7572. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7573. {
  7574. lock.enter();
  7575. if (! contains (newObject))
  7576. add (newObject);
  7577. lock.exit();
  7578. }
  7579. /** Replaces an object in the array with a different one.
  7580. If the index is less than zero, this method does nothing.
  7581. If the index is beyond the end of the array, the new object is added to the end of the array.
  7582. The object being added has its reference count increased, and if it's replacing
  7583. another object, then that one has its reference count decreased, and may be deleted.
  7584. @param indexToChange the index whose value you want to change
  7585. @param newObject the new value to set for this index.
  7586. @see add, insert, remove
  7587. */
  7588. void set (const int indexToChange,
  7589. ObjectClass* const newObject)
  7590. {
  7591. if (indexToChange >= 0)
  7592. {
  7593. lock.enter();
  7594. if (newObject != 0)
  7595. newObject->incReferenceCount();
  7596. if (indexToChange < numUsed)
  7597. {
  7598. if (this->elements [indexToChange] != 0)
  7599. this->elements [indexToChange]->decReferenceCount();
  7600. this->elements [indexToChange] = newObject;
  7601. }
  7602. else
  7603. {
  7604. this->ensureAllocatedSize (numUsed + 1);
  7605. this->elements [numUsed++] = newObject;
  7606. }
  7607. lock.exit();
  7608. }
  7609. }
  7610. /** Adds elements from another array to the end of this array.
  7611. @param arrayToAddFrom the array from which to copy the elements
  7612. @param startIndex the first element of the other array to start copying from
  7613. @param numElementsToAdd how many elements to add from the other array. If this
  7614. value is negative or greater than the number of available elements,
  7615. all available elements will be copied.
  7616. @see add
  7617. */
  7618. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7619. int startIndex = 0,
  7620. int numElementsToAdd = -1) throw()
  7621. {
  7622. arrayToAddFrom.lockArray();
  7623. lock.enter();
  7624. if (startIndex < 0)
  7625. {
  7626. jassertfalse
  7627. startIndex = 0;
  7628. }
  7629. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7630. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7631. if (numElementsToAdd > 0)
  7632. {
  7633. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  7634. while (--numElementsToAdd >= 0)
  7635. add (arrayToAddFrom.getUnchecked (startIndex++));
  7636. }
  7637. lock.exit();
  7638. arrayToAddFrom.unlockArray();
  7639. }
  7640. /** Inserts a new object into the array assuming that the array is sorted.
  7641. This will use a comparator to find the position at which the new object
  7642. should go. If the array isn't sorted, the behaviour of this
  7643. method will be unpredictable.
  7644. @param comparator the comparator object to use to compare the elements - see the
  7645. sort() method for details about this object's form
  7646. @param newObject the new object to insert to the array
  7647. @see add, sort
  7648. */
  7649. template <class ElementComparator>
  7650. void addSorted (ElementComparator& comparator,
  7651. ObjectClass* newObject) throw()
  7652. {
  7653. lock.enter();
  7654. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  7655. lock.exit();
  7656. }
  7657. /** Removes an object from the array.
  7658. This will remove the object at a given index and move back all the
  7659. subsequent objects to close the gap.
  7660. If the index passed in is out-of-range, nothing will happen.
  7661. The object that is removed will have its reference count decreased,
  7662. and may be deleted if not referenced from elsewhere.
  7663. @param indexToRemove the index of the element to remove
  7664. @see removeObject, removeRange
  7665. */
  7666. void remove (const int indexToRemove)
  7667. {
  7668. lock.enter();
  7669. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7670. {
  7671. ObjectClass** const e = this->elements + indexToRemove;
  7672. if (*e != 0)
  7673. (*e)->decReferenceCount();
  7674. --numUsed;
  7675. const int numberToShift = numUsed - indexToRemove;
  7676. if (numberToShift > 0)
  7677. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7678. if ((numUsed << 1) < this->numAllocated)
  7679. minimiseStorageOverheads();
  7680. }
  7681. lock.exit();
  7682. }
  7683. /** Removes the first occurrence of a specified object from the array.
  7684. If the item isn't found, no action is taken. If it is found, it is
  7685. removed and has its reference count decreased.
  7686. @param objectToRemove the object to try to remove
  7687. @see remove, removeRange
  7688. */
  7689. void removeObject (ObjectClass* const objectToRemove)
  7690. {
  7691. lock.enter();
  7692. remove (indexOf (objectToRemove));
  7693. lock.exit();
  7694. }
  7695. /** Removes a range of objects from the array.
  7696. This will remove a set of objects, starting from the given index,
  7697. and move any subsequent elements down to close the gap.
  7698. If the range extends beyond the bounds of the array, it will
  7699. be safely clipped to the size of the array.
  7700. The objects that are removed will have their reference counts decreased,
  7701. and may be deleted if not referenced from elsewhere.
  7702. @param startIndex the index of the first object to remove
  7703. @param numberToRemove how many objects should be removed
  7704. @see remove, removeObject
  7705. */
  7706. void removeRange (const int startIndex,
  7707. const int numberToRemove)
  7708. {
  7709. lock.enter();
  7710. const int start = jlimit (0, numUsed, startIndex);
  7711. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7712. if (end > start)
  7713. {
  7714. int i;
  7715. for (i = start; i < end; ++i)
  7716. {
  7717. if (this->elements[i] != 0)
  7718. {
  7719. this->elements[i]->decReferenceCount();
  7720. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7721. }
  7722. }
  7723. const int rangeSize = end - start;
  7724. ObjectClass** e = this->elements + start;
  7725. i = numUsed - end;
  7726. numUsed -= rangeSize;
  7727. while (--i >= 0)
  7728. {
  7729. *e = e [rangeSize];
  7730. ++e;
  7731. }
  7732. if ((numUsed << 1) < this->numAllocated)
  7733. minimiseStorageOverheads();
  7734. }
  7735. lock.exit();
  7736. }
  7737. /** Removes the last n objects from the array.
  7738. The objects that are removed will have their reference counts decreased,
  7739. and may be deleted if not referenced from elsewhere.
  7740. @param howManyToRemove how many objects to remove from the end of the array
  7741. @see remove, removeObject, removeRange
  7742. */
  7743. void removeLast (int howManyToRemove = 1)
  7744. {
  7745. lock.enter();
  7746. if (howManyToRemove > numUsed)
  7747. howManyToRemove = numUsed;
  7748. while (--howManyToRemove >= 0)
  7749. remove (numUsed - 1);
  7750. lock.exit();
  7751. }
  7752. /** Swaps a pair of objects in the array.
  7753. If either of the indexes passed in is out-of-range, nothing will happen,
  7754. otherwise the two objects at these positions will be exchanged.
  7755. */
  7756. void swap (const int index1,
  7757. const int index2) throw()
  7758. {
  7759. lock.enter();
  7760. if (((unsigned int) index1) < (unsigned int) numUsed
  7761. && ((unsigned int) index2) < (unsigned int) numUsed)
  7762. {
  7763. swapVariables (this->elements [index1],
  7764. this->elements [index2]);
  7765. }
  7766. lock.exit();
  7767. }
  7768. /** Moves one of the objects to a different position.
  7769. This will move the object to a specified index, shuffling along
  7770. any intervening elements as required.
  7771. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7772. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7773. @param currentIndex the index of the object to be moved. If this isn't a
  7774. valid index, then nothing will be done
  7775. @param newIndex the index at which you'd like this object to end up. If this
  7776. is less than zero, it will be moved to the end of the array
  7777. */
  7778. void move (const int currentIndex,
  7779. int newIndex) throw()
  7780. {
  7781. if (currentIndex != newIndex)
  7782. {
  7783. lock.enter();
  7784. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7785. {
  7786. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7787. newIndex = numUsed - 1;
  7788. ObjectClass* const value = this->elements [currentIndex];
  7789. if (newIndex > currentIndex)
  7790. {
  7791. memmove (this->elements + currentIndex,
  7792. this->elements + currentIndex + 1,
  7793. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7794. }
  7795. else
  7796. {
  7797. memmove (this->elements + newIndex + 1,
  7798. this->elements + newIndex,
  7799. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7800. }
  7801. this->elements [newIndex] = value;
  7802. }
  7803. lock.exit();
  7804. }
  7805. }
  7806. /** Compares this array to another one.
  7807. @returns true only if the other array contains the same objects in the same order
  7808. */
  7809. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7810. {
  7811. other.lockArray();
  7812. lock.enter();
  7813. bool result = numUsed == other.numUsed;
  7814. if (result)
  7815. {
  7816. for (int i = numUsed; --i >= 0;)
  7817. {
  7818. if (this->elements [i] != other.elements [i])
  7819. {
  7820. result = false;
  7821. break;
  7822. }
  7823. }
  7824. }
  7825. lock.exit();
  7826. other.unlockArray();
  7827. return result;
  7828. }
  7829. /** Compares this array to another one.
  7830. @see operator==
  7831. */
  7832. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7833. {
  7834. return ! operator== (other);
  7835. }
  7836. /** Sorts the elements in the array.
  7837. This will use a comparator object to sort the elements into order. The object
  7838. passed must have a method of the form:
  7839. @code
  7840. int compareElements (ElementType first, ElementType second);
  7841. @endcode
  7842. ..and this method must return:
  7843. - a value of < 0 if the first comes before the second
  7844. - a value of 0 if the two objects are equivalent
  7845. - a value of > 0 if the second comes before the first
  7846. To improve performance, the compareElements() method can be declared as static or const.
  7847. @param comparator the comparator to use for comparing elements.
  7848. @param retainOrderOfEquivalentItems if this is true, then items
  7849. which the comparator says are equivalent will be
  7850. kept in the order in which they currently appear
  7851. in the array. This is slower to perform, but may
  7852. be important in some cases. If it's false, a faster
  7853. algorithm is used, but equivalent elements may be
  7854. rearranged.
  7855. @see sortArray
  7856. */
  7857. template <class ElementComparator>
  7858. void sort (ElementComparator& comparator,
  7859. const bool retainOrderOfEquivalentItems = false) const throw()
  7860. {
  7861. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7862. // avoids getting warning messages about the parameter being unused
  7863. lock.enter();
  7864. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7865. lock.exit();
  7866. }
  7867. /** Reduces the amount of storage being used by the array.
  7868. Arrays typically allocate slightly more storage than they need, and after
  7869. removing elements, they may have quite a lot of unused space allocated.
  7870. This method will reduce the amount of allocated storage to a minimum.
  7871. */
  7872. void minimiseStorageOverheads() throw()
  7873. {
  7874. lock.enter();
  7875. if (numUsed == 0)
  7876. {
  7877. this->setAllocatedSize (0);
  7878. }
  7879. else
  7880. {
  7881. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  7882. if (newAllocation < this->numAllocated)
  7883. this->setAllocatedSize (newAllocation);
  7884. }
  7885. lock.exit();
  7886. }
  7887. /** Locks the array's CriticalSection.
  7888. Of course if the type of section used is a DummyCriticalSection, this won't
  7889. have any effect.
  7890. @see unlockArray
  7891. */
  7892. void lockArray() const throw()
  7893. {
  7894. lock.enter();
  7895. }
  7896. /** Unlocks the array's CriticalSection.
  7897. Of course if the type of section used is a DummyCriticalSection, this won't
  7898. have any effect.
  7899. @see lockArray
  7900. */
  7901. void unlockArray() const throw()
  7902. {
  7903. lock.exit();
  7904. }
  7905. juce_UseDebuggingNewOperator
  7906. private:
  7907. int numUsed;
  7908. TypeOfCriticalSectionToUse lock;
  7909. };
  7910. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7911. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7912. #endif
  7913. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7914. #endif
  7915. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7916. /********* Start of inlined file: juce_SortedSet.h *********/
  7917. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7918. #define __JUCE_SORTEDSET_JUCEHEADER__
  7919. #if JUCE_MSVC
  7920. #pragma warning (push)
  7921. #pragma warning (disable: 4512)
  7922. #endif
  7923. /**
  7924. Holds a set of unique primitive objects, such as ints or doubles.
  7925. A set can only hold one item with a given value, so if for example it's a
  7926. set of integers, attempting to add the same integer twice will do nothing
  7927. the second time.
  7928. Internally, the list of items is kept sorted (which means that whatever
  7929. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7930. to determine the order), and searching the set for known values is very fast
  7931. because it uses a binary-chop method.
  7932. Note that if you're using a class or struct as the element type, it must be
  7933. capable of being copied or moved with a straightforward memcpy, rather than
  7934. needing construction and destruction code.
  7935. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7936. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7937. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7938. */
  7939. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7940. class SortedSet : private ArrayAllocationBase <ElementType>
  7941. {
  7942. public:
  7943. /** Creates an empty set.
  7944. @param granularity this is the size of increment by which the internal storage
  7945. used by the array will grow. Only change it from the default if you know the
  7946. array is going to be very big and needs to be able to grow efficiently.
  7947. @see ArrayAllocationBase
  7948. */
  7949. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7950. : ArrayAllocationBase <ElementType> (granularity),
  7951. numUsed (0)
  7952. {
  7953. }
  7954. /** Creates a copy of another set.
  7955. @param other the set to copy
  7956. */
  7957. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7958. : ArrayAllocationBase <ElementType> (other.granularity)
  7959. {
  7960. other.lockSet();
  7961. numUsed = other.numUsed;
  7962. setAllocatedSize (other.numUsed);
  7963. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7964. other.unlockSet();
  7965. }
  7966. /** Destructor. */
  7967. ~SortedSet() throw()
  7968. {
  7969. }
  7970. /** Copies another set over this one.
  7971. @param other the set to copy
  7972. */
  7973. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7974. {
  7975. if (this != &other)
  7976. {
  7977. other.lockSet();
  7978. lock.enter();
  7979. this->granularity = other.granularity;
  7980. ensureAllocatedSize (other.size());
  7981. numUsed = other.numUsed;
  7982. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7983. minimiseStorageOverheads();
  7984. lock.exit();
  7985. other.unlockSet();
  7986. }
  7987. return *this;
  7988. }
  7989. /** Compares this set to another one.
  7990. Two sets are considered equal if they both contain the same set of
  7991. elements.
  7992. @param other the other set to compare with
  7993. */
  7994. bool operator== (const SortedSet<ElementType>& other) const throw()
  7995. {
  7996. lock.enter();
  7997. if (numUsed != other.numUsed)
  7998. {
  7999. lock.exit();
  8000. return false;
  8001. }
  8002. for (int i = numUsed; --i >= 0;)
  8003. {
  8004. if (this->elements [i] != other.elements [i])
  8005. {
  8006. lock.exit();
  8007. return false;
  8008. }
  8009. }
  8010. lock.exit();
  8011. return true;
  8012. }
  8013. /** Compares this set to another one.
  8014. Two sets are considered equal if they both contain the same set of
  8015. elements.
  8016. @param other the other set to compare with
  8017. */
  8018. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8019. {
  8020. return ! operator== (other);
  8021. }
  8022. /** Removes all elements from the set.
  8023. This will remove all the elements, and free any storage that the set is
  8024. using. To clear it without freeing the storage, use the clearQuick()
  8025. method instead.
  8026. @see clearQuick
  8027. */
  8028. void clear() throw()
  8029. {
  8030. lock.enter();
  8031. this->setAllocatedSize (0);
  8032. numUsed = 0;
  8033. lock.exit();
  8034. }
  8035. /** Removes all elements from the set without freeing the array's allocated storage.
  8036. @see clear
  8037. */
  8038. void clearQuick() throw()
  8039. {
  8040. lock.enter();
  8041. numUsed = 0;
  8042. lock.exit();
  8043. }
  8044. /** Returns the current number of elements in the set.
  8045. */
  8046. inline int size() const throw()
  8047. {
  8048. return numUsed;
  8049. }
  8050. /** Returns one of the elements in the set.
  8051. If the index passed in is beyond the range of valid elements, this
  8052. will return zero.
  8053. If you're certain that the index will always be a valid element, you
  8054. can call getUnchecked() instead, which is faster.
  8055. @param index the index of the element being requested (0 is the first element in the set)
  8056. @see getUnchecked, getFirst, getLast
  8057. */
  8058. inline ElementType operator[] (const int index) const throw()
  8059. {
  8060. lock.enter();
  8061. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8062. ? this->elements [index]
  8063. : (ElementType) 0;
  8064. lock.exit();
  8065. return result;
  8066. }
  8067. /** Returns one of the elements in the set, without checking the index passed in.
  8068. Unlike the operator[] method, this will try to return an element without
  8069. checking that the index is within the bounds of the set, so should only
  8070. be used when you're confident that it will always be a valid index.
  8071. @param index the index of the element being requested (0 is the first element in the set)
  8072. @see operator[], getFirst, getLast
  8073. */
  8074. inline ElementType getUnchecked (const int index) const throw()
  8075. {
  8076. lock.enter();
  8077. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8078. const ElementType result = this->elements [index];
  8079. lock.exit();
  8080. return result;
  8081. }
  8082. /** Returns the first element in the set, or 0 if the set is empty.
  8083. @see operator[], getUnchecked, getLast
  8084. */
  8085. inline ElementType getFirst() const throw()
  8086. {
  8087. lock.enter();
  8088. const ElementType result = (numUsed > 0) ? this->elements [0]
  8089. : (ElementType) 0;
  8090. lock.exit();
  8091. return result;
  8092. }
  8093. /** Returns the last element in the set, or 0 if the set is empty.
  8094. @see operator[], getUnchecked, getFirst
  8095. */
  8096. inline ElementType getLast() const throw()
  8097. {
  8098. lock.enter();
  8099. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8100. : (ElementType) 0;
  8101. lock.exit();
  8102. return result;
  8103. }
  8104. /** Finds the index of the first element which matches the value passed in.
  8105. This will search the set for the given object, and return the index
  8106. of its first occurrence. If the object isn't found, the method will return -1.
  8107. @param elementToLookFor the value or object to look for
  8108. @returns the index of the object, or -1 if it's not found
  8109. */
  8110. int indexOf (const ElementType elementToLookFor) const throw()
  8111. {
  8112. lock.enter();
  8113. int start = 0;
  8114. int end = numUsed;
  8115. for (;;)
  8116. {
  8117. if (start >= end)
  8118. {
  8119. lock.exit();
  8120. return -1;
  8121. }
  8122. else if (elementToLookFor == this->elements [start])
  8123. {
  8124. lock.exit();
  8125. return start;
  8126. }
  8127. else
  8128. {
  8129. const int halfway = (start + end) >> 1;
  8130. if (halfway == start)
  8131. {
  8132. lock.exit();
  8133. return -1;
  8134. }
  8135. else if (elementToLookFor >= this->elements [halfway])
  8136. start = halfway;
  8137. else
  8138. end = halfway;
  8139. }
  8140. }
  8141. }
  8142. /** Returns true if the set contains at least one occurrence of an object.
  8143. @param elementToLookFor the value or object to look for
  8144. @returns true if the item is found
  8145. */
  8146. bool contains (const ElementType elementToLookFor) const throw()
  8147. {
  8148. lock.enter();
  8149. int start = 0;
  8150. int end = numUsed;
  8151. for (;;)
  8152. {
  8153. if (start >= end)
  8154. {
  8155. lock.exit();
  8156. return false;
  8157. }
  8158. else if (elementToLookFor == this->elements [start])
  8159. {
  8160. lock.exit();
  8161. return true;
  8162. }
  8163. else
  8164. {
  8165. const int halfway = (start + end) >> 1;
  8166. if (halfway == start)
  8167. {
  8168. lock.exit();
  8169. return false;
  8170. }
  8171. else if (elementToLookFor >= this->elements [halfway])
  8172. start = halfway;
  8173. else
  8174. end = halfway;
  8175. }
  8176. }
  8177. }
  8178. /** Adds a new element to the set, (as long as it's not already in there).
  8179. @param newElement the new object to add to the set
  8180. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8181. */
  8182. void add (const ElementType newElement) throw()
  8183. {
  8184. lock.enter();
  8185. int start = 0;
  8186. int end = numUsed;
  8187. for (;;)
  8188. {
  8189. if (start >= end)
  8190. {
  8191. jassert (start <= end);
  8192. insertInternal (start, newElement);
  8193. break;
  8194. }
  8195. else if (newElement == this->elements [start])
  8196. {
  8197. break;
  8198. }
  8199. else
  8200. {
  8201. const int halfway = (start + end) >> 1;
  8202. if (halfway == start)
  8203. {
  8204. if (newElement >= this->elements [halfway])
  8205. insertInternal (start + 1, newElement);
  8206. else
  8207. insertInternal (start, newElement);
  8208. break;
  8209. }
  8210. else if (newElement >= this->elements [halfway])
  8211. start = halfway;
  8212. else
  8213. end = halfway;
  8214. }
  8215. }
  8216. lock.exit();
  8217. }
  8218. /** Adds elements from an array to this set.
  8219. @param elementsToAdd the array of elements to add
  8220. @param numElementsToAdd how many elements are in this other array
  8221. @see add
  8222. */
  8223. void addArray (const ElementType* elementsToAdd,
  8224. int numElementsToAdd) throw()
  8225. {
  8226. lock.enter();
  8227. while (--numElementsToAdd >= 0)
  8228. add (*elementsToAdd++);
  8229. lock.exit();
  8230. }
  8231. /** Adds elements from another set to this one.
  8232. @param setToAddFrom the set from which to copy the elements
  8233. @param startIndex the first element of the other set to start copying from
  8234. @param numElementsToAdd how many elements to add from the other set. If this
  8235. value is negative or greater than the number of available elements,
  8236. all available elements will be copied.
  8237. @see add
  8238. */
  8239. template <class OtherSetType>
  8240. void addSet (const OtherSetType& setToAddFrom,
  8241. int startIndex = 0,
  8242. int numElementsToAdd = -1) throw()
  8243. {
  8244. setToAddFrom.lockSet();
  8245. lock.enter();
  8246. jassert (this != &setToAddFrom);
  8247. if (this != &setToAddFrom)
  8248. {
  8249. if (startIndex < 0)
  8250. {
  8251. jassertfalse
  8252. startIndex = 0;
  8253. }
  8254. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8255. numElementsToAdd = setToAddFrom.size() - startIndex;
  8256. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8257. }
  8258. lock.exit();
  8259. setToAddFrom.unlockSet();
  8260. }
  8261. /** Removes an element from the set.
  8262. This will remove the element at a given index.
  8263. If the index passed in is out-of-range, nothing will happen.
  8264. @param indexToRemove the index of the element to remove
  8265. @returns the element that has been removed
  8266. @see removeValue, removeRange
  8267. */
  8268. ElementType remove (const int indexToRemove) throw()
  8269. {
  8270. lock.enter();
  8271. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8272. {
  8273. --numUsed;
  8274. ElementType* const e = this->elements + indexToRemove;
  8275. ElementType const removed = *e;
  8276. const int numberToShift = numUsed - indexToRemove;
  8277. if (numberToShift > 0)
  8278. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8279. if ((numUsed << 1) < this->numAllocated)
  8280. minimiseStorageOverheads();
  8281. lock.exit();
  8282. return removed;
  8283. }
  8284. else
  8285. {
  8286. lock.exit();
  8287. return 0;
  8288. }
  8289. }
  8290. /** Removes an item from the set.
  8291. This will remove the given element from the set, if it's there.
  8292. @param valueToRemove the object to try to remove
  8293. @see remove, removeRange
  8294. */
  8295. void removeValue (const ElementType valueToRemove) throw()
  8296. {
  8297. lock.enter();
  8298. remove (indexOf (valueToRemove));
  8299. lock.exit();
  8300. }
  8301. /** Removes any elements which are also in another set.
  8302. @param otherSet the other set in which to look for elements to remove
  8303. @see removeValuesNotIn, remove, removeValue, removeRange
  8304. */
  8305. template <class OtherSetType>
  8306. void removeValuesIn (const OtherSetType& otherSet) throw()
  8307. {
  8308. otherSet.lockSet();
  8309. lock.enter();
  8310. if (this == &otherSet)
  8311. {
  8312. clear();
  8313. }
  8314. else
  8315. {
  8316. if (otherSet.size() > 0)
  8317. {
  8318. for (int i = numUsed; --i >= 0;)
  8319. if (otherSet.contains (this->elements [i]))
  8320. remove (i);
  8321. }
  8322. }
  8323. lock.exit();
  8324. otherSet.unlockSet();
  8325. }
  8326. /** Removes any elements which are not found in another set.
  8327. Only elements which occur in this other set will be retained.
  8328. @param otherSet the set in which to look for elements NOT to remove
  8329. @see removeValuesIn, remove, removeValue, removeRange
  8330. */
  8331. template <class OtherSetType>
  8332. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8333. {
  8334. otherSet.lockSet();
  8335. lock.enter();
  8336. if (this != &otherSet)
  8337. {
  8338. if (otherSet.size() <= 0)
  8339. {
  8340. clear();
  8341. }
  8342. else
  8343. {
  8344. for (int i = numUsed; --i >= 0;)
  8345. if (! otherSet.contains (this->elements [i]))
  8346. remove (i);
  8347. }
  8348. }
  8349. lock.exit();
  8350. otherSet.lockSet();
  8351. }
  8352. /** Reduces the amount of storage being used by the set.
  8353. Sets typically allocate slightly more storage than they need, and after
  8354. removing elements, they may have quite a lot of unused space allocated.
  8355. This method will reduce the amount of allocated storage to a minimum.
  8356. */
  8357. void minimiseStorageOverheads() throw()
  8358. {
  8359. lock.enter();
  8360. if (numUsed == 0)
  8361. {
  8362. this->setAllocatedSize (0);
  8363. }
  8364. else
  8365. {
  8366. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8367. if (newAllocation < this->numAllocated)
  8368. this->setAllocatedSize (newAllocation);
  8369. }
  8370. lock.exit();
  8371. }
  8372. /** Locks the set's CriticalSection.
  8373. Of course if the type of section used is a DummyCriticalSection, this won't
  8374. have any effect.
  8375. @see unlockSet
  8376. */
  8377. void lockSet() const throw()
  8378. {
  8379. lock.enter();
  8380. }
  8381. /** Unlocks the set's CriticalSection.
  8382. Of course if the type of section used is a DummyCriticalSection, this won't
  8383. have any effect.
  8384. @see lockSet
  8385. */
  8386. void unlockSet() const throw()
  8387. {
  8388. lock.exit();
  8389. }
  8390. juce_UseDebuggingNewOperator
  8391. private:
  8392. int numUsed;
  8393. TypeOfCriticalSectionToUse lock;
  8394. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8395. {
  8396. this->ensureAllocatedSize (numUsed + 1);
  8397. ElementType* const insertPos = this->elements + indexToInsertAt;
  8398. const int numberToMove = numUsed - indexToInsertAt;
  8399. if (numberToMove > 0)
  8400. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8401. *insertPos = newElement;
  8402. ++numUsed;
  8403. }
  8404. };
  8405. #if JUCE_MSVC
  8406. #pragma warning (pop)
  8407. #endif
  8408. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8409. /********* End of inlined file: juce_SortedSet.h *********/
  8410. #endif
  8411. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8412. /********* Start of inlined file: juce_SparseSet.h *********/
  8413. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8414. #define __JUCE_SPARSESET_JUCEHEADER__
  8415. /**
  8416. Holds a set of primitive values, storing them as a set of ranges.
  8417. This container acts like a simple BitArray, but can efficiently hold large
  8418. continguous ranges of values. It's quite a specialised class, mostly useful
  8419. for things like keeping the set of selected rows in a listbox.
  8420. The type used as a template paramter must be an integer type, such as int, short,
  8421. int64, etc.
  8422. */
  8423. template <class Type>
  8424. class SparseSet
  8425. {
  8426. public:
  8427. /** Creates a new empty set. */
  8428. SparseSet() throw()
  8429. {
  8430. }
  8431. /** Creates a copy of another SparseSet. */
  8432. SparseSet (const SparseSet<Type>& other) throw()
  8433. : values (other.values)
  8434. {
  8435. }
  8436. /** Destructor. */
  8437. ~SparseSet() throw()
  8438. {
  8439. }
  8440. /** Clears the set. */
  8441. void clear() throw()
  8442. {
  8443. values.clear();
  8444. }
  8445. /** Checks whether the set is empty.
  8446. This is much quicker than using (size() == 0).
  8447. */
  8448. bool isEmpty() const throw()
  8449. {
  8450. return values.size() == 0;
  8451. }
  8452. /** Returns the number of values in the set.
  8453. Because of the way the data is stored, this method can take longer if there
  8454. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8455. are any items.
  8456. */
  8457. Type size() const throw()
  8458. {
  8459. Type num = 0;
  8460. for (int i = 0; i < values.size(); i += 2)
  8461. num += values[i + 1] - values[i];
  8462. return num;
  8463. }
  8464. /** Returns one of the values in the set.
  8465. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8466. @returns the value at this index, or 0 if it's out-of-range
  8467. */
  8468. Type operator[] (int index) const throw()
  8469. {
  8470. for (int i = 0; i < values.size(); i += 2)
  8471. {
  8472. const Type s = values.getUnchecked(i);
  8473. const Type e = values.getUnchecked(i + 1);
  8474. if (index < e - s)
  8475. return s + index;
  8476. index -= e - s;
  8477. }
  8478. return (Type) 0;
  8479. }
  8480. /** Checks whether a particular value is in the set. */
  8481. bool contains (const Type valueToLookFor) const throw()
  8482. {
  8483. bool on = false;
  8484. for (int i = 0; i < values.size(); ++i)
  8485. {
  8486. if (values.getUnchecked(i) > valueToLookFor)
  8487. return on;
  8488. on = ! on;
  8489. }
  8490. return false;
  8491. }
  8492. /** Returns the number of contiguous blocks of values.
  8493. @see getRange
  8494. */
  8495. int getNumRanges() const throw()
  8496. {
  8497. return values.size() >> 1;
  8498. }
  8499. /** Returns one of the contiguous ranges of values stored.
  8500. @param rangeIndex the index of the range to look up, between 0
  8501. and (getNumRanges() - 1)
  8502. @param startValue on return, the value at the start of the range
  8503. @param numValues on return, the number of values in the range
  8504. @see getTotalRange
  8505. */
  8506. bool getRange (const int rangeIndex,
  8507. Type& startValue,
  8508. Type& numValues) const throw()
  8509. {
  8510. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8511. {
  8512. startValue = values [rangeIndex << 1];
  8513. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8514. return true;
  8515. }
  8516. return false;
  8517. }
  8518. /** Returns the lowest and highest values in the set.
  8519. @see getRange
  8520. */
  8521. bool getTotalRange (Type& lowestValue,
  8522. Type& highestValue) const throw()
  8523. {
  8524. if (values.size() > 0)
  8525. {
  8526. lowestValue = values.getUnchecked (0);
  8527. highestValue = values.getUnchecked (values.size() - 1);
  8528. return true;
  8529. }
  8530. return false;
  8531. }
  8532. /** Adds a range of contiguous values to the set.
  8533. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8534. @param firstValue the start of the range of values to add
  8535. @param numValuesToAdd how many values to add
  8536. */
  8537. void addRange (const Type firstValue,
  8538. const Type numValuesToAdd) throw()
  8539. {
  8540. jassert (numValuesToAdd >= 0);
  8541. if (numValuesToAdd > 0)
  8542. {
  8543. removeRange (firstValue, numValuesToAdd);
  8544. IntegerElementComparator<Type> sorter;
  8545. values.addSorted (sorter, firstValue);
  8546. values.addSorted (sorter, firstValue + numValuesToAdd);
  8547. simplify();
  8548. }
  8549. }
  8550. /** Removes a range of values from the set.
  8551. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8552. @param firstValue the start of the range of values to remove
  8553. @param numValuesToRemove how many values to remove
  8554. */
  8555. void removeRange (const Type firstValue,
  8556. const Type numValuesToRemove) throw()
  8557. {
  8558. jassert (numValuesToRemove >= 0);
  8559. if (numValuesToRemove >= 0
  8560. && firstValue < values.getLast())
  8561. {
  8562. const bool onAtStart = contains (firstValue - 1);
  8563. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  8564. const bool onAtEnd = contains (lastValue);
  8565. for (int i = values.size(); --i >= 0;)
  8566. {
  8567. if (values.getUnchecked(i) <= lastValue)
  8568. {
  8569. while (values.getUnchecked(i) >= firstValue)
  8570. {
  8571. values.remove (i);
  8572. if (--i < 0)
  8573. break;
  8574. }
  8575. break;
  8576. }
  8577. }
  8578. IntegerElementComparator<Type> sorter;
  8579. if (onAtStart)
  8580. values.addSorted (sorter, firstValue);
  8581. if (onAtEnd)
  8582. values.addSorted (sorter, lastValue);
  8583. simplify();
  8584. }
  8585. }
  8586. /** Does an XOR of the values in a given range. */
  8587. void invertRange (const Type firstValue,
  8588. const Type numValues)
  8589. {
  8590. SparseSet newItems;
  8591. newItems.addRange (firstValue, numValues);
  8592. int i;
  8593. for (i = getNumRanges(); --i >= 0;)
  8594. {
  8595. const int start = values [i << 1];
  8596. const int end = values [(i << 1) + 1];
  8597. newItems.removeRange (start, end);
  8598. }
  8599. removeRange (firstValue, numValues);
  8600. for (i = newItems.getNumRanges(); --i >= 0;)
  8601. {
  8602. const int start = newItems.values [i << 1];
  8603. const int end = newItems.values [(i << 1) + 1];
  8604. addRange (start, end);
  8605. }
  8606. }
  8607. /** Checks whether any part of a given range overlaps any part of this one. */
  8608. bool overlapsRange (const Type firstValue,
  8609. const Type numValues) throw()
  8610. {
  8611. jassert (numValues >= 0);
  8612. if (numValues > 0)
  8613. {
  8614. for (int i = getNumRanges(); --i >= 0;)
  8615. {
  8616. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8617. return false;
  8618. if (firstValue + numValues > values.getUnchecked (i << 1))
  8619. return true;
  8620. }
  8621. }
  8622. return false;
  8623. }
  8624. /** Checks whether the whole of a given range is contained within this one. */
  8625. bool containsRange (const Type firstValue,
  8626. const Type numValues) throw()
  8627. {
  8628. jassert (numValues >= 0);
  8629. if (numValues > 0)
  8630. {
  8631. for (int i = getNumRanges(); --i >= 0;)
  8632. {
  8633. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8634. return false;
  8635. if (firstValue >= values.getUnchecked (i << 1)
  8636. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8637. return true;
  8638. }
  8639. }
  8640. return false;
  8641. }
  8642. bool operator== (const SparseSet<Type>& other) throw()
  8643. {
  8644. return values == other.values;
  8645. }
  8646. bool operator!= (const SparseSet<Type>& other) throw()
  8647. {
  8648. return values != other.values;
  8649. }
  8650. juce_UseDebuggingNewOperator
  8651. private:
  8652. // alternating start/end values of ranges of values that are present.
  8653. Array<Type> values;
  8654. void simplify() throw()
  8655. {
  8656. jassert ((values.size() & 1) == 0);
  8657. for (int i = values.size(); --i > 0;)
  8658. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8659. values.removeRange (i - 1, 2);
  8660. }
  8661. };
  8662. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8663. /********* End of inlined file: juce_SparseSet.h *********/
  8664. #endif
  8665. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  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_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9515. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9516. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9517. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9518. /** Wraps another input stream, and reads from it using an intermediate buffer
  9519. If you're using an input stream such as a file input stream, and making lots of
  9520. small read accesses to it, it's probably sensible to wrap it in one of these,
  9521. so that the source stream gets accessed in larger chunk sizes, meaning less
  9522. work for the underlying stream.
  9523. */
  9524. class JUCE_API BufferedInputStream : public InputStream
  9525. {
  9526. public:
  9527. /** Creates a BufferedInputStream from an input source.
  9528. @param sourceStream the source stream to read from
  9529. @param bufferSize the size of reservoir to use to buffer the source
  9530. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9531. deleted by this object when it is itself deleted.
  9532. */
  9533. BufferedInputStream (InputStream* const sourceStream,
  9534. const int bufferSize,
  9535. const bool deleteSourceWhenDestroyed) throw();
  9536. /** Destructor.
  9537. This may also delete the source stream, if that option was chosen when the
  9538. buffered stream was created.
  9539. */
  9540. ~BufferedInputStream() throw();
  9541. int64 getTotalLength();
  9542. int64 getPosition();
  9543. bool setPosition (int64 newPosition);
  9544. int read (void* destBuffer, int maxBytesToRead);
  9545. const String readString();
  9546. bool isExhausted();
  9547. juce_UseDebuggingNewOperator
  9548. private:
  9549. InputStream* const source;
  9550. const bool deleteSourceWhenDestroyed;
  9551. int bufferSize;
  9552. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9553. char* buffer;
  9554. void ensureBuffered();
  9555. BufferedInputStream (const BufferedInputStream&);
  9556. const BufferedInputStream& operator= (const BufferedInputStream&);
  9557. };
  9558. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9559. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9560. #endif
  9561. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9562. /********* Start of inlined file: juce_FileInputSource.h *********/
  9563. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9564. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9565. /********* Start of inlined file: juce_InputSource.h *********/
  9566. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9567. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9568. /**
  9569. A lightweight object that can create a stream to read some kind of resource.
  9570. This may be used to refer to a file, or some other kind of source, allowing a
  9571. caller to create an input stream that can read from it when required.
  9572. @see FileInputSource
  9573. */
  9574. class JUCE_API InputSource
  9575. {
  9576. public:
  9577. InputSource() throw() {}
  9578. /** Destructor. */
  9579. virtual ~InputSource() {}
  9580. /** Returns a new InputStream to read this item.
  9581. @returns an inputstream that the caller will delete, or 0 if
  9582. the filename isn't found.
  9583. */
  9584. virtual InputStream* createInputStream() = 0;
  9585. /** Returns a new InputStream to read an item, relative.
  9586. @param relatedItemPath the relative pathname of the resource that is required
  9587. @returns an inputstream that the caller will delete, or 0 if
  9588. the item isn't found.
  9589. */
  9590. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9591. /** Returns a hash code that uniquely represents this item.
  9592. */
  9593. virtual int64 hashCode() const = 0;
  9594. juce_UseDebuggingNewOperator
  9595. };
  9596. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9597. /********* End of inlined file: juce_InputSource.h *********/
  9598. /**
  9599. A type of InputSource that represents a normal file.
  9600. @see InputSource
  9601. */
  9602. class JUCE_API FileInputSource : public InputSource
  9603. {
  9604. public:
  9605. FileInputSource (const File& file) throw();
  9606. ~FileInputSource();
  9607. InputStream* createInputStream();
  9608. InputStream* createInputStreamFor (const String& relatedItemPath);
  9609. int64 hashCode() const;
  9610. juce_UseDebuggingNewOperator
  9611. private:
  9612. const File file;
  9613. FileInputSource (const FileInputSource&);
  9614. const FileInputSource& operator= (const FileInputSource&);
  9615. };
  9616. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9617. /********* End of inlined file: juce_FileInputSource.h *********/
  9618. #endif
  9619. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9620. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9621. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9622. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9623. /**
  9624. A stream which uses zlib to compress the data written into it.
  9625. @see GZIPDecompressorInputStream
  9626. */
  9627. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9628. {
  9629. public:
  9630. /** Creates a compression stream.
  9631. @param destStream the stream into which the compressed data should
  9632. be written
  9633. @param compressionLevel how much to compress the data, between 1 and 9, where
  9634. 1 is the fastest/lowest compression, and 9 is the
  9635. slowest/highest compression. Any value outside this range
  9636. indicates that a default compression level should be used.
  9637. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9638. this stream is destroyed
  9639. @param noWrap this is used internally by the ZipFile class
  9640. and should be ignored by user applications
  9641. */
  9642. GZIPCompressorOutputStream (OutputStream* const destStream,
  9643. int compressionLevel = 0,
  9644. const bool deleteDestStreamWhenDestroyed = false,
  9645. const bool noWrap = false);
  9646. /** Destructor. */
  9647. ~GZIPCompressorOutputStream();
  9648. void flush();
  9649. int64 getPosition();
  9650. bool setPosition (int64 newPosition);
  9651. bool write (const void* destBuffer, int howMany);
  9652. juce_UseDebuggingNewOperator
  9653. private:
  9654. OutputStream* const destStream;
  9655. const bool deleteDestStream;
  9656. uint8* buffer;
  9657. void* helper;
  9658. bool doNextBlock();
  9659. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9660. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9661. };
  9662. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9663. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9664. #endif
  9665. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9666. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9667. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9668. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9669. /**
  9670. This stream will decompress a source-stream using zlib.
  9671. Tip: if you're reading lots of small items from one of these streams, you
  9672. can increase the performance enormously by passing it through a
  9673. BufferedInputStream, so that it has to read larger blocks less often.
  9674. @see GZIPCompressorOutputStream
  9675. */
  9676. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9677. {
  9678. public:
  9679. /** Creates a decompressor stream.
  9680. @param sourceStream the stream to read from
  9681. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9682. when this object is destroyed
  9683. @param noWrap this is used internally by the ZipFile class
  9684. and should be ignored by user applications
  9685. @param uncompressedStreamLength if the creator knows the length that the
  9686. uncompressed stream will be, then it can supply this
  9687. value, which will be returned by getTotalLength()
  9688. */
  9689. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9690. const bool deleteSourceWhenDestroyed,
  9691. const bool noWrap = false,
  9692. const int64 uncompressedStreamLength = -1);
  9693. /** Destructor. */
  9694. ~GZIPDecompressorInputStream();
  9695. int64 getPosition();
  9696. bool setPosition (int64 pos);
  9697. int64 getTotalLength();
  9698. bool isExhausted();
  9699. int read (void* destBuffer, int maxBytesToRead);
  9700. juce_UseDebuggingNewOperator
  9701. private:
  9702. InputStream* const sourceStream;
  9703. const int64 uncompressedStreamLength;
  9704. const bool deleteSourceWhenDestroyed, noWrap;
  9705. bool isEof;
  9706. int activeBufferSize;
  9707. int64 originalSourcePos, currentPos;
  9708. uint8* buffer;
  9709. void* helper;
  9710. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9711. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9712. };
  9713. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9714. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9715. #endif
  9716. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9717. #endif
  9718. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9719. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9720. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9721. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9722. /**
  9723. Allows a block of data and to be accessed as a stream.
  9724. This can either be used to refer to a shared block of memory, or can make its
  9725. own internal copy of the data when the MemoryInputStream is created.
  9726. */
  9727. class JUCE_API MemoryInputStream : public InputStream
  9728. {
  9729. public:
  9730. /** Creates a MemoryInputStream.
  9731. @param sourceData the block of data to use as the stream's source
  9732. @param sourceDataSize the number of bytes in the source data block
  9733. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9734. the source data, so this data shouldn't be changed
  9735. for the lifetime of the stream; if this parameter is
  9736. true, the stream will make its own copy of the
  9737. data and use that.
  9738. */
  9739. MemoryInputStream (const void* const sourceData,
  9740. const int sourceDataSize,
  9741. const bool keepInternalCopyOfData) throw();
  9742. /** Destructor. */
  9743. ~MemoryInputStream() throw();
  9744. int64 getPosition();
  9745. bool setPosition (int64 pos);
  9746. int64 getTotalLength();
  9747. bool isExhausted();
  9748. int read (void* destBuffer, int maxBytesToRead);
  9749. juce_UseDebuggingNewOperator
  9750. private:
  9751. const char* data;
  9752. int dataSize, position;
  9753. MemoryBlock internalCopy;
  9754. };
  9755. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9756. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9757. #endif
  9758. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9759. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9760. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9761. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9762. /** Writes data to an internal memory buffer, which grows as required.
  9763. The data that was written into the stream can then be accessed later as
  9764. a contiguous block of memory.
  9765. */
  9766. class JUCE_API MemoryOutputStream : public OutputStream
  9767. {
  9768. public:
  9769. /** Creates a memory stream ready for writing into.
  9770. @param initialSize the intial amount of space to allocate for writing into
  9771. @param granularity the increments by which the internal storage will be increased
  9772. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9773. place that the data gets stored. If it's zero, the stream
  9774. will allocate its own storage internally, which you can
  9775. access using getData() and getDataSize()
  9776. */
  9777. MemoryOutputStream (const int initialSize = 256,
  9778. const int granularity = 256,
  9779. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9780. /** Destructor.
  9781. This will free any data that was written to it.
  9782. */
  9783. ~MemoryOutputStream() throw();
  9784. /** Returns a pointer to the data that has been written to the stream.
  9785. @see getDataSize
  9786. */
  9787. const char* getData() throw();
  9788. /** Returns the number of bytes of data that have been written to the stream.
  9789. @see getData
  9790. */
  9791. int getDataSize() const throw();
  9792. /** Resets the stream, clearing any data that has been written to it so far. */
  9793. void reset() throw();
  9794. void flush();
  9795. bool write (const void* buffer, int howMany);
  9796. int64 getPosition();
  9797. bool setPosition (int64 newPosition);
  9798. juce_UseDebuggingNewOperator
  9799. private:
  9800. MemoryBlock* data;
  9801. int position, size, blockSize;
  9802. bool ownsMemoryBlock;
  9803. };
  9804. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9805. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9806. #endif
  9807. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9808. /********* Start of inlined file: juce_SubregionStream.h *********/
  9809. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9810. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9811. /** Wraps another input stream, and reads from a specific part of it.
  9812. This lets you take a subsection of a stream and present it as an entire
  9813. stream in its own right.
  9814. */
  9815. class JUCE_API SubregionStream : public InputStream
  9816. {
  9817. public:
  9818. /** Creates a SubregionStream from an input source.
  9819. @param sourceStream the source stream to read from
  9820. @param startPositionInSourceStream this is the position in the source stream that
  9821. corresponds to position 0 in this stream
  9822. @param lengthOfSourceStream this specifies the maximum number of bytes
  9823. from the source stream that will be passed through
  9824. by this stream. When the position of this stream
  9825. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9826. If the length passed in here is greater than the length
  9827. of the source stream (as returned by getTotalLength()),
  9828. then the smaller value will be used.
  9829. Passing a negative value for this parameter means it
  9830. will keep reading until the source's end-of-stream.
  9831. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9832. deleted by this object when it is itself deleted.
  9833. */
  9834. SubregionStream (InputStream* const sourceStream,
  9835. const int64 startPositionInSourceStream,
  9836. const int64 lengthOfSourceStream,
  9837. const bool deleteSourceWhenDestroyed) throw();
  9838. /** Destructor.
  9839. This may also delete the source stream, if that option was chosen when the
  9840. buffered stream was created.
  9841. */
  9842. ~SubregionStream() throw();
  9843. int64 getTotalLength();
  9844. int64 getPosition();
  9845. bool setPosition (int64 newPosition);
  9846. int read (void* destBuffer, int maxBytesToRead);
  9847. bool isExhausted();
  9848. juce_UseDebuggingNewOperator
  9849. private:
  9850. InputStream* const source;
  9851. const bool deleteSourceWhenDestroyed;
  9852. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9853. SubregionStream (const SubregionStream&);
  9854. const SubregionStream& operator= (const SubregionStream&);
  9855. };
  9856. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9857. /********* End of inlined file: juce_SubregionStream.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. #endif
  9953. #if JUCE_WIN32 || DOXYGEN
  9954. // Some registry helper functions:
  9955. /** WIN32 ONLY - Returns a string from the registry.
  9956. The path is a string for the entire path of a value in the registry,
  9957. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9958. */
  9959. static const String getRegistryValue (const String& regValuePath,
  9960. const String& defaultValue = String::empty);
  9961. /** WIN32 ONLY - Sets a registry value as a string.
  9962. This will take care of creating any groups needed to get to the given
  9963. registry value.
  9964. */
  9965. static void setRegistryValue (const String& regValuePath,
  9966. const String& value);
  9967. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9968. static bool registryValueExists (const String& regValuePath);
  9969. /** WIN32 ONLY - Deletes a registry value. */
  9970. static void deleteRegistryValue (const String& regValuePath);
  9971. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9972. static void deleteRegistryKey (const String& regKeyPath);
  9973. /** WIN32 ONLY - Creates a file association in the registry.
  9974. This lets you set the exe that should be launched by a given file extension.
  9975. @param fileExtension the file extension to associate, including the
  9976. initial dot, e.g. ".txt"
  9977. @param symbolicDescription a space-free short token to identify the file type
  9978. @param fullDescription a human-readable description of the file type
  9979. @param targetExecutable the executable that should be launched
  9980. @param iconResourceNumber the icon that gets displayed for the file type will be
  9981. found by looking up this resource number in the
  9982. executable. Pass 0 here to not use an icon
  9983. */
  9984. static void registerFileAssociation (const String& fileExtension,
  9985. const String& symbolicDescription,
  9986. const String& fullDescription,
  9987. const File& targetExecutable,
  9988. int iconResourceNumber);
  9989. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9990. In a normal Juce application this will be set to the module handle
  9991. of the application executable.
  9992. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9993. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9994. to set the correct module handle in your DllMain() function, because
  9995. the win32 system relies on the correct instance handle when opening windows.
  9996. */
  9997. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9998. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9999. @see getCurrentModuleInstanceHandle()
  10000. */
  10001. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10002. /** WIN32 ONLY - Gets the command-line params as a string.
  10003. This is needed to avoid unicode problems with the argc type params.
  10004. */
  10005. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  10006. #endif
  10007. /** Clears the floating point unit's flags.
  10008. Only has an effect under win32, currently.
  10009. */
  10010. static void fpuReset();
  10011. #if JUCE_LINUX || JUCE_WIN32
  10012. /** Loads a dynamically-linked library into the process's address space.
  10013. @param pathOrFilename the platform-dependent name and search path
  10014. @returns a handle which can be used by getProcedureEntryPoint(), or
  10015. zero if it fails.
  10016. @see freeDynamicLibrary, getProcedureEntryPoint
  10017. */
  10018. static void* loadDynamicLibrary (const String& pathOrFilename);
  10019. /** Frees a dynamically-linked library.
  10020. @param libraryHandle a handle created by loadDynamicLibrary
  10021. @see loadDynamicLibrary, getProcedureEntryPoint
  10022. */
  10023. static void freeDynamicLibrary (void* libraryHandle);
  10024. /** Finds a procedure call in a dynamically-linked library.
  10025. @param libraryHandle a library handle returned by loadDynamicLibrary
  10026. @param procedureName the name of the procedure call to try to load
  10027. @returns a pointer to the function if found, or 0 if it fails
  10028. @see loadDynamicLibrary
  10029. */
  10030. static void* getProcedureEntryPoint (void* libraryHandle,
  10031. const String& procedureName);
  10032. #endif
  10033. #if JUCE_LINUX || DOXYGEN
  10034. #endif
  10035. };
  10036. #if JUCE_MAC
  10037. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10038. using RAII.
  10039. */
  10040. class ScopedAutoReleasePool
  10041. {
  10042. public:
  10043. ScopedAutoReleasePool();
  10044. ~ScopedAutoReleasePool();
  10045. private:
  10046. void* pool;
  10047. };
  10048. /**
  10049. A wrapper class for picking up events from an Apple IR remote control device.
  10050. To use it, just create a subclass of this class, implementing the buttonPressed()
  10051. callback, then call start() and stop() to start or stop receiving events.
  10052. */
  10053. class JUCE_API AppleRemoteDevice
  10054. {
  10055. public:
  10056. AppleRemoteDevice();
  10057. virtual ~AppleRemoteDevice();
  10058. /** The set of buttons that may be pressed.
  10059. @see buttonPressed
  10060. */
  10061. enum ButtonType
  10062. {
  10063. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10064. playButton, /**< The play button. */
  10065. plusButton, /**< The plus or volume-up button. */
  10066. minusButton, /**< The minus or volume-down button. */
  10067. rightButton, /**< The right button (if it's held for a short time). */
  10068. leftButton, /**< The left button (if it's held for a short time). */
  10069. rightButton_Long, /**< The right button (if it's held for a long time). */
  10070. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10071. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10072. playButtonSleepMode,
  10073. switched
  10074. };
  10075. /** Override this method to receive the callback about a button press.
  10076. The callback will happen on the application's message thread.
  10077. Some buttons trigger matching up and down events, in which the isDown parameter
  10078. will be true and then false. Others only send a single event when the
  10079. button is pressed.
  10080. */
  10081. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10082. /** Starts the device running and responding to events.
  10083. Returns true if it managed to open the device.
  10084. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10085. and will not be available to any other part of the system. If
  10086. false, it will be shared with other apps.
  10087. @see stop
  10088. */
  10089. bool start (const bool inExclusiveMode) throw();
  10090. /** Stops the device running.
  10091. @see start
  10092. */
  10093. void stop() throw();
  10094. /** Returns true if the device has been started successfully.
  10095. */
  10096. bool isActive() const throw();
  10097. /** Returns the ID number of the remote, if it has sent one.
  10098. */
  10099. int getRemoteId() const throw() { return remoteId; }
  10100. juce_UseDebuggingNewOperator
  10101. /** @internal */
  10102. void handleCallbackInternal();
  10103. private:
  10104. void* device;
  10105. void* queue;
  10106. int remoteId;
  10107. bool open (const bool openInExclusiveMode) throw();
  10108. };
  10109. #endif
  10110. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10111. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10112. #endif
  10113. #ifndef __JUCE_UUID_JUCEHEADER__
  10114. /********* Start of inlined file: juce_Uuid.h *********/
  10115. #ifndef __JUCE_UUID_JUCEHEADER__
  10116. #define __JUCE_UUID_JUCEHEADER__
  10117. /**
  10118. A universally unique 128-bit identifier.
  10119. This class generates very random unique numbers based on the system time
  10120. and MAC addresses if any are available. It's extremely unlikely that two identical
  10121. UUIDs would ever be created by chance.
  10122. The class includes methods for saving the ID as a string or as raw binary data.
  10123. */
  10124. class JUCE_API Uuid
  10125. {
  10126. public:
  10127. /** Creates a new unique ID. */
  10128. Uuid();
  10129. /** Destructor. */
  10130. ~Uuid() throw();
  10131. /** Creates a copy of another UUID. */
  10132. Uuid (const Uuid& other);
  10133. /** Copies another UUID. */
  10134. Uuid& operator= (const Uuid& other);
  10135. /** Returns true if the ID is zero. */
  10136. bool isNull() const throw();
  10137. /** Compares two UUIDs. */
  10138. bool operator== (const Uuid& other) const;
  10139. /** Compares two UUIDs. */
  10140. bool operator!= (const Uuid& other) const;
  10141. /** Returns a stringified version of this UUID.
  10142. A Uuid object can later be reconstructed from this string using operator= or
  10143. the constructor that takes a string parameter.
  10144. @returns a 32 character hex string.
  10145. */
  10146. const String toString() const;
  10147. /** Creates an ID from an encoded string version.
  10148. @see toString
  10149. */
  10150. Uuid (const String& uuidString);
  10151. /** Copies from a stringified UUID.
  10152. The string passed in should be one that was created with the toString() method.
  10153. */
  10154. Uuid& operator= (const String& uuidString);
  10155. /** Returns a pointer to the internal binary representation of the ID.
  10156. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10157. the constructor or operator= method that takes an array of uint8s.
  10158. */
  10159. const uint8* getRawData() const throw() { return value.asBytes; }
  10160. /** Creates a UUID from a 16-byte array.
  10161. @see getRawData
  10162. */
  10163. Uuid (const uint8* const rawData);
  10164. /** Sets this UUID from 16-bytes of raw data. */
  10165. Uuid& operator= (const uint8* const rawData);
  10166. juce_UseDebuggingNewOperator
  10167. private:
  10168. union
  10169. {
  10170. uint8 asBytes [16];
  10171. int asInt[4];
  10172. int64 asInt64[2];
  10173. } value;
  10174. };
  10175. #endif // __JUCE_UUID_JUCEHEADER__
  10176. /********* End of inlined file: juce_Uuid.h *********/
  10177. #endif
  10178. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10179. /********* Start of inlined file: juce_ZipFile.h *********/
  10180. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10181. #define __JUCE_ZIPFILE_JUCEHEADER__
  10182. /**
  10183. Decodes a ZIP file from a stream.
  10184. This can enumerate the items in a ZIP file and can create suitable stream objects
  10185. to read each one.
  10186. */
  10187. class JUCE_API ZipFile
  10188. {
  10189. public:
  10190. /** Creates a ZipFile for a given stream.
  10191. @param inputStream the stream to read from
  10192. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10193. will be deleted when this ZipFile object is deleted
  10194. */
  10195. ZipFile (InputStream* const inputStream,
  10196. const bool deleteStreamWhenDestroyed) throw();
  10197. /** Creates a ZipFile based for a file. */
  10198. ZipFile (const File& file);
  10199. /** Creates a ZipFile for an input source.
  10200. The inputSource object will be owned by the zip file, which will delete
  10201. it later when not needed.
  10202. */
  10203. ZipFile (InputSource* const inputSource);
  10204. /** Destructor. */
  10205. ~ZipFile() throw();
  10206. /**
  10207. Contains information about one of the entries in a ZipFile.
  10208. @see ZipFile::getEntry
  10209. */
  10210. struct ZipEntry
  10211. {
  10212. /** The name of the file, which may also include a partial pathname. */
  10213. String filename;
  10214. /** The file's original size. */
  10215. unsigned int uncompressedSize;
  10216. /** The last time the file was modified. */
  10217. Time fileTime;
  10218. };
  10219. /** Returns the number of items in the zip file. */
  10220. int getNumEntries() const throw();
  10221. /** Returns a structure that describes one of the entries in the zip file.
  10222. This may return zero if the index is out of range.
  10223. @see ZipFile::ZipEntry
  10224. */
  10225. const ZipEntry* getEntry (const int index) const throw();
  10226. /** Returns the index of the first entry with a given filename.
  10227. This uses a case-sensitive comparison to look for a filename in the
  10228. list of entries. It might return -1 if no match is found.
  10229. @see ZipFile::ZipEntry
  10230. */
  10231. int getIndexOfFileName (const String& fileName) const throw();
  10232. /** Returns a structure that describes one of the entries in the zip file.
  10233. This uses a case-sensitive comparison to look for a filename in the
  10234. list of entries. It might return 0 if no match is found.
  10235. @see ZipFile::ZipEntry
  10236. */
  10237. const ZipEntry* getEntry (const String& fileName) const throw();
  10238. /** Sorts the list of entries, based on the filename.
  10239. */
  10240. void sortEntriesByFilename();
  10241. /** Creates a stream that can read from one of the zip file's entries.
  10242. The stream that is returned must be deleted by the caller (and
  10243. zero might be returned if a stream can't be opened for some reason).
  10244. The stream must not be used after the ZipFile object that created
  10245. has been deleted.
  10246. */
  10247. InputStream* createStreamForEntry (const int index);
  10248. /** Uncompresses all of the files in the zip file.
  10249. This will expand all the entires into a target directory. The relative
  10250. paths of the entries are used.
  10251. @param targetDirectory the root folder to uncompress to
  10252. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10253. */
  10254. void uncompressTo (const File& targetDirectory,
  10255. const bool shouldOverwriteFiles = true);
  10256. juce_UseDebuggingNewOperator
  10257. private:
  10258. VoidArray entries;
  10259. friend class ZipInputStream;
  10260. CriticalSection lock;
  10261. InputStream* inputStream;
  10262. InputSource* inputSource;
  10263. bool deleteStreamWhenDestroyed;
  10264. int numEntries, centralRecStart;
  10265. #ifdef JUCE_DEBUG
  10266. int numOpenStreams;
  10267. #endif
  10268. void init();
  10269. int findEndOfZipEntryTable (InputStream* in);
  10270. ZipFile (const ZipFile&);
  10271. const ZipFile& operator= (const ZipFile&);
  10272. };
  10273. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10274. /********* End of inlined file: juce_ZipFile.h *********/
  10275. #endif
  10276. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10277. #endif
  10278. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10279. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10280. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10281. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10282. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10283. string into a localised version using the LocalisedStrings class.
  10284. @see LocalisedStrings
  10285. */
  10286. #define TRANS(stringLiteral) \
  10287. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10288. /**
  10289. Used to convert strings to localised foreign-language versions.
  10290. This is basically a look-up table of strings and their translated equivalents.
  10291. It can be loaded from a text file, so that you can supply a set of localised
  10292. versions of strings that you use in your app.
  10293. To use it in your code, simply call the translate() method on each string that
  10294. might have foreign versions, and if none is found, the method will just return
  10295. the original string.
  10296. The translation file should start with some lines specifying a description of
  10297. the language it contains, and also a list of ISO country codes where it might
  10298. be appropriate to use the file. After that, each line of the file should contain
  10299. a pair of quoted strings with an '=' sign.
  10300. E.g. for a french translation, the file might be:
  10301. @code
  10302. language: French
  10303. countries: fr be mc ch lu
  10304. "hello" = "bonjour"
  10305. "goodbye" = "au revoir"
  10306. @endcode
  10307. If the strings need to contain a quote character, they can use '\"' instead, and
  10308. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10309. (you can use this to add comments).
  10310. Note that this is a singleton class, so don't create or destroy the object directly.
  10311. There's also a TRANS(text) macro defined to make it easy to use the this.
  10312. E.g. @code
  10313. printSomething (TRANS("hello"));
  10314. @endcode
  10315. This macro is used in the Juce classes themselves, so your application has a chance to
  10316. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10317. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10318. code).
  10319. */
  10320. class JUCE_API LocalisedStrings
  10321. {
  10322. public:
  10323. /** Creates a set of translations from the text of a translation file.
  10324. When you create one of these, you can call setCurrentMappings() to make it
  10325. the set of mappings that the system's using.
  10326. */
  10327. LocalisedStrings (const String& fileContents) throw();
  10328. /** Creates a set of translations from a file.
  10329. When you create one of these, you can call setCurrentMappings() to make it
  10330. the set of mappings that the system's using.
  10331. */
  10332. LocalisedStrings (const File& fileToLoad) throw();
  10333. /** Destructor. */
  10334. ~LocalisedStrings() throw();
  10335. /** Selects the current set of mappings to be used by the system.
  10336. The object you pass in will be automatically deleted when no longer needed, so
  10337. don't keep a pointer to it. You can also pass in zero to remove the current
  10338. mappings.
  10339. See also the TRANS() macro, which uses the current set to do its translation.
  10340. @see translateWithCurrentMappings
  10341. */
  10342. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10343. /** Returns the currently selected set of mappings.
  10344. This is the object that was last passed to setCurrentMappings(). It may
  10345. be 0 if none has been created.
  10346. */
  10347. static LocalisedStrings* getCurrentMappings() throw();
  10348. /** Tries to translate a string using the currently selected set of mappings.
  10349. If no mapping has been set, or if the mapping doesn't contain a translation
  10350. for the string, this will just return the original string.
  10351. See also the TRANS() macro, which uses this method to do its translation.
  10352. @see setCurrentMappings, getCurrentMappings
  10353. */
  10354. static const String translateWithCurrentMappings (const String& text) throw();
  10355. /** Tries to translate a string using the currently selected set of mappings.
  10356. If no mapping has been set, or if the mapping doesn't contain a translation
  10357. for the string, this will just return the original string.
  10358. See also the TRANS() macro, which uses this method to do its translation.
  10359. @see setCurrentMappings, getCurrentMappings
  10360. */
  10361. static const String translateWithCurrentMappings (const char* text) throw();
  10362. /** Attempts to look up a string and return its localised version.
  10363. If the string isn't found in the list, the original string will be returned.
  10364. */
  10365. const String translate (const String& text) const throw();
  10366. /** Returns the name of the language specified in the translation file.
  10367. This is specified in the file using a line starting with "language:", e.g.
  10368. @code
  10369. language: german
  10370. @endcode
  10371. */
  10372. const String getLanguageName() const throw() { return languageName; }
  10373. /** Returns the list of suitable country codes listed in the translation file.
  10374. These is specified in the file using a line starting with "countries:", e.g.
  10375. @code
  10376. countries: fr be mc ch lu
  10377. @endcode
  10378. The country codes are supposed to be 2-character ISO complient codes.
  10379. */
  10380. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10381. /** Indicates whether to use a case-insensitive search when looking up a string.
  10382. This defaults to true.
  10383. */
  10384. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  10385. juce_UseDebuggingNewOperator
  10386. private:
  10387. String languageName;
  10388. StringArray countryCodes;
  10389. StringPairArray translations;
  10390. void loadFromText (const String& fileContents) throw();
  10391. };
  10392. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10393. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10394. #endif
  10395. #ifndef __JUCE_STRING_JUCEHEADER__
  10396. #endif
  10397. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10398. #endif
  10399. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10400. #endif
  10401. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10402. /********* Start of inlined file: juce_XmlDocument.h *********/
  10403. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10404. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10405. /**
  10406. Parses a text-based XML document and creates an XmlElement object from it.
  10407. The parser will parse DTDs to load external entities but won't
  10408. check the document for validity against the DTD.
  10409. e.g.
  10410. @code
  10411. XmlDocument myDocument (File ("myfile.xml"));
  10412. XmlElement* mainElement = myDocument.getDocumentElement();
  10413. if (mainElement == 0)
  10414. {
  10415. String error = myDocument.getLastParseError();
  10416. }
  10417. else
  10418. {
  10419. ..use the element
  10420. }
  10421. @endcode
  10422. @see XmlElement
  10423. */
  10424. class JUCE_API XmlDocument
  10425. {
  10426. public:
  10427. /** Creates an XmlDocument from the xml text.
  10428. The text doesn't actually get parsed until the getDocumentElement() method is
  10429. called.
  10430. */
  10431. XmlDocument (const String& documentText) throw();
  10432. /** Creates an XmlDocument from a file.
  10433. The text doesn't actually get parsed until the getDocumentElement() method is
  10434. called.
  10435. */
  10436. XmlDocument (const File& file);
  10437. /** Destructor. */
  10438. ~XmlDocument() throw();
  10439. /** Creates an XmlElement object to represent the main document node.
  10440. This method will do the actual parsing of the text, and if there's a
  10441. parse error, it may returns 0 (and you can find out the error using
  10442. the getLastParseError() method).
  10443. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10444. first section of the file, and will only
  10445. return the outer document element - this
  10446. allows quick checking of large files to
  10447. see if they contain the correct type of
  10448. tag, without having to parse the entire file
  10449. @returns a new XmlElement which the caller will need to delete, or null if
  10450. there was an error.
  10451. @see getLastParseError
  10452. */
  10453. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10454. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10455. @returns the error, or an empty string if there was no error.
  10456. */
  10457. const String& getLastParseError() const throw();
  10458. /** Sets an input source object to use for parsing documents that reference external entities.
  10459. If the document has been created from a file, this probably won't be needed, but
  10460. if you're parsing some text and there might be a DTD that references external
  10461. files, you may need to create a custom input source that can retrieve the
  10462. other files it needs.
  10463. The object that is passed-in will be deleted automatically when no longer needed.
  10464. @see InputSource
  10465. */
  10466. void setInputSource (InputSource* const newSource) throw();
  10467. /** Sets a flag to change the treatment of empty text elements.
  10468. If this is true (the default state), then any text elements that contain only
  10469. whitespace characters will be ingored during parsing. If you need to catch
  10470. whitespace-only text, then you should set this to false before calling the
  10471. getDocumentElement() method.
  10472. */
  10473. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  10474. juce_UseDebuggingNewOperator
  10475. private:
  10476. String originalText;
  10477. const tchar* input;
  10478. bool outOfData, errorOccurred;
  10479. bool identifierLookupTable [128];
  10480. String lastError, dtdText;
  10481. StringArray tokenisedDTD;
  10482. bool needToLoadDTD, ignoreEmptyTextElements;
  10483. InputSource* inputSource;
  10484. void setLastError (const String& desc, const bool carryOn) throw();
  10485. void skipHeader() throw();
  10486. void skipNextWhiteSpace() throw();
  10487. tchar readNextChar() throw();
  10488. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10489. void readChildElements (XmlElement* parent) throw();
  10490. int findNextTokenLength() throw();
  10491. void readQuotedString (String& result) throw();
  10492. void readEntity (String& result) throw();
  10493. const String getFileContents (const String& filename) const;
  10494. const String expandEntity (const String& entity);
  10495. const String expandExternalEntity (const String& entity);
  10496. const String getParameterEntity (const String& entity);
  10497. };
  10498. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10499. /********* End of inlined file: juce_XmlDocument.h *********/
  10500. #endif
  10501. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10502. #endif
  10503. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10504. #endif
  10505. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10506. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10507. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10508. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10509. /**
  10510. Acts as a critical section which processes can use to block each other.
  10511. @see CriticalSection
  10512. */
  10513. class JUCE_API InterProcessLock
  10514. {
  10515. public:
  10516. /** Creates a lock object.
  10517. @param name a name that processes will use to identify this lock object
  10518. */
  10519. InterProcessLock (const String& name) throw();
  10520. /** Destructor.
  10521. This will also release the lock if it's currently held by this process.
  10522. */
  10523. ~InterProcessLock() throw();
  10524. /** Attempts to lock the critical section.
  10525. @param timeOutMillisecs how many milliseconds to wait if the lock
  10526. is already held by another process - a value of
  10527. 0 will return immediately, negative values will wait
  10528. forever
  10529. @returns true if the lock could be gained within the timeout period, or
  10530. false if the timeout expired.
  10531. */
  10532. bool enter (int timeOutMillisecs = -1) throw();
  10533. /** Releases the lock if it's currently held by this process.
  10534. */
  10535. void exit() throw();
  10536. juce_UseDebuggingNewOperator
  10537. private:
  10538. void* internal;
  10539. String name;
  10540. int reentrancyLevel;
  10541. InterProcessLock (const InterProcessLock&);
  10542. const InterProcessLock& operator= (const InterProcessLock&);
  10543. };
  10544. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10545. /********* End of inlined file: juce_InterProcessLock.h *********/
  10546. #endif
  10547. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10548. /********* Start of inlined file: juce_Process.h *********/
  10549. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10550. #define __JUCE_PROCESS_JUCEHEADER__
  10551. /** Represents the current executable's process.
  10552. This contains methods for controlling the current application at the
  10553. process-level.
  10554. @see Thread, JUCEApplication
  10555. */
  10556. class JUCE_API Process
  10557. {
  10558. public:
  10559. enum ProcessPriority
  10560. {
  10561. LowPriority = 0,
  10562. NormalPriority = 1,
  10563. HighPriority = 2,
  10564. RealtimePriority = 3
  10565. };
  10566. /** Changes the current process's priority.
  10567. @param priority the process priority, where
  10568. 0=low, 1=normal, 2=high, 3=realtime
  10569. */
  10570. static void setPriority (const ProcessPriority priority);
  10571. /** Kills the current process immediately.
  10572. This is an emergency process terminator that kills the application
  10573. immediately - it's intended only for use only when something goes
  10574. horribly wrong.
  10575. @see JUCEApplication::quit
  10576. */
  10577. static void terminate();
  10578. /** Returns true if this application process is the one that the user is
  10579. currently using.
  10580. */
  10581. static bool isForegroundProcess() throw();
  10582. /** Raises the current process's privilege level.
  10583. Does nothing if this isn't supported by the current OS, or if process
  10584. privilege level is fixed.
  10585. */
  10586. static void raisePrivilege();
  10587. /** Lowers the current process's privilege level.
  10588. Does nothing if this isn't supported by the current OS, or if process
  10589. privilege level is fixed.
  10590. */
  10591. static void lowerPrivilege();
  10592. /** Returns true if this process is being hosted by a debugger.
  10593. */
  10594. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10595. };
  10596. #endif // __JUCE_PROCESS_JUCEHEADER__
  10597. /********* End of inlined file: juce_Process.h *********/
  10598. #endif
  10599. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10600. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10601. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10602. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10603. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10604. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10605. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10606. /**
  10607. Allows threads to wait for events triggered by other threads.
  10608. A thread can call wait() on a WaitableObject, and this will suspend the
  10609. calling thread until another thread wakes it up by calling the signal()
  10610. method.
  10611. */
  10612. class JUCE_API WaitableEvent
  10613. {
  10614. public:
  10615. /** Creates a WaitableEvent object. */
  10616. WaitableEvent() throw();
  10617. /** Destructor.
  10618. If other threads are waiting on this object when it gets deleted, this
  10619. can cause nasty errors, so be careful!
  10620. */
  10621. ~WaitableEvent() throw();
  10622. /** Suspends the calling thread until the event has been signalled.
  10623. This will wait until the object's signal() method is called by another thread,
  10624. or until the timeout expires.
  10625. After the event has been signalled, this method will return true and reset
  10626. the event.
  10627. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10628. value will cause it to wait forever.
  10629. @returns true if the object has been signalled, false if the timeout expires first.
  10630. @see signal, reset
  10631. */
  10632. bool wait (const int timeOutMilliseconds = -1) const throw();
  10633. /** Wakes up any threads that are currently waiting on this object.
  10634. If signal() is called when nothing is waiting, the next thread to call wait()
  10635. will return immediately and reset the signal.
  10636. @see wait, reset
  10637. */
  10638. void signal() const throw();
  10639. /** Resets the event to an unsignalled state.
  10640. If it's not already signalled, this does nothing.
  10641. */
  10642. void reset() const throw();
  10643. juce_UseDebuggingNewOperator
  10644. private:
  10645. void* internal;
  10646. WaitableEvent (const WaitableEvent&);
  10647. const WaitableEvent& operator= (const WaitableEvent&);
  10648. };
  10649. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10650. /********* End of inlined file: juce_WaitableEvent.h *********/
  10651. /********* Start of inlined file: juce_Thread.h *********/
  10652. #ifndef __JUCE_THREAD_JUCEHEADER__
  10653. #define __JUCE_THREAD_JUCEHEADER__
  10654. /**
  10655. Encapsulates a thread.
  10656. Subclasses derive from Thread and implement the run() method, in which they
  10657. do their business. The thread can then be started with the startThread() method
  10658. and controlled with various other methods.
  10659. This class also contains some thread-related static methods, such
  10660. as sleep(), yield(), getCurrentThreadId() etc.
  10661. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10662. MessageManagerLock
  10663. */
  10664. class JUCE_API Thread
  10665. {
  10666. public:
  10667. /**
  10668. Creates a thread.
  10669. When first created, the thread is not running. Use the startThread()
  10670. method to start it.
  10671. */
  10672. Thread (const String& threadName);
  10673. /** Destructor.
  10674. Deleting a Thread object that is running will only give the thread a
  10675. brief opportunity to stop itself cleanly, so it's recommended that you
  10676. should always call stopThread() with a decent timeout before deleting,
  10677. to avoid the thread being forcibly killed (which is a Bad Thing).
  10678. */
  10679. virtual ~Thread();
  10680. /** Must be implemented to perform the thread's actual code.
  10681. Remember that the thread must regularly check the threadShouldExit()
  10682. method whilst running, and if this returns true it should return from
  10683. the run() method as soon as possible to avoid being forcibly killed.
  10684. @see threadShouldExit, startThread
  10685. */
  10686. virtual void run() = 0;
  10687. // Thread control functions..
  10688. /** Starts the thread running.
  10689. This will start the thread's run() method.
  10690. (if it's already started, startThread() won't do anything).
  10691. @see stopThread
  10692. */
  10693. void startThread() throw();
  10694. /** Starts the thread with a given priority.
  10695. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10696. If the thread is already running, its priority will be changed.
  10697. @see startThread, setPriority
  10698. */
  10699. void startThread (const int priority) throw();
  10700. /** Attempts to stop the thread running.
  10701. This method will cause the threadShouldExit() method to return true
  10702. and call notify() in case the thread is currently waiting.
  10703. Hopefully the thread will then respond to this by exiting cleanly, and
  10704. the stopThread method will wait for a given time-period for this to
  10705. happen.
  10706. If the thread is stuck and fails to respond after the time-out, it gets
  10707. forcibly killed, which is a very bad thing to happen, as it could still
  10708. be holding locks, etc. which are needed by other parts of your program.
  10709. @param timeOutMilliseconds The number of milliseconds to wait for the
  10710. thread to finish before killing it by force. A negative
  10711. value in here will wait forever.
  10712. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10713. */
  10714. void stopThread (const int timeOutMilliseconds) throw();
  10715. /** Returns true if the thread is currently active */
  10716. bool isThreadRunning() const throw();
  10717. /** Sets a flag to tell the thread it should stop.
  10718. Calling this means that the threadShouldExit() method will then return true.
  10719. The thread should be regularly checking this to see whether it should exit.
  10720. @see threadShouldExit
  10721. @see waitForThreadToExit
  10722. */
  10723. void signalThreadShouldExit() throw();
  10724. /** Checks whether the thread has been told to stop running.
  10725. Threads need to check this regularly, and if it returns true, they should
  10726. return from their run() method at the first possible opportunity.
  10727. @see signalThreadShouldExit
  10728. */
  10729. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10730. /** Waits for the thread to stop.
  10731. This will waits until isThreadRunning() is false or until a timeout expires.
  10732. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10733. is less than zero, it will wait forever.
  10734. @returns true if the thread exits, or false if the timeout expires first.
  10735. */
  10736. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10737. /** Changes the thread's priority.
  10738. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10739. of 5 is normal.
  10740. */
  10741. void setPriority (const int priority) throw();
  10742. /** Changes the priority of the caller thread.
  10743. Similar to setPriority(), but this static method acts on the caller thread.
  10744. @see setPriority
  10745. */
  10746. static void setCurrentThreadPriority (const int priority) throw();
  10747. /** Sets the affinity mask for the thread.
  10748. This will only have an effect next time the thread is started - i.e. if the
  10749. thread is already running when called, it'll have no effect.
  10750. @see setCurrentThreadAffinityMask
  10751. */
  10752. void setAffinityMask (const uint32 affinityMask) throw();
  10753. /** Changes the affinity mask for the caller thread.
  10754. This will change the affinity mask for the thread that calls this static method.
  10755. @see setAffinityMask
  10756. */
  10757. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10758. // this can be called from any thread that needs to pause..
  10759. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10760. /** Yields the calling thread's current time-slot. */
  10761. static void JUCE_CALLTYPE yield() throw();
  10762. /** Makes the thread wait for a notification.
  10763. This puts the thread to sleep until either the timeout period expires, or
  10764. another thread calls the notify() method to wake it up.
  10765. @returns true if the event has been signalled, false if the timeout expires.
  10766. */
  10767. bool wait (const int timeOutMilliseconds) const throw();
  10768. /** Wakes up the thread.
  10769. If the thread has called the wait() method, this will wake it up.
  10770. @see wait
  10771. */
  10772. void notify() const throw();
  10773. /** A value type used for thread IDs.
  10774. @see getCurrentThreadId(), getThreadId()
  10775. */
  10776. typedef void* ThreadID;
  10777. /** Returns an id that identifies the caller thread.
  10778. To find the ID of a particular thread object, use getThreadId().
  10779. @returns a unique identifier that identifies the calling thread.
  10780. @see getThreadId
  10781. */
  10782. static ThreadID getCurrentThreadId() throw();
  10783. /** Finds the thread object that is currently running.
  10784. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10785. object associated with them, so this will return 0.
  10786. */
  10787. static Thread* getCurrentThread() throw();
  10788. /** Returns the ID of this thread.
  10789. That means the ID of this thread object - not of the thread that's calling the method.
  10790. This can change when the thread is started and stopped, and will be invalid if the
  10791. thread's not actually running.
  10792. @see getCurrentThreadId
  10793. */
  10794. ThreadID getThreadId() const throw();
  10795. /** Returns the name of the thread.
  10796. This is the name that gets set in the constructor.
  10797. */
  10798. const String getThreadName() const throw() { return threadName_; }
  10799. /** Returns the number of currently-running threads.
  10800. @returns the number of Thread objects known to be currently running.
  10801. @see stopAllThreads
  10802. */
  10803. static int getNumRunningThreads() throw();
  10804. /** Tries to stop all currently-running threads.
  10805. This will attempt to stop all the threads known to be running at the moment.
  10806. */
  10807. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10808. juce_UseDebuggingNewOperator
  10809. private:
  10810. const String threadName_;
  10811. void* volatile threadHandle_;
  10812. CriticalSection startStopLock;
  10813. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10814. int threadPriority_;
  10815. ThreadID threadId_;
  10816. uint32 affinityMask_;
  10817. bool volatile threadShouldExit_;
  10818. friend void JUCE_API juce_threadEntryPoint (void*);
  10819. static void threadEntryPoint (Thread* thread) throw();
  10820. Thread (const Thread&);
  10821. const Thread& operator= (const Thread&);
  10822. };
  10823. #endif // __JUCE_THREAD_JUCEHEADER__
  10824. /********* End of inlined file: juce_Thread.h *********/
  10825. /**
  10826. A critical section that allows multiple simultaneous readers.
  10827. Features of this type of lock are:
  10828. - Multiple readers can hold the lock at the same time, but only one writer
  10829. can hold it at once.
  10830. - Writers trying to gain the lock will be blocked until all readers and writers
  10831. have released it
  10832. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  10833. blocked until the writer has obtained and released it
  10834. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  10835. there are no other readers
  10836. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  10837. - Recursive locking is supported.
  10838. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  10839. */
  10840. class JUCE_API ReadWriteLock
  10841. {
  10842. public:
  10843. /**
  10844. Creates a ReadWriteLock object.
  10845. */
  10846. ReadWriteLock() throw();
  10847. /** Destructor.
  10848. If the object is deleted whilst locked, any subsequent behaviour
  10849. is unpredictable.
  10850. */
  10851. ~ReadWriteLock() throw();
  10852. /** Locks this object for reading.
  10853. Multiple threads can simulaneously lock the object for reading, but if another
  10854. thread has it locked for writing, then this will block until it releases the
  10855. lock.
  10856. @see exitRead, ScopedReadLock
  10857. */
  10858. void enterRead() const throw();
  10859. /** Releases the read-lock.
  10860. If the caller thread hasn't got the lock, this can have unpredictable results.
  10861. If the enterRead() method has been called multiple times by the thread, each
  10862. call must be matched by a call to exitRead() before other threads will be allowed
  10863. to take over the lock.
  10864. @see enterRead, ScopedReadLock
  10865. */
  10866. void exitRead() const throw();
  10867. /** Locks this object for writing.
  10868. This will block until any other threads that have it locked for reading or
  10869. writing have released their lock.
  10870. @see exitWrite, ScopedWriteLock
  10871. */
  10872. void enterWrite() const throw();
  10873. /** Tries to lock this object for writing.
  10874. This is like enterWrite(), but doesn't block - it returns true if it manages
  10875. to obtain the lock.
  10876. @see enterWrite
  10877. */
  10878. bool tryEnterWrite() const throw();
  10879. /** Releases the write-lock.
  10880. If the caller thread hasn't got the lock, this can have unpredictable results.
  10881. If the enterWrite() method has been called multiple times by the thread, each
  10882. call must be matched by a call to exit() before other threads will be allowed
  10883. to take over the lock.
  10884. @see enterWrite, ScopedWriteLock
  10885. */
  10886. void exitWrite() const throw();
  10887. juce_UseDebuggingNewOperator
  10888. private:
  10889. CriticalSection accessLock;
  10890. WaitableEvent waitEvent;
  10891. mutable int numWaitingWriters, numWriters;
  10892. mutable Thread::ThreadID writerThreadId;
  10893. mutable Array <Thread::ThreadID> readerThreads;
  10894. ReadWriteLock (const ReadWriteLock&);
  10895. const ReadWriteLock& operator= (const ReadWriteLock&);
  10896. };
  10897. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  10898. /********* End of inlined file: juce_ReadWriteLock.h *********/
  10899. #endif
  10900. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  10901. #endif
  10902. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10903. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  10904. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10905. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10906. /**
  10907. Automatically locks and unlocks a ReadWriteLock object.
  10908. Use one of these as a local variable to control access to a ReadWriteLock.
  10909. e.g. @code
  10910. ReadWriteLock myLock;
  10911. for (;;)
  10912. {
  10913. const ScopedReadLock myScopedLock (myLock);
  10914. // myLock is now locked
  10915. ...do some stuff...
  10916. // myLock gets unlocked here.
  10917. }
  10918. @endcode
  10919. @see ReadWriteLock, ScopedWriteLock
  10920. */
  10921. class JUCE_API ScopedReadLock
  10922. {
  10923. public:
  10924. /** Creates a ScopedReadLock.
  10925. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  10926. when the ScopedReadLock object is deleted, the ReadWriteLock will
  10927. be unlocked.
  10928. Make sure this object is created and deleted by the same thread,
  10929. otherwise there are no guarantees what will happen! Best just to use it
  10930. as a local stack object, rather than creating one with the new() operator.
  10931. */
  10932. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  10933. /** Destructor.
  10934. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  10935. Make sure this object is created and deleted by the same thread,
  10936. otherwise there are no guarantees what will happen!
  10937. */
  10938. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  10939. private:
  10940. const ReadWriteLock& lock_;
  10941. ScopedReadLock (const ScopedReadLock&);
  10942. const ScopedReadLock& operator= (const ScopedReadLock&);
  10943. };
  10944. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10945. /********* End of inlined file: juce_ScopedReadLock.h *********/
  10946. #endif
  10947. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10948. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  10949. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10950. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10951. /**
  10952. Automatically tries to lock and unlock a CriticalSection object.
  10953. Use one of these as a local variable to control access to a CriticalSection.
  10954. e.g. @code
  10955. CriticalSection myCriticalSection;
  10956. for (;;)
  10957. {
  10958. const ScopedTryLock myScopedTryLock (myCriticalSection);
  10959. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  10960. // should test this with the isLocked() method before doing your thread-unsafe
  10961. // action..
  10962. if (myScopedTryLock.isLocked())
  10963. {
  10964. ...do some stuff...
  10965. }
  10966. else
  10967. {
  10968. ..our attempt at locking failed because another thread had already locked it..
  10969. }
  10970. // myCriticalSection gets unlocked here (if it was locked)
  10971. }
  10972. @endcode
  10973. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  10974. */
  10975. class JUCE_API ScopedTryLock
  10976. {
  10977. public:
  10978. /** Creates a ScopedTryLock.
  10979. As soon as it is created, this will try to lock the CriticalSection, and
  10980. when the ScopedTryLock object is deleted, the CriticalSection will
  10981. be unlocked if the lock was successful.
  10982. Make sure this object is created and deleted by the same thread,
  10983. otherwise there are no guarantees what will happen! Best just to use it
  10984. as a local stack object, rather than creating one with the new() operator.
  10985. */
  10986. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  10987. /** Destructor.
  10988. The CriticalSection will be unlocked (if locked) when the destructor is called.
  10989. Make sure this object is created and deleted by the same thread,
  10990. otherwise there are no guarantees what will happen!
  10991. */
  10992. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  10993. /** Lock state
  10994. @return True if the CriticalSection is locked.
  10995. */
  10996. bool isLocked() const throw() { return lockWasSuccessful; }
  10997. private:
  10998. const CriticalSection& lock_;
  10999. const bool lockWasSuccessful;
  11000. ScopedTryLock (const ScopedTryLock&);
  11001. const ScopedTryLock& operator= (const ScopedTryLock&);
  11002. };
  11003. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11004. /********* End of inlined file: juce_ScopedTryLock.h *********/
  11005. #endif
  11006. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11007. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  11008. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11009. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11010. /**
  11011. Automatically locks and unlocks a ReadWriteLock object.
  11012. Use one of these as a local variable to control access to a ReadWriteLock.
  11013. e.g. @code
  11014. ReadWriteLock myLock;
  11015. for (;;)
  11016. {
  11017. const ScopedWriteLock myScopedLock (myLock);
  11018. // myLock is now locked
  11019. ...do some stuff...
  11020. // myLock gets unlocked here.
  11021. }
  11022. @endcode
  11023. @see ReadWriteLock, ScopedReadLock
  11024. */
  11025. class JUCE_API ScopedWriteLock
  11026. {
  11027. public:
  11028. /** Creates a ScopedWriteLock.
  11029. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  11030. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  11031. be unlocked.
  11032. Make sure this object is created and deleted by the same thread,
  11033. otherwise there are no guarantees what will happen! Best just to use it
  11034. as a local stack object, rather than creating one with the new() operator.
  11035. */
  11036. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  11037. /** Destructor.
  11038. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  11039. Make sure this object is created and deleted by the same thread,
  11040. otherwise there are no guarantees what will happen!
  11041. */
  11042. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  11043. private:
  11044. const ReadWriteLock& lock_;
  11045. ScopedWriteLock (const ScopedWriteLock&);
  11046. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  11047. };
  11048. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11049. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  11050. #endif
  11051. #ifndef __JUCE_THREAD_JUCEHEADER__
  11052. #endif
  11053. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11054. /********* Start of inlined file: juce_ThreadPool.h *********/
  11055. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11056. #define __JUCE_THREADPOOL_JUCEHEADER__
  11057. class ThreadPool;
  11058. class ThreadPoolThread;
  11059. /**
  11060. A task that is executed by a ThreadPool object.
  11061. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  11062. its threads.
  11063. The runJob() method needs to be implemented to do the task, and if the code that
  11064. does the work takes a significant time to run, it must keep checking the shouldExit()
  11065. method to see if something is trying to interrupt the job. If shouldExit() returns
  11066. true, the runJob() method must return immediately.
  11067. @see ThreadPool, Thread
  11068. */
  11069. class JUCE_API ThreadPoolJob
  11070. {
  11071. public:
  11072. /** Creates a thread pool job object.
  11073. After creating your job, add it to a thread pool with ThreadPool::addJob().
  11074. */
  11075. ThreadPoolJob (const String& name);
  11076. /** Destructor. */
  11077. virtual ~ThreadPoolJob();
  11078. /** Returns the name of this job.
  11079. @see setJobName
  11080. */
  11081. const String getJobName() const;
  11082. /** Changes the job's name.
  11083. @see getJobName
  11084. */
  11085. void setJobName (const String& newName);
  11086. /** These are the values that can be returned by the runJob() method.
  11087. */
  11088. enum JobStatus
  11089. {
  11090. jobHasFinished = 0, /**< indicates that the job has finished and can be
  11091. removed from the pool. */
  11092. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  11093. should be automatically deleted by the pool. */
  11094. jobNeedsRunningAgain /**< indicates that the job would like to be called
  11095. again when a thread is free. */
  11096. };
  11097. /** Peforms the actual work that this job needs to do.
  11098. Your subclass must implement this method, in which is does its work.
  11099. If the code in this method takes a significant time to run, it must repeatedly check
  11100. the shouldExit() method to see if something is trying to interrupt the job.
  11101. If shouldExit() ever returns true, the runJob() method must return immediately.
  11102. If this method returns jobHasFinished, then the job will be removed from the pool
  11103. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  11104. pool and will get a chance to run again as soon as a thread is free.
  11105. @see shouldExit()
  11106. */
  11107. virtual JobStatus runJob() = 0;
  11108. /** Returns true if this job is currently running its runJob() method. */
  11109. bool isRunning() const throw() { return isActive; }
  11110. /** Returns true if something is trying to interrupt this job and make it stop.
  11111. Your runJob() method must call this whenever it gets a chance, and if it ever
  11112. returns true, the runJob() method must return immediately.
  11113. @see signalJobShouldExit()
  11114. */
  11115. bool shouldExit() const throw() { return shouldStop; }
  11116. /** Calling this will cause the shouldExit() method to return true, and the job
  11117. should (if it's been implemented correctly) stop as soon as possible.
  11118. @see shouldExit()
  11119. */
  11120. void signalJobShouldExit();
  11121. juce_UseDebuggingNewOperator
  11122. private:
  11123. friend class ThreadPool;
  11124. friend class ThreadPoolThread;
  11125. String jobName;
  11126. ThreadPool* pool;
  11127. bool shouldStop, isActive, shouldBeDeleted;
  11128. };
  11129. /**
  11130. A set of threads that will run a list of jobs.
  11131. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11132. will be called by the next pooled thread that becomes free.
  11133. @see ThreadPoolJob, Thread
  11134. */
  11135. class JUCE_API ThreadPool
  11136. {
  11137. public:
  11138. /** Creates a thread pool.
  11139. Once you've created a pool, you can give it some things to do with the addJob()
  11140. method.
  11141. @param numberOfThreads the maximum number of actual threads to run.
  11142. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11143. until there are some jobs to run. If false, then
  11144. all the threads will be fired-up immediately so that
  11145. they're ready for action
  11146. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11147. inactive for this length of time, they will automatically
  11148. be stopped until more jobs come along and they're needed
  11149. */
  11150. ThreadPool (const int numberOfThreads,
  11151. const bool startThreadsOnlyWhenNeeded = true,
  11152. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11153. /** Destructor.
  11154. This will attempt to remove all the jobs before deleting, but if you want to
  11155. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11156. the pool.
  11157. */
  11158. ~ThreadPool();
  11159. /** Adds a job to the queue.
  11160. Once a job has been added, then the next time a thread is free, it will run
  11161. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11162. runJob() method, the pool will either remove the job from the pool or add it to
  11163. the back of the queue to be run again.
  11164. */
  11165. void addJob (ThreadPoolJob* const job);
  11166. /** Tries to remove a job from the pool.
  11167. If the job isn't yet running, this will simply remove it. If it is running, it
  11168. will wait for it to finish.
  11169. If the timeout period expires before the job finishes running, then the job will be
  11170. left in the pool and this will return false. It returns true if the job is sucessfully
  11171. stopped and removed.
  11172. @param job the job to remove
  11173. @param interruptIfRunning if true, then if the job is currently busy, its
  11174. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11175. to interrupt it. If false, then if the job will be allowed to run
  11176. until it stops normally (or the timeout expires)
  11177. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11178. before giving up and returning false
  11179. */
  11180. bool removeJob (ThreadPoolJob* const job,
  11181. const bool interruptIfRunning,
  11182. const int timeOutMilliseconds);
  11183. /** Tries clear all jobs from the pool.
  11184. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11185. methods called to try to interrupt them
  11186. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11187. before giving up and returning false
  11188. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11189. expires while waiting for them to stop
  11190. */
  11191. bool removeAllJobs (const bool interruptRunningJobs,
  11192. const int timeOutMilliseconds);
  11193. /** Returns the number of jobs currently running or queued.
  11194. */
  11195. int getNumJobs() const throw();
  11196. /** Returns one of the jobs in the queue.
  11197. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11198. around in the list, and this method may return 0 if the index is currently out-of-range.
  11199. */
  11200. ThreadPoolJob* getJob (const int index) const;
  11201. /** Returns true if the given job is currently queued or running.
  11202. @see isJobRunning()
  11203. */
  11204. bool contains (const ThreadPoolJob* const job) const throw();
  11205. /** Returns true if the given job is currently being run by a thread.
  11206. */
  11207. bool isJobRunning (const ThreadPoolJob* const job) const;
  11208. /** Waits until a job has finished running and has been removed from the pool.
  11209. This will wait until the job is no longer in the pool - i.e. until its
  11210. runJob() method returns ThreadPoolJob::jobHasFinished.
  11211. If the timeout period expires before the job finishes, this will return false;
  11212. it returns true if the job has finished successfully.
  11213. */
  11214. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11215. const int timeOutMilliseconds) const;
  11216. /** Returns a list of the names of all the jobs currently running or queued.
  11217. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11218. */
  11219. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  11220. /** Changes the priority of all the threads.
  11221. This will call Thread::setPriority() for each thread in the pool.
  11222. */
  11223. void setThreadPriorities (const int newPriority);
  11224. juce_UseDebuggingNewOperator
  11225. private:
  11226. const int numThreads, threadStopTimeout;
  11227. int priority;
  11228. Thread** threads;
  11229. VoidArray jobs;
  11230. CriticalSection lock;
  11231. uint32 lastJobEndTime;
  11232. friend class ThreadPoolThread;
  11233. bool runNextJob();
  11234. ThreadPool (const ThreadPool&);
  11235. const ThreadPool& operator= (const ThreadPool&);
  11236. };
  11237. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11238. /********* End of inlined file: juce_ThreadPool.h *********/
  11239. #endif
  11240. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11241. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11242. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11243. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11244. /**
  11245. Used by the TimeSliceThread class.
  11246. To register your class with a TimeSliceThread, derive from this class and
  11247. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11248. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11249. deleting your client!
  11250. @see TimeSliceThread
  11251. */
  11252. class JUCE_API TimeSliceClient
  11253. {
  11254. public:
  11255. /** Destructor. */
  11256. virtual ~TimeSliceClient() {}
  11257. /** Called back by a TimeSliceThread.
  11258. When you register this class with it, a TimeSliceThread will repeatedly call
  11259. this method.
  11260. The implementation of this method should use its time-slice to do something that's
  11261. quick - never block for longer than absolutely necessary.
  11262. @returns Your method should return true if it needs more time, or false if it's
  11263. not too busy and doesn't need calling back urgently. If all the thread's
  11264. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11265. up to half a second in between callbacks. You can force the TimeSliceThread
  11266. to wake up and poll again immediately by calling its notify() method.
  11267. */
  11268. virtual bool useTimeSlice() = 0;
  11269. };
  11270. /**
  11271. A thread that keeps a list of clients, and calls each one in turn, giving them
  11272. all a chance to run some sort of short task.
  11273. @see TimeSliceClient, Thread
  11274. */
  11275. class JUCE_API TimeSliceThread : public Thread
  11276. {
  11277. public:
  11278. /**
  11279. Creates a TimeSliceThread.
  11280. When first created, the thread is not running. Use the startThread()
  11281. method to start it.
  11282. */
  11283. TimeSliceThread (const String& threadName);
  11284. /** Destructor.
  11285. Deleting a Thread object that is running will only give the thread a
  11286. brief opportunity to stop itself cleanly, so it's recommended that you
  11287. should always call stopThread() with a decent timeout before deleting,
  11288. to avoid the thread being forcibly killed (which is a Bad Thing).
  11289. */
  11290. ~TimeSliceThread();
  11291. /** Adds a client to the list.
  11292. The client's callbacks will start immediately (possibly before the method
  11293. has returned).
  11294. */
  11295. void addTimeSliceClient (TimeSliceClient* const client);
  11296. /** Removes a client from the list.
  11297. This method will make sure that all callbacks to the client have completely
  11298. finished before the method returns.
  11299. */
  11300. void removeTimeSliceClient (TimeSliceClient* const client);
  11301. /** Returns the number of registered clients. */
  11302. int getNumClients() const throw();
  11303. /** Returns one of the registered clients. */
  11304. TimeSliceClient* getClient (const int index) const throw();
  11305. /** @internal */
  11306. void run();
  11307. juce_UseDebuggingNewOperator
  11308. private:
  11309. CriticalSection callbackLock, listLock;
  11310. Array <TimeSliceClient*> clients;
  11311. int index;
  11312. TimeSliceClient* clientBeingCalled;
  11313. bool clientsChanged;
  11314. TimeSliceThread (const TimeSliceThread&);
  11315. const TimeSliceThread& operator= (const TimeSliceThread&);
  11316. };
  11317. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11318. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11319. #endif
  11320. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11321. #endif
  11322. #endif
  11323. /********* End of inlined file: juce_core_includes.h *********/
  11324. // if you're compiling a command-line app, you might want to just include the core headers,
  11325. // so you can set this macro before including juce.h
  11326. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11327. /********* Start of inlined file: juce_app_includes.h *********/
  11328. #ifndef __JUCE_APP_INCLUDES_JUCEHEADER__
  11329. #define __JUCE_APP_INCLUDES_JUCEHEADER__
  11330. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11331. /********* Start of inlined file: juce_Application.h *********/
  11332. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11333. #define __JUCE_APPLICATION_JUCEHEADER__
  11334. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11335. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11336. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11337. /********* Start of inlined file: juce_Component.h *********/
  11338. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11339. #define __JUCE_COMPONENT_JUCEHEADER__
  11340. /********* Start of inlined file: juce_MouseCursor.h *********/
  11341. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11342. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11343. class Image;
  11344. class RefCountedMouseCursor;
  11345. class ComponentPeer;
  11346. class Component;
  11347. /**
  11348. Represents a mouse cursor image.
  11349. This object can either be used to represent one of the standard mouse
  11350. cursor shapes, or a custom one generated from an image.
  11351. */
  11352. class JUCE_API MouseCursor
  11353. {
  11354. public:
  11355. /** The set of available standard mouse cursors. */
  11356. enum StandardCursorType
  11357. {
  11358. NoCursor = 0, /**< An invisible cursor. */
  11359. NormalCursor, /**< The stardard arrow cursor. */
  11360. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11361. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11362. CrosshairCursor, /**< A pair of crosshairs. */
  11363. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11364. that you're dragging a copy of something. */
  11365. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11366. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11367. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11368. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11369. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11370. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11371. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11372. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11373. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11374. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11375. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11376. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11377. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11378. };
  11379. /** Creates the standard arrow cursor. */
  11380. MouseCursor() throw();
  11381. /** Creates one of the standard mouse cursor */
  11382. MouseCursor (const StandardCursorType type) throw();
  11383. /** Creates a custom cursor from an image.
  11384. @param image the image to use for the cursor - if this is bigger than the
  11385. system can manage, it might get scaled down first, and might
  11386. also have to be turned to black-and-white if it can't do colour
  11387. cursors.
  11388. @param hotSpotX the x position of the cursor's hotspot within the image
  11389. @param hotSpotY the y position of the cursor's hotspot within the image
  11390. */
  11391. MouseCursor (Image& image,
  11392. const int hotSpotX,
  11393. const int hotSpotY) throw();
  11394. /** Creates a copy of another cursor object. */
  11395. MouseCursor (const MouseCursor& other) throw();
  11396. /** Copies this cursor from another object. */
  11397. const MouseCursor& operator= (const MouseCursor& other) throw();
  11398. /** Destructor. */
  11399. ~MouseCursor() throw();
  11400. /** Checks whether two mouse cursors are the same.
  11401. For custom cursors, two cursors created from the same image won't be
  11402. recognised as the same, only MouseCursor objects that have been
  11403. copied from the same object.
  11404. */
  11405. bool operator== (const MouseCursor& other) const throw();
  11406. /** Checks whether two mouse cursors are the same.
  11407. For custom cursors, two cursors created from the same image won't be
  11408. recognised as the same, only MouseCursor objects that have been
  11409. copied from the same object.
  11410. */
  11411. bool operator!= (const MouseCursor& other) const throw();
  11412. /** Makes the system show its default 'busy' cursor.
  11413. This will turn the system cursor to an hourglass or spinning beachball
  11414. until the next time the mouse is moved, or hideWaitCursor() is called.
  11415. This is handy if the message loop is about to block for a couple of
  11416. seconds while busy and you want to give the user feedback about this.
  11417. @see MessageManager::setTimeBeforeShowingWaitCursor
  11418. */
  11419. static void showWaitCursor() throw();
  11420. /** If showWaitCursor has been called, this will return the mouse to its
  11421. normal state.
  11422. This will look at what component is under the mouse, and update the
  11423. cursor to be the correct one for that component.
  11424. @see showWaitCursor
  11425. */
  11426. static void hideWaitCursor() throw();
  11427. juce_UseDebuggingNewOperator
  11428. private:
  11429. RefCountedMouseCursor* cursorHandle;
  11430. friend class Component;
  11431. void showInWindow (ComponentPeer* window) const throw();
  11432. void showInAllWindows() const throw();
  11433. void* getHandle() const throw();
  11434. };
  11435. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11436. /********* End of inlined file: juce_MouseCursor.h *********/
  11437. /********* Start of inlined file: juce_MouseListener.h *********/
  11438. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11439. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11440. /********* Start of inlined file: juce_MouseEvent.h *********/
  11441. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11442. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11443. class Component;
  11444. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11445. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11446. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11447. /**
  11448. Represents the state of the mouse buttons and modifier keys.
  11449. This is used both by mouse events and by KeyPress objects to describe
  11450. the state of keys such as shift, control, alt, etc.
  11451. @see KeyPress, MouseEvent::mods
  11452. */
  11453. class JUCE_API ModifierKeys
  11454. {
  11455. public:
  11456. /** Creates a ModifierKeys object from a raw set of flags.
  11457. @param flags to represent the keys that are down
  11458. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11459. rightButtonModifier, commandModifier, popupMenuClickModifier
  11460. */
  11461. ModifierKeys (const int flags = 0) throw();
  11462. /** Creates a copy of another object. */
  11463. ModifierKeys (const ModifierKeys& other) throw();
  11464. /** Copies this object from another one. */
  11465. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11466. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11467. This is a platform-agnostic way of checking for the operating system's
  11468. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11469. Windows/Linux, it's actually checking for the CTRL key.
  11470. */
  11471. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11472. /** Checks whether the user is trying to launch a pop-up menu.
  11473. This checks for platform-specific modifiers that might indicate that the user
  11474. is following the operating system's normal method of showing a pop-up menu.
  11475. So on Windows/Linux, this method is really testing for a right-click.
  11476. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11477. */
  11478. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11479. /** Checks whether the flag is set for the left mouse-button. */
  11480. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11481. /** Checks whether the flag is set for the right mouse-button.
  11482. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11483. this is platform-independent (and makes your code more explanatory too).
  11484. */
  11485. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11486. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11487. /** Tests for any of the mouse-button flags. */
  11488. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11489. /** Tests for any of the modifier key flags. */
  11490. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11491. /** Checks whether the shift key's flag is set. */
  11492. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11493. /** Checks whether the CTRL key's flag is set.
  11494. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11495. popup-menu modifiers.
  11496. @see isCommandDown, isPopupMenu
  11497. */
  11498. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11499. /** Checks whether the shift key's flag is set. */
  11500. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11501. /** Flags that represent the different keys. */
  11502. enum Flags
  11503. {
  11504. /** Shift key flag. */
  11505. shiftModifier = 1,
  11506. /** CTRL key flag. */
  11507. ctrlModifier = 2,
  11508. /** ALT key flag. */
  11509. altModifier = 4,
  11510. /** Left mouse button flag. */
  11511. leftButtonModifier = 16,
  11512. /** Right mouse button flag. */
  11513. rightButtonModifier = 32,
  11514. /** Middle mouse button flag. */
  11515. middleButtonModifier = 64,
  11516. #if JUCE_MAC
  11517. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11518. commandModifier = 8,
  11519. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11520. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11521. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11522. #else
  11523. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11524. commandModifier = ctrlModifier,
  11525. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11526. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11527. popupMenuClickModifier = rightButtonModifier,
  11528. #endif
  11529. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11530. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11531. /** Represents a combination of all the mouse buttons at once. */
  11532. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11533. };
  11534. /** Returns the raw flags for direct testing. */
  11535. inline int getRawFlags() const throw() { return flags; }
  11536. /** Tests a combination of flags and returns true if any of them are set. */
  11537. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11538. /** Creates a ModifierKeys object to represent the last-known state of the
  11539. keyboard and mouse buttons.
  11540. @see getCurrentModifiersRealtime
  11541. */
  11542. static const ModifierKeys getCurrentModifiers() throw();
  11543. /** Creates a ModifierKeys object to represent the current state of the
  11544. keyboard and mouse buttons.
  11545. This isn't often needed and isn't recommended, but will actively check all the
  11546. mouse and key states rather than just returning their last-known state like
  11547. getCurrentModifiers() does.
  11548. This is only needed in special circumstances for up-to-date modifier information
  11549. at times when the app's event loop isn't running normally.
  11550. */
  11551. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11552. private:
  11553. int flags;
  11554. static int currentModifierFlags;
  11555. friend class ComponentPeer;
  11556. static void updateCurrentModifiers() throw();
  11557. };
  11558. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11559. /********* End of inlined file: juce_ModifierKeys.h *********/
  11560. /**
  11561. Contains position and status information about a mouse event.
  11562. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11563. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11564. */
  11565. class JUCE_API MouseEvent
  11566. {
  11567. public:
  11568. /** Creates a MouseEvent.
  11569. Normally an application will never need to use this.
  11570. @param x the x position of the mouse, relative to the component that is passed-in
  11571. @param y the y position of the mouse, relative to the component that is passed-in
  11572. @param modifiers the key modifiers at the time of the event
  11573. @param originator the component that the mouse event applies to
  11574. @param eventTime the time the event happened
  11575. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11576. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11577. the same as the current mouse-x position.
  11578. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11579. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11580. the same as the current mouse-y position.
  11581. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11582. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11583. the same as the current mouse-event time.
  11584. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11585. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11586. */
  11587. MouseEvent (const int x, const int y,
  11588. const ModifierKeys& modifiers,
  11589. Component* const originator,
  11590. const Time& eventTime,
  11591. const int mouseDownX,
  11592. const int mouseDownY,
  11593. const Time& mouseDownTime,
  11594. const int numberOfClicks,
  11595. const bool mouseWasDragged) throw();
  11596. /** Destructor. */
  11597. ~MouseEvent() throw();
  11598. /** The x-position of the mouse when the event occurred.
  11599. This value is relative to the top-left of the component to which the
  11600. event applies (as indicated by the MouseEvent::eventComponent field).
  11601. */
  11602. int x;
  11603. /** The y-position of the mouse when the event occurred.
  11604. This value is relative to the top-left of the component to which the
  11605. event applies (as indicated by the MouseEvent::eventComponent field).
  11606. */
  11607. int y;
  11608. /** The key modifiers associated with the event.
  11609. This will let you find out which mouse buttons were down, as well as which
  11610. modifier keys were held down.
  11611. When used for mouse-up events, this will indicate the state of the mouse buttons
  11612. just before they were released, so that you can tell which button they let go of.
  11613. */
  11614. ModifierKeys mods;
  11615. /** The component that this event applies to.
  11616. This is usually the component that the mouse was over at the time, but for mouse-drag
  11617. events the mouse could actually be over a different component and the events are
  11618. still sent to the component that the button was originally pressed on.
  11619. The x and y member variables are relative to this component's position.
  11620. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11621. component, this pointer will be updated, but originalComponent remains unchanged.
  11622. @see originalComponent
  11623. */
  11624. Component* eventComponent;
  11625. /** The component that the event first occurred on.
  11626. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11627. component, this value remains unchanged to indicate the first component that received it.
  11628. @see eventComponent
  11629. */
  11630. Component* originalComponent;
  11631. /** The time that this mouse-event occurred.
  11632. */
  11633. Time eventTime;
  11634. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11635. The co-ordinate is relative to the component specified in MouseEvent::component.
  11636. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11637. */
  11638. int getMouseDownX() const throw();
  11639. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11640. The co-ordinate is relative to the component specified in MouseEvent::component.
  11641. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11642. */
  11643. int getMouseDownY() const throw();
  11644. /** Returns the straight-line distance between where the mouse is now and where it
  11645. was the last time the button was pressed.
  11646. This is quite handy for things like deciding whether the user has moved far enough
  11647. for it to be considered a drag operation.
  11648. @see getDistanceFromDragStartX
  11649. */
  11650. int getDistanceFromDragStart() const throw();
  11651. /** Returns the difference between the mouse's current x postion and where it was
  11652. when the button was last pressed.
  11653. @see getDistanceFromDragStart
  11654. */
  11655. int getDistanceFromDragStartX() const throw();
  11656. /** Returns the difference between the mouse's current y postion and where it was
  11657. when the button was last pressed.
  11658. @see getDistanceFromDragStart
  11659. */
  11660. int getDistanceFromDragStartY() const throw();
  11661. /** Returns true if the mouse has just been clicked.
  11662. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11663. the user has dragged the mouse more than a few pixels from the place where the
  11664. mouse-down occurred.
  11665. Once they have dragged it far enough for this method to return false, it will continue
  11666. to return false until the mouse-up, even if they move the mouse back to the same
  11667. position where they originally pressed it. This means that it's very handy for
  11668. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11669. callback to ignore any small movements they might make while clicking.
  11670. @returns true if the mouse wasn't dragged by more than a few pixels between
  11671. the last time the button was pressed and released.
  11672. */
  11673. bool mouseWasClicked() const throw();
  11674. /** For a click event, the number of times the mouse was clicked in succession.
  11675. So for example a double-click event will return 2, a triple-click 3, etc.
  11676. */
  11677. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11678. /** Returns the time that the mouse button has been held down for.
  11679. If called from a mouseDrag or mouseUp callback, this will return the
  11680. number of milliseconds since the corresponding mouseDown event occurred.
  11681. If called in other contexts, e.g. a mouseMove, then the returned value
  11682. may be 0 or an undefined value.
  11683. */
  11684. int getLengthOfMousePress() const throw();
  11685. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11686. The co-ordinates are relative to the top-left of the main monitor.
  11687. @see getMouseDownScreenX, Desktop::getMousePosition
  11688. */
  11689. int getScreenX() const throw();
  11690. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11691. The co-ordinates are relative to the top-left of the main monitor.
  11692. @see getMouseDownScreenY, Desktop::getMousePosition
  11693. */
  11694. int getScreenY() const throw();
  11695. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11696. The co-ordinates are relative to the top-left of the main monitor.
  11697. @see getScreenX, Desktop::getMousePosition
  11698. */
  11699. int getMouseDownScreenX() const throw();
  11700. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11701. The co-ordinates are relative to the top-left of the main monitor.
  11702. @see getScreenY, Desktop::getMousePosition
  11703. */
  11704. int getMouseDownScreenY() const throw();
  11705. /** Creates a version of this event that is relative to a different component.
  11706. The x and y positions of the event that is returned will have been
  11707. adjusted to be relative to the new component.
  11708. */
  11709. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11710. /** Changes the application-wide setting for the double-click time limit.
  11711. This is the maximum length of time between mouse-clicks for it to be
  11712. considered a double-click. It's used by the Component class.
  11713. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11714. */
  11715. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11716. /** Returns the application-wide setting for the double-click time limit.
  11717. This is the maximum length of time between mouse-clicks for it to be
  11718. considered a double-click. It's used by the Component class.
  11719. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11720. */
  11721. static int getDoubleClickTimeout() throw();
  11722. juce_UseDebuggingNewOperator
  11723. private:
  11724. int mouseDownX, mouseDownY;
  11725. Time mouseDownTime;
  11726. int numberOfClicks;
  11727. bool wasMovedSinceMouseDown;
  11728. };
  11729. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11730. /********* End of inlined file: juce_MouseEvent.h *********/
  11731. /**
  11732. A MouseListener can be registered with a component to receive callbacks
  11733. about mouse events that happen to that component.
  11734. @see Component::addMouseListener, Component::removeMouseListener
  11735. */
  11736. class JUCE_API MouseListener
  11737. {
  11738. public:
  11739. /** Destructor. */
  11740. virtual ~MouseListener() {}
  11741. /** Called when the mouse moves inside a component.
  11742. If the mouse button isn't pressed and the mouse moves over a component,
  11743. this will be called to let the component react to this.
  11744. A component will always get a mouseEnter callback before a mouseMove.
  11745. @param e details about the position and status of the mouse event, including
  11746. the source component in which it occurred
  11747. @see mouseEnter, mouseExit, mouseDrag, contains
  11748. */
  11749. virtual void mouseMove (const MouseEvent& e);
  11750. /** Called when the mouse first enters a component.
  11751. If the mouse button isn't pressed and the mouse moves into a component,
  11752. this will be called to let the component react to this.
  11753. When the mouse button is pressed and held down while being moved in
  11754. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11755. mouseDrag messages are sent to the component that the mouse was originally
  11756. clicked on, until the button is released.
  11757. @param e details about the position and status of the mouse event, including
  11758. the source component in which it occurred
  11759. @see mouseExit, mouseDrag, mouseMove, contains
  11760. */
  11761. virtual void mouseEnter (const MouseEvent& e);
  11762. /** Called when the mouse moves out of a component.
  11763. This will be called when the mouse moves off the edge of this
  11764. component.
  11765. If the mouse button was pressed, and it was then dragged off the
  11766. edge of the component and released, then this callback will happen
  11767. when the button is released, after the mouseUp callback.
  11768. @param e details about the position and status of the mouse event, including
  11769. the source component in which it occurred
  11770. @see mouseEnter, mouseDrag, mouseMove, contains
  11771. */
  11772. virtual void mouseExit (const MouseEvent& e);
  11773. /** Called when a mouse button is pressed.
  11774. The MouseEvent object passed in contains lots of methods for finding out
  11775. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11776. were held down at the time.
  11777. Once a button is held down, the mouseDrag method will be called when the
  11778. mouse moves, until the button is released.
  11779. @param e details about the position and status of the mouse event, including
  11780. the source component in which it occurred
  11781. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11782. */
  11783. virtual void mouseDown (const MouseEvent& e);
  11784. /** Called when the mouse is moved while a button is held down.
  11785. When a mouse button is pressed inside a component, that component
  11786. receives mouseDrag callbacks each time the mouse moves, even if the
  11787. mouse strays outside the component's bounds.
  11788. @param e details about the position and status of the mouse event, including
  11789. the source component in which it occurred
  11790. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11791. */
  11792. virtual void mouseDrag (const MouseEvent& e);
  11793. /** Called when a mouse button is released.
  11794. A mouseUp callback is sent to the component in which a button was pressed
  11795. even if the mouse is actually over a different component when the
  11796. button is released.
  11797. The MouseEvent object passed in contains lots of methods for finding out
  11798. which buttons were down just before they were released.
  11799. @param e details about the position and status of the mouse event, including
  11800. the source component in which it occurred
  11801. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11802. */
  11803. virtual void mouseUp (const MouseEvent& e);
  11804. /** Called when a mouse button has been double-clicked on a component.
  11805. The MouseEvent object passed in contains lots of methods for finding out
  11806. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11807. were held down at the time.
  11808. @param e details about the position and status of the mouse event, including
  11809. the source component in which it occurred
  11810. @see mouseDown, mouseUp
  11811. */
  11812. virtual void mouseDoubleClick (const MouseEvent& e);
  11813. /** Called when the mouse-wheel is moved.
  11814. This callback is sent to the component that the mouse is over when the
  11815. wheel is moved.
  11816. If not overridden, the component will forward this message to its parent, so
  11817. that parent components can collect mouse-wheel messages that happen to
  11818. child components which aren't interested in them.
  11819. @param e details about the position and status of the mouse event, including
  11820. the source component in which it occurred
  11821. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11822. value means the wheel has been pushed to the right, negative means it
  11823. was pushed to the left
  11824. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11825. value means the wheel has been pushed upwards, negative means it
  11826. was pushed downwards
  11827. */
  11828. virtual void mouseWheelMove (const MouseEvent& e,
  11829. float wheelIncrementX,
  11830. float wheelIncrementY);
  11831. private:
  11832. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11833. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11834. // if that happens, update your code to use the new one above.
  11835. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11836. };
  11837. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11838. /********* End of inlined file: juce_MouseListener.h *********/
  11839. /********* Start of inlined file: juce_ComponentListener.h *********/
  11840. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11841. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11842. class Component;
  11843. /**
  11844. Gets informed about changes to a component's hierarchy or position.
  11845. To monitor a component for changes, register a subclass of ComponentListener
  11846. with the component using Component::addComponentListener().
  11847. Be sure to deregister listeners before you delete them!
  11848. @see Component::addComponentListener, Component::removeComponentListener
  11849. */
  11850. class JUCE_API ComponentListener
  11851. {
  11852. public:
  11853. /** Destructor. */
  11854. virtual ~ComponentListener() {}
  11855. /** Called when the component's position or size changes.
  11856. @param component the component that was moved or resized
  11857. @param wasMoved true if the component's top-left corner has just moved
  11858. @param wasResized true if the component's width or height has just changed
  11859. @see Component::setBounds, Component::resized, Component::moved
  11860. */
  11861. virtual void componentMovedOrResized (Component& component,
  11862. bool wasMoved,
  11863. bool wasResized);
  11864. /** Called when the component is brought to the top of the z-order.
  11865. @param component the component that was moved
  11866. @see Component::toFront, Component::broughtToFront
  11867. */
  11868. virtual void componentBroughtToFront (Component& component);
  11869. /** Called when the component is made visible or invisible.
  11870. @param component the component that changed
  11871. @see Component::setVisible
  11872. */
  11873. virtual void componentVisibilityChanged (Component& component);
  11874. /** Called when the component has children added or removed.
  11875. @param component the component whose children were changed
  11876. @see Component::childrenChanged, Component::addChildComponent,
  11877. Component::removeChildComponent
  11878. */
  11879. virtual void componentChildrenChanged (Component& component);
  11880. /** Called to indicate that the component's parents have changed.
  11881. When a component is added or removed from its parent, all of its children
  11882. will produce this notification (recursively - so all children of its
  11883. children will also be called as well).
  11884. @param component the component that this listener is registered with
  11885. @see Component::parentHierarchyChanged
  11886. */
  11887. virtual void componentParentHierarchyChanged (Component& component);
  11888. /** Called when the component's name is changed.
  11889. @see Component::setName, Component::getName
  11890. */
  11891. virtual void componentNameChanged (Component& component);
  11892. };
  11893. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11894. /********* End of inlined file: juce_ComponentListener.h *********/
  11895. /********* Start of inlined file: juce_KeyListener.h *********/
  11896. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11897. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11898. /********* Start of inlined file: juce_KeyPress.h *********/
  11899. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11900. #define __JUCE_KEYPRESS_JUCEHEADER__
  11901. /**
  11902. Represents a key press, including any modifier keys that are needed.
  11903. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11904. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11905. */
  11906. class JUCE_API KeyPress
  11907. {
  11908. public:
  11909. /** Creates an (invalid) KeyPress.
  11910. @see isValid
  11911. */
  11912. KeyPress() throw();
  11913. /** Creates a KeyPress for a key and some modifiers.
  11914. e.g.
  11915. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11916. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11917. @param keyCode a code that represents the key - this value must be
  11918. one of special constants listed in this class, or an
  11919. 8-bit character code such as a letter (case is ignored),
  11920. digit or a simple key like "," or ".". Note that this
  11921. isn't the same as the textCharacter parameter, so for example
  11922. a keyCode of 'a' and a shift-key modifier should have a
  11923. textCharacter value of 'A'.
  11924. @param modifiers the modifiers to associate with the keystroke
  11925. @param textCharacter the character that would be printed if someone typed
  11926. this keypress into a text editor. This value may be
  11927. null if the keypress is a non-printing character
  11928. @see getKeyCode, isKeyCode, getModifiers
  11929. */
  11930. KeyPress (const int keyCode,
  11931. const ModifierKeys& modifiers,
  11932. const juce_wchar textCharacter) throw();
  11933. /** Creates a keypress with a keyCode but no modifiers or text character.
  11934. */
  11935. KeyPress (const int keyCode) throw();
  11936. /** Creates a copy of another KeyPress. */
  11937. KeyPress (const KeyPress& other) throw();
  11938. /** Copies this KeyPress from another one. */
  11939. const KeyPress& operator= (const KeyPress& other) throw();
  11940. /** Compares two KeyPress objects. */
  11941. bool operator== (const KeyPress& other) const throw();
  11942. /** Compares two KeyPress objects. */
  11943. bool operator!= (const KeyPress& other) const throw();
  11944. /** Returns true if this is a valid KeyPress.
  11945. A null keypress can be created by the default constructor, in case it's
  11946. needed.
  11947. */
  11948. bool isValid() const throw() { return keyCode != 0; }
  11949. /** Returns the key code itself.
  11950. This will either be one of the special constants defined in this class,
  11951. or an 8-bit character code.
  11952. */
  11953. int getKeyCode() const throw() { return keyCode; }
  11954. /** Returns the key modifiers.
  11955. @see ModifierKeys
  11956. */
  11957. const ModifierKeys getModifiers() const throw() { return mods; }
  11958. /** Returns the character that is associated with this keypress.
  11959. This is the character that you'd expect to see printed if you press this
  11960. keypress in a text editor or similar component.
  11961. */
  11962. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11963. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11964. the modifiers.
  11965. The values for key codes can either be one of the special constants defined in
  11966. this class, or an 8-bit character code.
  11967. @see getKeyCode
  11968. */
  11969. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11970. /** Converts a textual key description to a KeyPress.
  11971. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11972. This isn't designed to cope with any kind of input, but should be given the
  11973. strings that are created by the getTextDescription() method.
  11974. If the string can't be parsed, the object returned will be invalid.
  11975. @see getTextDescription
  11976. */
  11977. static const KeyPress createFromDescription (const String& textVersion) throw();
  11978. /** Creates a textual description of the key combination.
  11979. e.g. "CTRL + C" or "DELETE".
  11980. To store a keypress in a file, use this method, along with createFromDescription()
  11981. to retrieve it later.
  11982. */
  11983. const String getTextDescription() const throw();
  11984. /** Checks whether the user is currently holding down the keys that make up this
  11985. KeyPress.
  11986. Note that this will return false if any extra modifier keys are
  11987. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11988. then it will be false.
  11989. */
  11990. bool isCurrentlyDown() const throw();
  11991. /** Checks whether a particular key is held down, irrespective of modifiers.
  11992. The values for key codes can either be one of the special constants defined in
  11993. this class, or an 8-bit character code.
  11994. */
  11995. static bool isKeyCurrentlyDown (int keyCode) throw();
  11996. // Key codes
  11997. //
  11998. // Note that the actual values of these are platform-specific and may change
  11999. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  12000. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  12001. //
  12002. static const int spaceKey; /**< key-code for the space bar */
  12003. static const int escapeKey; /**< key-code for the escape key */
  12004. static const int returnKey; /**< key-code for the return key*/
  12005. static const int tabKey; /**< key-code for the tab key*/
  12006. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  12007. static const int backspaceKey; /**< key-code for the backspace key */
  12008. static const int insertKey; /**< key-code for the insert key */
  12009. static const int upKey; /**< key-code for the cursor-up key */
  12010. static const int downKey; /**< key-code for the cursor-down key */
  12011. static const int leftKey; /**< key-code for the cursor-left key */
  12012. static const int rightKey; /**< key-code for the cursor-right key */
  12013. static const int pageUpKey; /**< key-code for the page-up key */
  12014. static const int pageDownKey; /**< key-code for the page-down key */
  12015. static const int homeKey; /**< key-code for the home key */
  12016. static const int endKey; /**< key-code for the end key */
  12017. static const int F1Key; /**< key-code for the F1 key */
  12018. static const int F2Key; /**< key-code for the F2 key */
  12019. static const int F3Key; /**< key-code for the F3 key */
  12020. static const int F4Key; /**< key-code for the F4 key */
  12021. static const int F5Key; /**< key-code for the F5 key */
  12022. static const int F6Key; /**< key-code for the F6 key */
  12023. static const int F7Key; /**< key-code for the F7 key */
  12024. static const int F8Key; /**< key-code for the F8 key */
  12025. static const int F9Key; /**< key-code for the F9 key */
  12026. static const int F10Key; /**< key-code for the F10 key */
  12027. static const int F11Key; /**< key-code for the F11 key */
  12028. static const int F12Key; /**< key-code for the F12 key */
  12029. static const int F13Key; /**< key-code for the F13 key */
  12030. static const int F14Key; /**< key-code for the F14 key */
  12031. static const int F15Key; /**< key-code for the F15 key */
  12032. static const int F16Key; /**< key-code for the F16 key */
  12033. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  12034. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  12035. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  12036. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  12037. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  12038. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  12039. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  12040. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  12041. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  12042. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  12043. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  12044. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  12045. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  12046. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  12047. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  12048. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  12049. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  12050. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  12051. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  12052. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  12053. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  12054. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  12055. juce_UseDebuggingNewOperator
  12056. private:
  12057. int keyCode;
  12058. ModifierKeys mods;
  12059. juce_wchar textCharacter;
  12060. };
  12061. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  12062. /********* End of inlined file: juce_KeyPress.h *********/
  12063. class Component;
  12064. /**
  12065. Receives callbacks when keys are pressed.
  12066. You can add a key listener to a component to be informed when that component
  12067. gets key events. See the Component::addListener method for more details.
  12068. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  12069. */
  12070. class JUCE_API KeyListener
  12071. {
  12072. public:
  12073. /** Destructor. */
  12074. virtual ~KeyListener() {}
  12075. /** Called to indicate that a key has been pressed.
  12076. If your implementation returns true, then the key event is considered to have
  12077. been consumed, and will not be passed on to any other components. If it returns
  12078. false, then the key will be passed to other components that might want to use it.
  12079. @param key the keystroke, including modifier keys
  12080. @param originatingComponent the component that received the key event
  12081. @see keyStateChanged, Component::keyPressed
  12082. */
  12083. virtual bool keyPressed (const KeyPress& key,
  12084. Component* originatingComponent) = 0;
  12085. /** Called when any key is pressed or released.
  12086. When this is called, classes that might be interested in
  12087. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  12088. check whether their key has changed.
  12089. If your implementation returns true, then the key event is considered to have
  12090. been consumed, and will not be passed on to any other components. If it returns
  12091. false, then the key will be passed to other components that might want to use it.
  12092. @param originatingComponent the component that received the key event
  12093. @see KeyPress, Component::keyStateChanged
  12094. */
  12095. virtual bool keyStateChanged (Component* originatingComponent);
  12096. };
  12097. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  12098. /********* End of inlined file: juce_KeyListener.h *********/
  12099. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  12100. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12101. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12102. class Component;
  12103. /**
  12104. Controls the order in which focus moves between components.
  12105. The default algorithm used by this class to work out the order of traversal
  12106. is as follows:
  12107. - if two components both have an explicit focus order specified, then the
  12108. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12109. method).
  12110. - any component with an explicit focus order greater than 0 comes before ones
  12111. that don't have an order specified.
  12112. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12113. order.
  12114. If you need traversal in a more customised way, you can create a subclass
  12115. of KeyboardFocusTraverser that uses your own algorithm, and use
  12116. Component::createFocusTraverser() to create it.
  12117. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12118. */
  12119. class JUCE_API KeyboardFocusTraverser
  12120. {
  12121. public:
  12122. KeyboardFocusTraverser();
  12123. /** Destructor. */
  12124. virtual ~KeyboardFocusTraverser();
  12125. /** Returns the component that should be given focus after the specified one
  12126. when moving "forwards".
  12127. The default implementation will return the next component which is to the
  12128. right of or below this one.
  12129. This may return 0 if there's no suitable candidate.
  12130. */
  12131. virtual Component* getNextComponent (Component* current);
  12132. /** Returns the component that should be given focus after the specified one
  12133. when moving "backwards".
  12134. The default implementation will return the next component which is to the
  12135. left of or above this one.
  12136. This may return 0 if there's no suitable candidate.
  12137. */
  12138. virtual Component* getPreviousComponent (Component* current);
  12139. /** Returns the component that should receive focus be default within the given
  12140. parent component.
  12141. The default implementation will just return the foremost child component that
  12142. wants focus.
  12143. This may return 0 if there's no suitable candidate.
  12144. */
  12145. virtual Component* getDefaultComponent (Component* parentComponent);
  12146. };
  12147. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12148. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12149. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12150. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12151. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12152. /********* Start of inlined file: juce_Graphics.h *********/
  12153. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12154. #define __JUCE_GRAPHICS_JUCEHEADER__
  12155. /********* Start of inlined file: juce_Font.h *********/
  12156. #ifndef __JUCE_FONT_JUCEHEADER__
  12157. #define __JUCE_FONT_JUCEHEADER__
  12158. /********* Start of inlined file: juce_Typeface.h *********/
  12159. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12160. #define __JUCE_TYPEFACE_JUCEHEADER__
  12161. /********* Start of inlined file: juce_Path.h *********/
  12162. #ifndef __JUCE_PATH_JUCEHEADER__
  12163. #define __JUCE_PATH_JUCEHEADER__
  12164. /********* Start of inlined file: juce_AffineTransform.h *********/
  12165. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12166. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12167. /**
  12168. Represents a 2D affine-transformation matrix.
  12169. An affine transformation is a transformation such as a rotation, scale, shear,
  12170. resize or translation.
  12171. These are used for various 2D transformation tasks, e.g. with Path objects.
  12172. @see Path, Point, Line
  12173. */
  12174. class JUCE_API AffineTransform
  12175. {
  12176. public:
  12177. /** Creates an identity transform. */
  12178. AffineTransform() throw();
  12179. /** Creates a copy of another transform. */
  12180. AffineTransform (const AffineTransform& other) throw();
  12181. /** Creates a transform from a set of raw matrix values.
  12182. The resulting matrix is:
  12183. (mat00 mat01 mat02)
  12184. (mat10 mat11 mat12)
  12185. ( 0 0 1 )
  12186. */
  12187. AffineTransform (const float mat00, const float mat01, const float mat02,
  12188. const float mat10, const float mat11, const float mat12) throw();
  12189. /** Copies from another AffineTransform object */
  12190. const AffineTransform& operator= (const AffineTransform& other) throw();
  12191. /** Compares two transforms. */
  12192. bool operator== (const AffineTransform& other) const throw();
  12193. /** Compares two transforms. */
  12194. bool operator!= (const AffineTransform& other) const throw();
  12195. /** A ready-to-use identity transform, which you can use to append other
  12196. transformations to.
  12197. e.g. @code
  12198. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12199. .scaled (2.0f);
  12200. @endcode
  12201. */
  12202. static const AffineTransform identity;
  12203. /** Transforms a 2D co-ordinate using this matrix. */
  12204. void transformPoint (float& x,
  12205. float& y) const throw();
  12206. /** Transforms a 2D co-ordinate using this matrix. */
  12207. void transformPoint (double& x,
  12208. double& y) const throw();
  12209. /** Returns a new transform which is the same as this one followed by a translation. */
  12210. const AffineTransform translated (const float deltaX,
  12211. const float deltaY) const throw();
  12212. /** Returns a new transform which is a translation. */
  12213. static const AffineTransform translation (const float deltaX,
  12214. const float deltaY) throw();
  12215. /** Returns a transform which is the same as this one followed by a rotation.
  12216. The rotation is specified by a number of radians to rotate clockwise, centred around
  12217. the origin (0, 0).
  12218. */
  12219. const AffineTransform rotated (const float angleInRadians) const throw();
  12220. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12221. The rotation is specified by a number of radians to rotate clockwise, centred around
  12222. the co-ordinates passed in.
  12223. */
  12224. const AffineTransform rotated (const float angleInRadians,
  12225. const float pivotX,
  12226. const float pivotY) const throw();
  12227. /** Returns a new transform which is a rotation about (0, 0). */
  12228. static const AffineTransform rotation (const float angleInRadians) throw();
  12229. /** Returns a new transform which is a rotation about a given point. */
  12230. static const AffineTransform rotation (const float angleInRadians,
  12231. const float pivotX,
  12232. const float pivotY) throw();
  12233. /** Returns a transform which is the same as this one followed by a re-scaling.
  12234. The scaling is centred around the origin (0, 0).
  12235. */
  12236. const AffineTransform scaled (const float factorX,
  12237. const float factorY) const throw();
  12238. /** Returns a new transform which is a re-scale about the origin. */
  12239. static const AffineTransform scale (const float factorX,
  12240. const float factorY) throw();
  12241. /** Returns a transform which is the same as this one followed by a shear.
  12242. The shear is centred around the origin (0, 0).
  12243. */
  12244. const AffineTransform sheared (const float shearX,
  12245. const float shearY) const throw();
  12246. /** Returns a matrix which is the inverse operation of this one.
  12247. Some matrices don't have an inverse - in this case, the method will just return
  12248. an identity transform.
  12249. */
  12250. const AffineTransform inverted() const throw();
  12251. /** Returns the result of concatenating another transformation after this one. */
  12252. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12253. /** Returns true if this transform has no effect on points. */
  12254. bool isIdentity() const throw();
  12255. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12256. bool isSingularity() const throw();
  12257. juce_UseDebuggingNewOperator
  12258. /* The transform matrix is:
  12259. (mat00 mat01 mat02)
  12260. (mat10 mat11 mat12)
  12261. ( 0 0 1 )
  12262. */
  12263. float mat00, mat01, mat02;
  12264. float mat10, mat11, mat12;
  12265. private:
  12266. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12267. const float mat10, const float mat11, const float mat12) const throw();
  12268. };
  12269. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12270. /********* End of inlined file: juce_AffineTransform.h *********/
  12271. /********* Start of inlined file: juce_Point.h *********/
  12272. #ifndef __JUCE_POINT_JUCEHEADER__
  12273. #define __JUCE_POINT_JUCEHEADER__
  12274. /**
  12275. A pair of (x, y) co-ordinates.
  12276. Uses 32-bit floating point accuracy.
  12277. @see Line, Path, AffineTransform
  12278. */
  12279. class JUCE_API Point
  12280. {
  12281. public:
  12282. /** Creates a point with co-ordinates (0, 0). */
  12283. Point() throw();
  12284. /** Creates a copy of another point. */
  12285. Point (const Point& other) throw();
  12286. /** Creates a point from an (x, y) position. */
  12287. Point (const float x, const float y) throw();
  12288. /** Copies this point from another one.
  12289. @see setXY
  12290. */
  12291. const Point& operator= (const Point& other) throw();
  12292. /** Destructor. */
  12293. ~Point() throw();
  12294. /** Returns the point's x co-ordinate. */
  12295. inline float getX() const throw() { return x; }
  12296. /** Returns the point's y co-ordinate. */
  12297. inline float getY() const throw() { return y; }
  12298. /** Changes the point's x and y co-ordinates. */
  12299. void setXY (const float x,
  12300. const float y) throw();
  12301. /** Uses a transform to change the point's co-ordinates.
  12302. @see AffineTransform::transformPoint
  12303. */
  12304. void applyTransform (const AffineTransform& transform) throw();
  12305. juce_UseDebuggingNewOperator
  12306. private:
  12307. float x, y;
  12308. };
  12309. #endif // __JUCE_POINT_JUCEHEADER__
  12310. /********* End of inlined file: juce_Point.h *********/
  12311. /********* Start of inlined file: juce_Justification.h *********/
  12312. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12313. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12314. /**
  12315. Represents a type of justification to be used when positioning graphical items.
  12316. e.g. it indicates whether something should be placed top-left, top-right,
  12317. centred, etc.
  12318. It is used in various places wherever this kind of information is needed.
  12319. */
  12320. class JUCE_API Justification
  12321. {
  12322. public:
  12323. /** Creates a Justification object using a combination of flags. */
  12324. inline Justification (const int flags_) throw() : flags (flags_) {}
  12325. /** Creates a copy of another Justification object. */
  12326. Justification (const Justification& other) throw();
  12327. /** Copies another Justification object. */
  12328. const Justification& operator= (const Justification& other) throw();
  12329. /** Returns the raw flags that are set for this Justification object. */
  12330. inline int getFlags() const throw() { return flags; }
  12331. /** Tests a set of flags for this object.
  12332. @returns true if any of the flags passed in are set on this object.
  12333. */
  12334. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12335. /** Returns just the flags from this object that deal with vertical layout. */
  12336. int getOnlyVerticalFlags() const throw();
  12337. /** Returns just the flags from this object that deal with horizontal layout. */
  12338. int getOnlyHorizontalFlags() const throw();
  12339. /** Adjusts the position of a rectangle to fit it into a space.
  12340. The (x, y) position of the rectangle will be updated to position it inside the
  12341. given space according to the justification flags.
  12342. */
  12343. void applyToRectangle (int& x, int& y,
  12344. const int w, const int h,
  12345. const int spaceX, const int spaceY,
  12346. const int spaceW, const int spaceH) const throw();
  12347. /** Flag values that can be combined and used in the constructor. */
  12348. enum
  12349. {
  12350. /** Indicates that the item should be aligned against the left edge of the available space. */
  12351. left = 1,
  12352. /** Indicates that the item should be aligned against the right edge of the available space. */
  12353. right = 2,
  12354. /** Indicates that the item should be placed in the centre between the left and right
  12355. sides of the available space. */
  12356. horizontallyCentred = 4,
  12357. /** Indicates that the item should be aligned against the top edge of the available space. */
  12358. top = 8,
  12359. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12360. bottom = 16,
  12361. /** Indicates that the item should be placed in the centre between the top and bottom
  12362. sides of the available space. */
  12363. verticallyCentred = 32,
  12364. /** Indicates that lines of text should be spread out to fill the maximum width
  12365. available, so that both margins are aligned vertically.
  12366. */
  12367. horizontallyJustified = 64,
  12368. /** Indicates that the item should be centred vertically and horizontally.
  12369. This is equivalent to (horizontallyCentred | verticallyCentred)
  12370. */
  12371. centred = 36,
  12372. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12373. This is equivalent to (left | verticallyCentred)
  12374. */
  12375. centredLeft = 33,
  12376. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12377. This is equivalent to (right | verticallyCentred)
  12378. */
  12379. centredRight = 34,
  12380. /** Indicates that the item should be centred horizontally and placed at the top.
  12381. This is equivalent to (horizontallyCentred | top)
  12382. */
  12383. centredTop = 12,
  12384. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12385. This is equivalent to (horizontallyCentred | bottom)
  12386. */
  12387. centredBottom = 20,
  12388. /** Indicates that the item should be placed in the top-left corner.
  12389. This is equivalent to (left | top)
  12390. */
  12391. topLeft = 9,
  12392. /** Indicates that the item should be placed in the top-right corner.
  12393. This is equivalent to (right | top)
  12394. */
  12395. topRight = 10,
  12396. /** Indicates that the item should be placed in the bottom-left corner.
  12397. This is equivalent to (left | bottom)
  12398. */
  12399. bottomLeft = 17,
  12400. /** Indicates that the item should be placed in the bottom-left corner.
  12401. This is equivalent to (right | bottom)
  12402. */
  12403. bottomRight = 18
  12404. };
  12405. private:
  12406. int flags;
  12407. };
  12408. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12409. /********* End of inlined file: juce_Justification.h *********/
  12410. /**
  12411. A path is a sequence of lines and curves that may either form a closed shape
  12412. or be open-ended.
  12413. To use a path, you can create an empty one, then add lines and curves to it
  12414. to create shapes, then it can be rendered by a Graphics context or used
  12415. for geometric operations.
  12416. e.g. @code
  12417. Path myPath;
  12418. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12419. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12420. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12421. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12422. // add an ellipse as well, which will form a second sub-path within the path..
  12423. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12424. // double the width of the whole thing..
  12425. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12426. // and draw it to a graphics context with a 5-pixel thick outline.
  12427. g.strokePath (myPath, PathStrokeType (5.0f));
  12428. @endcode
  12429. A path object can actually contain multiple sub-paths, which may themselves
  12430. be open or closed.
  12431. @see PathFlatteningIterator, PathStrokeType, Graphics
  12432. */
  12433. class JUCE_API Path : private ArrayAllocationBase <float>
  12434. {
  12435. public:
  12436. /** Creates an empty path. */
  12437. Path() throw();
  12438. /** Creates a copy of another path. */
  12439. Path (const Path& other) throw();
  12440. /** Destructor. */
  12441. ~Path() throw();
  12442. /** Copies this path from another one. */
  12443. const Path& operator= (const Path& other) throw();
  12444. /** Returns true if the path doesn't contain any lines or curves. */
  12445. bool isEmpty() const throw();
  12446. /** Returns the smallest rectangle that contains all points within the path.
  12447. */
  12448. void getBounds (float& x, float& y,
  12449. float& w, float& h) const throw();
  12450. /** Returns the smallest rectangle that contains all points within the path
  12451. after it's been transformed with the given tranasform matrix.
  12452. */
  12453. void getBoundsTransformed (const AffineTransform& transform,
  12454. float& x, float& y,
  12455. float& w, float& h) const throw();
  12456. /** Checks whether a point lies within the path.
  12457. This is only relevent for closed paths (see closeSubPath()), and
  12458. may produce false results if used on a path which has open sub-paths.
  12459. The path's winding rule is taken into account by this method.
  12460. The tolerence parameter is passed to the PathFlatteningIterator that
  12461. is used to trace the path - for more info about it, see the notes for
  12462. the PathFlatteningIterator constructor.
  12463. @see closeSubPath, setUsingNonZeroWinding
  12464. */
  12465. bool contains (const float x,
  12466. const float y,
  12467. const float tolerence = 10.0f) const throw();
  12468. /** Checks whether a line crosses the path.
  12469. This will return positive if the line crosses any of the paths constituent
  12470. lines or curves. It doesn't take into account whether the line is inside
  12471. or outside the path, or whether the path is open or closed.
  12472. The tolerence parameter is passed to the PathFlatteningIterator that
  12473. is used to trace the path - for more info about it, see the notes for
  12474. the PathFlatteningIterator constructor.
  12475. */
  12476. bool intersectsLine (const float x1, const float y1,
  12477. const float x2, const float y2,
  12478. const float tolerence = 10.0f) throw();
  12479. /** Removes all lines and curves, resetting the path completely. */
  12480. void clear() throw();
  12481. /** Begins a new subpath with a given starting position.
  12482. This will move the path's current position to the co-ordinates passed in and
  12483. make it ready to draw lines or curves starting from this position.
  12484. After adding whatever lines and curves are needed, you can either
  12485. close the current sub-path using closeSubPath() or call startNewSubPath()
  12486. to move to a new sub-path, leaving the old one open-ended.
  12487. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12488. */
  12489. void startNewSubPath (const float startX,
  12490. const float startY) throw();
  12491. /** Closes a the current sub-path with a line back to its start-point.
  12492. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12493. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12494. to join the final point back to the start.
  12495. This ensures that closes shapes are recognised as such, and this is
  12496. important for tasks like drawing strokes, which needs to know whether to
  12497. draw end-caps or not.
  12498. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12499. */
  12500. void closeSubPath() throw();
  12501. /** Adds a line from the shape's last position to a new end-point.
  12502. This will connect the end-point of the last line or curve that was added
  12503. to a new point, using a straight line.
  12504. See the class description for an example of how to add lines and curves to a path.
  12505. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12506. */
  12507. void lineTo (const float endX,
  12508. const float endY) throw();
  12509. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12510. This will connect the end-point of the last line or curve that was added
  12511. to a new point, using a quadratic spline with one control-point.
  12512. See the class description for an example of how to add lines and curves to a path.
  12513. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12514. */
  12515. void quadraticTo (const float controlPointX,
  12516. const float controlPointY,
  12517. const float endPointX,
  12518. const float endPointY) throw();
  12519. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12520. This will connect the end-point of the last line or curve that was added
  12521. to a new point, using a cubic spline with two control-points.
  12522. See the class description for an example of how to add lines and curves to a path.
  12523. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12524. */
  12525. void cubicTo (const float controlPoint1X,
  12526. const float controlPoint1Y,
  12527. const float controlPoint2X,
  12528. const float controlPoint2Y,
  12529. const float endPointX,
  12530. const float endPointY) throw();
  12531. /** Returns the last point that was added to the path by one of the drawing methods.
  12532. */
  12533. const Point getCurrentPosition() const;
  12534. /** Adds a rectangle to the path.
  12535. The rectangle is added as a new sub-path. (Any currently open paths will be
  12536. left open).
  12537. @see addRoundedRectangle, addTriangle
  12538. */
  12539. void addRectangle (const float x, const float y,
  12540. const float w, const float h) throw();
  12541. /** Adds a rectangle with rounded corners to the path.
  12542. The rectangle is added as a new sub-path. (Any currently open paths will be
  12543. left open).
  12544. @see addRectangle, addTriangle
  12545. */
  12546. void addRoundedRectangle (const float x, const float y,
  12547. const float w, const float h,
  12548. float cornerSize) throw();
  12549. /** Adds a rectangle with rounded corners to the path.
  12550. The rectangle is added as a new sub-path. (Any currently open paths will be
  12551. left open).
  12552. @see addRectangle, addTriangle
  12553. */
  12554. void addRoundedRectangle (const float x, const float y,
  12555. const float w, const float h,
  12556. float cornerSizeX,
  12557. float cornerSizeY) throw();
  12558. /** Adds a triangle to the path.
  12559. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12560. left open).
  12561. Note that whether the vertices are specified in clockwise or anticlockwise
  12562. order will affect how the triangle is filled when it overlaps other
  12563. shapes (the winding order setting will affect this of course).
  12564. */
  12565. void addTriangle (const float x1, const float y1,
  12566. const float x2, const float y2,
  12567. const float x3, const float y3) throw();
  12568. /** Adds a quadrilateral to the path.
  12569. The quad is added as a new closed sub-path. (Any currently open paths will be
  12570. left open).
  12571. Note that whether the vertices are specified in clockwise or anticlockwise
  12572. order will affect how the quad is filled when it overlaps other
  12573. shapes (the winding order setting will affect this of course).
  12574. */
  12575. void addQuadrilateral (const float x1, const float y1,
  12576. const float x2, const float y2,
  12577. const float x3, const float y3,
  12578. const float x4, const float y4) throw();
  12579. /** Adds an ellipse to the path.
  12580. The shape is added as a new sub-path. (Any currently open paths will be
  12581. left open).
  12582. @see addArc
  12583. */
  12584. void addEllipse (const float x, const float y,
  12585. const float width, const float height) throw();
  12586. /** Adds an elliptical arc to the current path.
  12587. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12588. or anti-clockwise according to whether the end angle is greater than the start. This means
  12589. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12590. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12591. @param y the top edge of the rectangle in which the elliptical outline fits
  12592. @param width the width of the rectangle in which the elliptical outline fits
  12593. @param height the height of the rectangle in which the elliptical outline fits
  12594. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12595. top-centre of the ellipse)
  12596. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12597. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12598. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12599. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12600. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12601. it will be added to the current sub-path, continuing from the current postition
  12602. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12603. */
  12604. void addArc (const float x, const float y,
  12605. const float width, const float height,
  12606. const float fromRadians,
  12607. const float toRadians,
  12608. const bool startAsNewSubPath = false) throw();
  12609. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12610. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12611. or anti-clockwise according to whether the end angle is greater than the start. This means
  12612. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12613. @param centreX the centre x of the ellipse
  12614. @param centreY the centre y of the ellipse
  12615. @param radiusX the horizontal radius of the ellipse
  12616. @param radiusY the vertical radius of the ellipse
  12617. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12618. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12619. top-centre of the ellipse)
  12620. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12621. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12622. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12623. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12624. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12625. it will be added to the current sub-path, continuing from the current postition
  12626. @see addArc, arcTo
  12627. */
  12628. void addCentredArc (const float centreX, const float centreY,
  12629. const float radiusX, const float radiusY,
  12630. const float rotationOfEllipse,
  12631. const float fromRadians,
  12632. const float toRadians,
  12633. const bool startAsNewSubPath = false) throw();
  12634. /** Adds a "pie-chart" shape to the path.
  12635. The shape is added as a new sub-path. (Any currently open paths will be
  12636. left open).
  12637. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12638. or anti-clockwise according to whether the end angle is greater than the start. This means
  12639. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12640. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12641. @param y the top edge of the rectangle in which the elliptical outline fits
  12642. @param width the width of the rectangle in which the elliptical outline fits
  12643. @param height the height of the rectangle in which the elliptical outline fits
  12644. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12645. top-centre of the ellipse)
  12646. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12647. top-centre of the ellipse)
  12648. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12649. ellipse at its centre, where this value indicates the inner ellipse's size with
  12650. respect to the outer one.
  12651. @see addArc
  12652. */
  12653. void addPieSegment (const float x, const float y,
  12654. const float width, const float height,
  12655. const float fromRadians,
  12656. const float toRadians,
  12657. const float innerCircleProportionalSize);
  12658. /** Adds a line with a specified thickness.
  12659. The line is added as a new closed sub-path. (Any currently open paths will be
  12660. left open).
  12661. @see addArrow
  12662. */
  12663. void addLineSegment (const float startX, const float startY,
  12664. const float endX, const float endY,
  12665. float lineThickness) throw();
  12666. /** Adds a line with an arrowhead on the end.
  12667. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12668. left open).
  12669. */
  12670. void addArrow (const float startX, const float startY,
  12671. const float endX, const float endY,
  12672. float lineThickness,
  12673. float arrowheadWidth,
  12674. float arrowheadLength) throw();
  12675. /** Adds a star shape to the path.
  12676. */
  12677. void addStar (const float centreX,
  12678. const float centreY,
  12679. const int numberOfPoints,
  12680. const float innerRadius,
  12681. const float outerRadius,
  12682. const float startAngle = 0.0f);
  12683. /** Adds a speech-bubble shape to the path.
  12684. @param bodyX the left of the main body area of the bubble
  12685. @param bodyY the top of the main body area of the bubble
  12686. @param bodyW the width of the main body area of the bubble
  12687. @param bodyH the height of the main body area of the bubble
  12688. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12689. @param arrowTipX the x position that the tip of the arrow should connect to
  12690. @param arrowTipY the y position that the tip of the arrow should connect to
  12691. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12692. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12693. arrow's base should be - this is a proportional distance between 0 and 1.0
  12694. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12695. */
  12696. void addBubble (float bodyX, float bodyY,
  12697. float bodyW, float bodyH,
  12698. float cornerSize,
  12699. float arrowTipX,
  12700. float arrowTipY,
  12701. int whichSide,
  12702. float arrowPositionAlongEdgeProportional,
  12703. float arrowWidth);
  12704. /** Adds another path to this one.
  12705. The new path is added as a new sub-path. (Any currently open paths in this
  12706. path will be left open).
  12707. @param pathToAppend the path to add
  12708. */
  12709. void addPath (const Path& pathToAppend) throw();
  12710. /** Adds another path to this one, transforming it on the way in.
  12711. The new path is added as a new sub-path, its points being transformed by the given
  12712. matrix before being added.
  12713. @param pathToAppend the path to add
  12714. @param transformToApply an optional transform to apply to the incoming vertices
  12715. */
  12716. void addPath (const Path& pathToAppend,
  12717. const AffineTransform& transformToApply) throw();
  12718. /** Swaps the contents of this path with another one.
  12719. The internal data of the two paths is swapped over, so this is much faster than
  12720. copying it to a temp variable and back.
  12721. */
  12722. void swapWithPath (Path& other);
  12723. /** Applies a 2D transform to all the vertices in the path.
  12724. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12725. */
  12726. void applyTransform (const AffineTransform& transform) throw();
  12727. /** Rescales this path to make it fit neatly into a given space.
  12728. This is effectively a quick way of calling
  12729. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12730. @param x the x position of the rectangle to fit the path inside
  12731. @param y the y position of the rectangle to fit the path inside
  12732. @param width the width of the rectangle to fit the path inside
  12733. @param height the height of the rectangle to fit the path inside
  12734. @param preserveProportions if true, it will fit the path into the space without altering its
  12735. horizontal/vertical scale ratio; if false, it will distort the
  12736. path to fill the specified ratio both horizontally and vertically
  12737. @see applyTransform, getTransformToScaleToFit
  12738. */
  12739. void scaleToFit (const float x, const float y,
  12740. const float width, const float height,
  12741. const bool preserveProportions) throw();
  12742. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12743. @param x the x position of the rectangle to fit the path inside
  12744. @param y the y position of the rectangle to fit the path inside
  12745. @param width the width of the rectangle to fit the path inside
  12746. @param height the height of the rectangle to fit the path inside
  12747. @param preserveProportions if true, it will fit the path into the space without altering its
  12748. horizontal/vertical scale ratio; if false, it will distort the
  12749. path to fill the specified ratio both horizontally and vertically
  12750. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12751. than the available rectangle, so this describes how it should be
  12752. positioned within the space.
  12753. @returns an appropriate transformation
  12754. @see applyTransform, scaleToFit
  12755. */
  12756. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12757. const float width, const float height,
  12758. const bool preserveProportions,
  12759. const Justification& justificationType = Justification::centred) const throw();
  12760. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12761. Wherever two lines meet at an angle, this will replace the corner with a curve
  12762. of the given radius.
  12763. */
  12764. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12765. /** Changes the winding-rule to be used when filling the path.
  12766. If set to true (which is the default), then the path uses a non-zero-winding rule
  12767. to determine which points are inside the path. If set to false, it uses an
  12768. alternate-winding rule.
  12769. The winding-rule comes into play when areas of the shape overlap other
  12770. areas, and determines whether the overlapping regions are considered to be
  12771. inside or outside.
  12772. Changing this value just sets a flag - it doesn't affect the contents of the
  12773. path.
  12774. @see isUsingNonZeroWinding
  12775. */
  12776. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12777. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12778. The default for a new path is true.
  12779. @see setUsingNonZeroWinding
  12780. */
  12781. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12782. /** Iterates the lines and curves that a path contains.
  12783. @see Path, PathFlatteningIterator
  12784. */
  12785. class JUCE_API Iterator
  12786. {
  12787. public:
  12788. Iterator (const Path& path);
  12789. ~Iterator();
  12790. /** Moves onto the next element in the path.
  12791. If this returns false, there are no more elements. If it returns true,
  12792. the elementType variable will be set to the type of the current element,
  12793. and some of the x and y variables will be filled in with values.
  12794. */
  12795. bool next();
  12796. enum PathElementType
  12797. {
  12798. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12799. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12800. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12801. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12802. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12803. };
  12804. PathElementType elementType;
  12805. float x1, y1, x2, y2, x3, y3;
  12806. private:
  12807. const Path& path;
  12808. int index;
  12809. Iterator (const Iterator&);
  12810. const Iterator& operator= (const Iterator&);
  12811. };
  12812. /** Loads a stored path from a data stream.
  12813. The data in the stream must have been written using writePathToStream().
  12814. Note that this will append the stored path to whatever is currently in
  12815. this path, so you might need to call clear() beforehand.
  12816. @see loadPathFromData, writePathToStream
  12817. */
  12818. void loadPathFromStream (InputStream& source);
  12819. /** Loads a stored path from a block of data.
  12820. This is similar to loadPathFromStream(), but just reads from a block
  12821. of data. Useful if you're including stored shapes in your code as a
  12822. block of static data.
  12823. @see loadPathFromStream, writePathToStream
  12824. */
  12825. void loadPathFromData (const unsigned char* const data,
  12826. const int numberOfBytes) throw();
  12827. /** Stores the path by writing it out to a stream.
  12828. After writing out a path, you can reload it using loadPathFromStream().
  12829. @see loadPathFromStream, loadPathFromData
  12830. */
  12831. void writePathToStream (OutputStream& destination) const;
  12832. /** Creates a string containing a textual representation of this path.
  12833. @see restoreFromString
  12834. */
  12835. const String toString() const;
  12836. /** Restores this path from a string that was created with the toString() method.
  12837. @see toString()
  12838. */
  12839. void restoreFromString (const String& stringVersion);
  12840. juce_UseDebuggingNewOperator
  12841. private:
  12842. friend class PathFlatteningIterator;
  12843. friend class Path::Iterator;
  12844. int numElements;
  12845. float pathXMin, pathXMax, pathYMin, pathYMax;
  12846. bool useNonZeroWinding;
  12847. static const float lineMarker;
  12848. static const float moveMarker;
  12849. static const float quadMarker;
  12850. static const float cubicMarker;
  12851. static const float closeSubPathMarker;
  12852. };
  12853. #endif // __JUCE_PATH_JUCEHEADER__
  12854. /********* End of inlined file: juce_Path.h *********/
  12855. class Font;
  12856. class Typeface;
  12857. /**
  12858. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12859. @see Typeface, PositionedGlyph, GlyphArrangement
  12860. */
  12861. class JUCE_API TypefaceGlyphInfo
  12862. {
  12863. public:
  12864. /** Returns the path that describes the glyph's outline.
  12865. This is normalised to a height of 1.0, and its origin is the
  12866. left-hand edge of the glyph's baseline.
  12867. */
  12868. const Path& getPath() const throw() { return path; }
  12869. /** Returns the unicode character that this glyph represents. */
  12870. juce_wchar getCharacter() const throw() { return character; }
  12871. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12872. /** Returns the distance to leave between this and a following character.
  12873. The value returned is expressed as a proportion of the font's height.
  12874. */
  12875. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12876. /** Returns the typeface that this glyph belongs to. */
  12877. Typeface* getTypeface() const throw() { return typeface; }
  12878. private:
  12879. friend class Typeface;
  12880. struct KerningPair
  12881. {
  12882. juce_wchar character2;
  12883. float kerningAmount;
  12884. };
  12885. const juce_wchar character;
  12886. const Path path;
  12887. float width;
  12888. MemoryBlock kerningPairs;
  12889. Typeface* const typeface;
  12890. TypefaceGlyphInfo (const juce_wchar character,
  12891. const Path& shape,
  12892. const float horizontalSeparation,
  12893. Typeface* const typeface) throw();
  12894. ~TypefaceGlyphInfo() throw();
  12895. KerningPair& getKerningPair (const int index) const throw();
  12896. int getNumKerningPairs() const throw();
  12897. void addKerningPair (const juce_wchar subsequentCharacter,
  12898. const float extraKerningAmount) throw();
  12899. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12900. };
  12901. /**
  12902. Represents a size-independent system font.
  12903. A Font object represents a particular Typeface along with a specific size,
  12904. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12905. of the shapes of the glyphs and their properties.
  12906. */
  12907. class JUCE_API Typeface : public ReferenceCountedObject
  12908. {
  12909. public:
  12910. /** Tries to load a named system font and to initialise all the glyphs
  12911. appropriately from it.
  12912. @param faceName the name of the typeface, e.g. "Times"
  12913. @param bold whether to try to find a bold version of the font (may not always be available)
  12914. @param italic whether to try to find an italicised version of the font (may not always be available)
  12915. */
  12916. Typeface (const String& faceName,
  12917. const bool bold,
  12918. const bool italic);
  12919. /** Creates a copy of another typeface */
  12920. Typeface (const Typeface& other);
  12921. /** Destructor. */
  12922. ~Typeface();
  12923. /** Copies another typeface over this one. */
  12924. const Typeface& operator= (const Typeface& other) throw();
  12925. /** Returns a unique ID for the typeface.
  12926. This is based on the name and style, so can be used to compare two Typeface objects.
  12927. */
  12928. int hashCode() const throw() { return hash; }
  12929. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12930. const String& getName() const throw() { return typefaceName; }
  12931. /** Returns the font's ascent as a proportion of its height. */
  12932. float getAscent() const throw() { return ascent; }
  12933. /** Returns true if the font is flagged as being bold. */
  12934. bool isBold() const throw() { return bold; }
  12935. /** Returns true if the typeface's 'italic' flag is set. */
  12936. bool isItalic() const throw() { return italic; }
  12937. /** Finds the Path that describes the outline shape of a character.
  12938. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12939. height of the font).
  12940. This may return 0 if the typeface has no characters, but if the character
  12941. that is asked for is not found, it will first try to return a default
  12942. character instead.
  12943. */
  12944. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12945. /** Tries to find the information describing a glyph for this character.
  12946. If there isn't a glyph specifically for the character it will return
  12947. a default glyph instead; if the typeface is empty, it may return a null
  12948. pointer.
  12949. */
  12950. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12951. /** Deletes all the glyphs and kerning data fom the typeface. */
  12952. void clear() throw();
  12953. /** Adds a glyph to the typeface.
  12954. This is typically only called by the platform-specific code that generates
  12955. the typeface from a system font.
  12956. */
  12957. void addGlyph (const juce_wchar character,
  12958. const Path& path,
  12959. const float horizontalSpacing) throw();
  12960. /** Adds a kerning distance to the typeface.
  12961. The extra amount passed in is expressed as a proportion of the font's
  12962. height, normalised to 1.0.
  12963. This is typically only called by the platform-specific code that generates
  12964. the typeface from a system font.
  12965. */
  12966. void addKerningPair (const juce_wchar firstChar,
  12967. const juce_wchar secondChar,
  12968. const float extraAmount) throw();
  12969. /** Sets the typeface's name.
  12970. This is typically only called by the platform-specific code that generates
  12971. the typeface from a system font. Calling this method won't actually affect
  12972. the underlying font being used.
  12973. */
  12974. void setName (const String& name) throw();
  12975. /** Sets the font's ascent value, as a proportion of the font height.
  12976. This is typically only called by the platform-specific code that generates
  12977. the typeface from a system font.
  12978. */
  12979. void setAscent (const float newAscent) throw();
  12980. /** Sets the typeface's 'bold' flag.
  12981. This is typically only called by the platform-specific code that generates
  12982. the typeface from a system font.
  12983. */
  12984. void setBold (const bool shouldBeBold) throw();
  12985. /** Sets the typeface's 'italic' flag.
  12986. This is typically only called by the platform-specific code that generates
  12987. the typeface from a system font.
  12988. */
  12989. void setItalic (const bool shouldBeItalic) throw();
  12990. /** Changes the character index to use as the default character.
  12991. This is the character that gets returned for characters which don't have a
  12992. glyph set for them.
  12993. */
  12994. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12995. /** Creates a typeface from data created using Typeface::serialise().
  12996. This will attempt to load a compressed typeface that was created using
  12997. the Typeface::serialise() method. This is handy if you want to store
  12998. a typeface in your application as a binary blob, and use it without
  12999. having to actually install it on the computer.
  13000. @see Typeface::serialise()
  13001. */
  13002. Typeface (InputStream& serialisedTypefaceStream);
  13003. /** Writes the typeface to a stream (using a proprietary format).
  13004. This lets you save a typeface and reload it using the
  13005. Typeface::Typeface (InputStream&) constructor. The data's saved in
  13006. a compressed format.
  13007. @see Typeface::Typeface (InputStream&)
  13008. */
  13009. void serialise (OutputStream& outputStream);
  13010. /** A name that represents the default sans-serif typeface name.
  13011. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13012. is a generic string that represents whatever that font is, such as "DefaultSans".
  13013. If you try to create a typeface with this name, the global default LookAndFeel
  13014. object will be asked to provide an appropriate typeface.
  13015. */
  13016. static const tchar* defaultTypefaceNameSans;
  13017. /** A name that represents the default serif typeface name.
  13018. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13019. is a generic string that represents it, such as "DefaultSans".
  13020. If you try to create a typeface with this name, the global default LookAndFeel
  13021. object will be asked to provide an appropriate typeface.
  13022. */
  13023. static const tchar* defaultTypefaceNameSerif;
  13024. /** A name that represents the default monospaced typeface name.
  13025. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13026. is a generic string that represents it, such as "DefaultSans".
  13027. If you try to create a typeface with this name, the global default LookAndFeel
  13028. object will be asked to provide an appropriate typeface.
  13029. */
  13030. static const tchar* defaultTypefaceNameMono;
  13031. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  13032. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  13033. juce_UseDebuggingNewOperator
  13034. private:
  13035. VoidArray glyphs;
  13036. short lookupTable [128];
  13037. String typefaceName;
  13038. int hash;
  13039. float ascent; // as a proportion of the height
  13040. bool bold, italic, isFullyPopulated;
  13041. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  13042. Typeface() throw();
  13043. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  13044. friend class Font;
  13045. friend class TypefaceCache;
  13046. friend class FontGlyphAlphaMap;
  13047. static const Ptr getTypefaceFor (const Font& font) throw();
  13048. // this is a platform-dependent method that will look for the given typeface
  13049. // and set up its kerning tables, etc. accordingly.
  13050. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  13051. // to the typeface immediately, rather than having to add them later on-demand.
  13052. void initialiseTypefaceCharacteristics (const String& fontName,
  13053. bool bold, bool italic,
  13054. bool addAllGlyphsToFont) throw();
  13055. // platform-specific routine to look up and add a glyph to this typeface
  13056. bool findAndAddSystemGlyph (juce_wchar character) throw();
  13057. void updateHashCode() throw();
  13058. friend class LookAndFeel;
  13059. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13060. };
  13061. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  13062. /********* End of inlined file: juce_Typeface.h *********/
  13063. /**
  13064. Represents a particular font, including its size, style, etc.
  13065. Apart from the typeface to be used, a Font object also dictates whether
  13066. the font is bold, italic, underlined, how big it is, and its kerning and
  13067. horizontal scale factor.
  13068. @see Typeface
  13069. */
  13070. class JUCE_API Font
  13071. {
  13072. public:
  13073. /** A combination of these values is used by the constructor to specify the
  13074. style of font to use.
  13075. */
  13076. enum FontStyleFlags
  13077. {
  13078. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  13079. bold = 1, /**< boldens the font. @see setStyleFlags */
  13080. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  13081. underlined = 4 /**< underlines the font. @see setStyleFlags */
  13082. };
  13083. /** Creates a sans-serif font in a given size.
  13084. @param fontHeight the height in pixels (can be fractional)
  13085. @param styleFlags the style to use - this can be a combination of the
  13086. Font::bold, Font::italic and Font::underlined, or
  13087. just Font::plain for the normal style.
  13088. @see FontStyleFlags, getDefaultSansSerifFontName
  13089. */
  13090. Font (const float fontHeight,
  13091. const int styleFlags = plain) throw();
  13092. /** Creates a font with a given typeface and parameters.
  13093. @param typefaceName the name of the typeface to use
  13094. @param fontHeight the height in pixels (can be fractional)
  13095. @param styleFlags the style to use - this can be a combination of the
  13096. Font::bold, Font::italic and Font::underlined, or
  13097. just Font::plain for the normal style.
  13098. @see FontStyleFlags, getDefaultSansSerifFontName
  13099. */
  13100. Font (const String& typefaceName,
  13101. const float fontHeight,
  13102. const int styleFlags) throw();
  13103. /** Creates a copy of another Font object. */
  13104. Font (const Font& other) throw();
  13105. /** Creates a font based on a typeface.
  13106. The font object stores its own internal copy of the typeface, so you can safely
  13107. delete the one passed in after calling this.
  13108. */
  13109. Font (const Typeface& typeface) throw();
  13110. /** Creates a basic sans-serif font at a default height.
  13111. You should use one of the other constructors for creating a font that you're planning
  13112. on drawing with - this constructor is here to help initialise objects before changing
  13113. the font's settings later.
  13114. */
  13115. Font() throw();
  13116. /** Copies this font from another one. */
  13117. const Font& operator= (const Font& other) throw();
  13118. bool operator== (const Font& other) const throw();
  13119. bool operator!= (const Font& other) const throw();
  13120. /** Destructor. */
  13121. ~Font() throw();
  13122. /** Changes the name of the typeface family.
  13123. e.g. "Arial", "Courier", etc.
  13124. This may also be set to Typeface::defaultTypefaceNameSans, Typeface::defaultTypefaceNameSerif,
  13125. or Typeface::defaultTypefaceNameMono, which are not actual platform-specific font names, but
  13126. are generic names that are used to represent the various default fonts.
  13127. If a suitable font isn't found on the machine, it'll just use a default instead.
  13128. */
  13129. void setTypefaceName (const String& faceName) throw();
  13130. /** Returns the name of the typeface family that this font uses.
  13131. e.g. "Arial", "Courier", etc.
  13132. Note that this may also be one of the values: Typeface::defaultTypefaceNameSans,
  13133. Typeface::defaultTypefaceNameSerif, or Typeface::defaultTypefaceNameMono, which are not actual
  13134. platform-specific font names, but are generic names that are used to represent the various
  13135. default fonts. If you need to know the exact typeface name being used, you can call
  13136. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  13137. */
  13138. const String& getTypefaceName() const throw() { return typefaceName; }
  13139. /** Returns a typeface name that represents the default sans-serif font.
  13140. This is also the typeface that will be used when a font is created without
  13141. specifying any typeface details.
  13142. Note that this method just returns the same value as Typeface::defaultTypefaceNameSans,
  13143. which is a generic placeholder string, and not a platform-specific font name.
  13144. @see Typeface::defaultTypefaceNameSans, setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  13145. */
  13146. static const String getDefaultSansSerifFontName() throw() { return Typeface::defaultTypefaceNameSans; }
  13147. /** Returns a typeface name that represents the default sans-serif font.
  13148. Note that this method just returns the same value as Typeface::defaultTypefaceNameSerif,
  13149. which is a generic placeholder string, and not a platform-specific font name.
  13150. @see Typeface::defaultTypefaceNameSerif, setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13151. */
  13152. static const String getDefaultSerifFontName() throw() { return Typeface::defaultTypefaceNameSerif; }
  13153. /** Returns a typeface name that represents the default sans-serif font.
  13154. Note that this method just returns the same value as Typeface::defaultTypefaceNameMono,
  13155. which is a generic placeholder string, and not a platform-specific font name.
  13156. @see Typeface::defaultTypefaceNameMono, setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13157. */
  13158. static const String getDefaultMonospacedFontName() throw() { return Typeface::defaultTypefaceNameMono; }
  13159. /** Returns the total height of this font.
  13160. This is the maximum height, from the top of the ascent to the bottom of the
  13161. descenders.
  13162. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13163. */
  13164. float getHeight() const throw() { return height; }
  13165. /** Changes the font's height.
  13166. @see getHeight, setHeightWithoutChangingWidth
  13167. */
  13168. void setHeight (float newHeight) throw();
  13169. /** Changes the font's height without changing its width.
  13170. This alters the horizontal scale to compensate for the change in height.
  13171. */
  13172. void setHeightWithoutChangingWidth (float newHeight) throw();
  13173. /** Returns the height of the font above its baseline.
  13174. This is the maximum height from the baseline to the top.
  13175. @see getHeight, getDescent
  13176. */
  13177. float getAscent() const throw();
  13178. /** Returns the amount that the font descends below its baseline.
  13179. This is calculated as (getHeight() - getAscent()).
  13180. @see getAscent, getHeight
  13181. */
  13182. float getDescent() const throw();
  13183. /** Returns the font's style flags.
  13184. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13185. enum, to describe whether the font is bold, italic, etc.
  13186. @see FontStyleFlags
  13187. */
  13188. int getStyleFlags() const throw() { return styleFlags; }
  13189. /** Changes the font's style.
  13190. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13191. enum, to set the font's properties
  13192. @see FontStyleFlags
  13193. */
  13194. void setStyleFlags (const int newFlags) throw();
  13195. /** Makes the font bold or non-bold. */
  13196. void setBold (const bool shouldBeBold) throw();
  13197. /** Returns true if the font is bold. */
  13198. bool isBold() const throw();
  13199. /** Makes the font italic or non-italic. */
  13200. void setItalic (const bool shouldBeItalic) throw();
  13201. /** Returns true if the font is italic. */
  13202. bool isItalic() const throw();
  13203. /** Makes the font underlined or non-underlined. */
  13204. void setUnderline (const bool shouldBeUnderlined) throw();
  13205. /** Returns true if the font is underlined. */
  13206. bool isUnderlined() const throw();
  13207. /** Changes the font's horizontal scale factor.
  13208. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13209. narrower, greater than 1.0 will be stretched out.
  13210. */
  13211. void setHorizontalScale (const float scaleFactor) throw();
  13212. /** Returns the font's horizontal scale.
  13213. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13214. than 1.0 will be stretched out.
  13215. @see setHorizontalScale
  13216. */
  13217. float getHorizontalScale() const throw() { return horizontalScale; }
  13218. /** Changes the font's kerning.
  13219. @param extraKerning a multiple of the font's height that will be added
  13220. to space between the characters. So a value of zero is
  13221. normal spacing, positive values spread the letters out,
  13222. negative values make them closer together.
  13223. */
  13224. void setExtraKerningFactor (const float extraKerning) throw();
  13225. /** Returns the font's kerning.
  13226. This is the extra space added between adjacent characters, as a proportion
  13227. of the font's height.
  13228. A value of zero is normal spacing, positive values will spread the letters
  13229. out more, and negative values make them closer together.
  13230. */
  13231. float getExtraKerningFactor() const throw() { return kerning; }
  13232. /** Changes all the font's characteristics with one call. */
  13233. void setSizeAndStyle (const float newHeight,
  13234. const int newStyleFlags,
  13235. const float newHorizontalScale,
  13236. const float newKerningAmount) throw();
  13237. /** Resets this font's characteristics.
  13238. This is basically like saying "myFont = Font();", because it resets the
  13239. typeface, size, style, etc to a default state. Not very useful to most
  13240. people, its raison d'etre is to help the Graphics class be more efficient.
  13241. */
  13242. void resetToDefaultState() throw();
  13243. /** Returns the total width of a string as it would be drawn using this font.
  13244. For a more accurate floating-point result, use getStringWidthFloat().
  13245. */
  13246. int getStringWidth (const String& text) const throw();
  13247. /** Returns the total width of a string as it would be drawn using this font.
  13248. @see getStringWidth
  13249. */
  13250. float getStringWidthFloat (const String& text) const throw();
  13251. /** Returns the typeface used by this font.
  13252. Note that the object returned may go out of scope if this font is deleted
  13253. or has its style changed.
  13254. */
  13255. Typeface* getTypeface() const throw();
  13256. /** Creates an array of Font objects to represent all the fonts on the system.
  13257. If you just need the names of the typefaces, you can also use
  13258. findAllTypefaceNames() instead.
  13259. @param results the array to which new Font objects will be added.
  13260. */
  13261. static void findFonts (OwnedArray<Font>& results) throw();
  13262. /** Returns a list of all the available typeface names.
  13263. The names returned can be passed into setTypefaceName().
  13264. You can use this instead of findFonts() if you only need their names, and not
  13265. font objects.
  13266. */
  13267. static const StringArray findAllTypefaceNames() throw();
  13268. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13269. in the requested typeface.
  13270. */
  13271. static const String getFallbackFontName() throw();
  13272. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13273. available in whatever font you're trying to use.
  13274. */
  13275. static void setFallbackFontName (const String& name) throw();
  13276. juce_UseDebuggingNewOperator
  13277. private:
  13278. friend class FontGlyphAlphaMap;
  13279. friend class TypefaceCache;
  13280. String typefaceName;
  13281. float height, horizontalScale, kerning;
  13282. mutable float ascent;
  13283. int styleFlags;
  13284. mutable Typeface::Ptr typeface;
  13285. };
  13286. #endif // __JUCE_FONT_JUCEHEADER__
  13287. /********* End of inlined file: juce_Font.h *********/
  13288. /********* Start of inlined file: juce_Rectangle.h *********/
  13289. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13290. #define __JUCE_RECTANGLE_JUCEHEADER__
  13291. /**
  13292. A rectangle, specified using integer co-ordinates.
  13293. @see RectangleList, Path, Line, Point
  13294. */
  13295. class JUCE_API Rectangle
  13296. {
  13297. public:
  13298. /** Creates a rectangle of zero size.
  13299. The default co-ordinates will be (0, 0, 0, 0).
  13300. */
  13301. Rectangle() throw();
  13302. /** Creates a copy of another rectangle. */
  13303. Rectangle (const Rectangle& other) throw();
  13304. /** Creates a rectangle with a given position and size. */
  13305. Rectangle (const int x, const int y,
  13306. const int width, const int height) throw();
  13307. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13308. Rectangle (const int width, const int height) throw();
  13309. /** Destructor. */
  13310. ~Rectangle() throw();
  13311. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13312. inline int getX() const throw() { return x; }
  13313. /** Returns the y co-ordinate of the rectangle's top edge. */
  13314. inline int getY() const throw() { return y; }
  13315. /** Returns the width of the rectangle. */
  13316. inline int getWidth() const throw() { return w; }
  13317. /** Returns the height of the rectangle. */
  13318. inline int getHeight() const throw() { return h; }
  13319. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13320. inline int getRight() const throw() { return x + w; }
  13321. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13322. inline int getBottom() const throw() { return y + h; }
  13323. /** Returns the x co-ordinate of the rectangle's centre. */
  13324. inline int getCentreX() const throw() { return x + (w >> 1); }
  13325. /** Returns the y co-ordinate of the rectangle's centre. */
  13326. inline int getCentreY() const throw() { return y + (h >> 1); }
  13327. /** Returns true if the rectangle's width and height are both zero or less */
  13328. bool isEmpty() const throw();
  13329. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13330. void setPosition (const int x, const int y) throw();
  13331. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13332. void setSize (const int w, const int h) throw();
  13333. /** Changes all the rectangle's co-ordinates. */
  13334. void setBounds (const int newX, const int newY,
  13335. const int newWidth, const int newHeight) throw();
  13336. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  13337. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  13338. */
  13339. void setLeft (const int newLeft) throw();
  13340. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  13341. If the y is moved to be below the current bottom edge, the height will be set to zero.
  13342. */
  13343. void setTop (const int newTop) throw();
  13344. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  13345. If the new right is below the current X value, the X will be pushed down to match it.
  13346. @see getRight
  13347. */
  13348. void setRight (const int newRight) throw();
  13349. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  13350. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  13351. @see getBottom
  13352. */
  13353. void setBottom (const int newBottom) throw();
  13354. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13355. void translate (const int deltaX,
  13356. const int deltaY) throw();
  13357. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13358. const Rectangle translated (const int deltaX,
  13359. const int deltaY) const throw();
  13360. /** Expands the rectangle by a given amount.
  13361. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13362. @see expanded, reduce, reduced
  13363. */
  13364. void expand (const int deltaX,
  13365. const int deltaY) throw();
  13366. /** Returns a rectangle that is larger than this one by a given amount.
  13367. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13368. @see expand, reduce, reduced
  13369. */
  13370. const Rectangle expanded (const int deltaX,
  13371. const int deltaY) const throw();
  13372. /** Shrinks the rectangle by a given amount.
  13373. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13374. @see reduced, expand, expanded
  13375. */
  13376. void reduce (const int deltaX,
  13377. const int deltaY) throw();
  13378. /** Returns a rectangle that is smaller than this one by a given amount.
  13379. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13380. @see reduce, expand, expanded
  13381. */
  13382. const Rectangle reduced (const int deltaX,
  13383. const int deltaY) const throw();
  13384. /** Returns true if the two rectangles are identical. */
  13385. bool operator== (const Rectangle& other) const throw();
  13386. /** Returns true if the two rectangles are not identical. */
  13387. bool operator!= (const Rectangle& other) const throw();
  13388. /** Returns true if this co-ordinate is inside the rectangle. */
  13389. bool contains (const int x, const int y) const throw();
  13390. /** Returns true if this other rectangle is completely inside this one. */
  13391. bool contains (const Rectangle& other) const throw();
  13392. /** Returns true if any part of another rectangle overlaps this one. */
  13393. bool intersects (const Rectangle& other) const throw();
  13394. /** Returns the region that is the overlap between this and another rectangle.
  13395. If the two rectangles don't overlap, the rectangle returned will be empty.
  13396. */
  13397. const Rectangle getIntersection (const Rectangle& other) const throw();
  13398. /** Clips a rectangle so that it lies only within this one.
  13399. This is a non-static version of intersectRectangles().
  13400. Returns false if the two regions didn't overlap.
  13401. */
  13402. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13403. /** Returns the smallest rectangle that contains both this one and the one
  13404. passed-in.
  13405. */
  13406. const Rectangle getUnion (const Rectangle& other) const throw();
  13407. /** If this rectangle merged with another one results in a simple rectangle, this
  13408. will set this rectangle to the result, and return true.
  13409. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13410. or if they form a complex region.
  13411. */
  13412. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13413. /** If after removing another rectangle from this one the result is a simple rectangle,
  13414. this will set this object's bounds to be the result, and return true.
  13415. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13416. or if removing the other one would form a complex region.
  13417. */
  13418. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13419. /** Static utility to intersect two sets of rectangular co-ordinates.
  13420. Returns false if the two regions didn't overlap.
  13421. @see intersectRectangle
  13422. */
  13423. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13424. int x2, int y2, int w2, int h2) throw();
  13425. /** Creates a string describing this rectangle.
  13426. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13427. Coupled with the fromString() method, this is very handy for things like
  13428. storing rectangles (particularly component positions) in XML attributes.
  13429. @see fromString
  13430. */
  13431. const String toString() const throw();
  13432. /** Parses a string containing a rectangle's details.
  13433. The string should contain 4 integer tokens, in the form "x y width height". They
  13434. can be comma or whitespace separated.
  13435. This method is intended to go with the toString() method, to form an easy way
  13436. of saving/loading rectangles as strings.
  13437. @see toString
  13438. */
  13439. static const Rectangle fromString (const String& stringVersion);
  13440. juce_UseDebuggingNewOperator
  13441. private:
  13442. friend class RectangleList;
  13443. int x, y, w, h;
  13444. };
  13445. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13446. /********* End of inlined file: juce_Rectangle.h *********/
  13447. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13448. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13449. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13450. /**
  13451. Describes a type of stroke used to render a solid outline along a path.
  13452. A PathStrokeType object can be used directly to create the shape of an outline
  13453. around a path, and is used by Graphics::strokePath to specify the type of
  13454. stroke to draw.
  13455. @see Path, Graphics::strokePath
  13456. */
  13457. class JUCE_API PathStrokeType
  13458. {
  13459. public:
  13460. /** The type of shape to use for the corners between two adjacent line segments. */
  13461. enum JointStyle
  13462. {
  13463. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13464. Note that for angles that curve back on themselves, drawing a
  13465. mitre could require extending the point too far away from the
  13466. path, so a mitre limit is imposed and any corners that exceed it
  13467. are drawn as bevelled instead. */
  13468. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13469. beveled /**< Indicates that corners should be drawn with a line flattening their
  13470. outside edge. */
  13471. };
  13472. /** The type shape to use for the ends of lines. */
  13473. enum EndCapStyle
  13474. {
  13475. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13476. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13477. the thickness of the stroke. */
  13478. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13479. };
  13480. /** Creates a stroke type.
  13481. @param strokeThickness the width of the line to use
  13482. @param jointStyle the type of joints to use for corners
  13483. @param endStyle the type of end-caps to use for the ends of open paths.
  13484. */
  13485. PathStrokeType (const float strokeThickness,
  13486. const JointStyle jointStyle = mitered,
  13487. const EndCapStyle endStyle = butt) throw();
  13488. /** Createes a copy of another stroke type. */
  13489. PathStrokeType (const PathStrokeType& other) throw();
  13490. /** Copies another stroke onto this one. */
  13491. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13492. /** Destructor. */
  13493. ~PathStrokeType() throw();
  13494. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13495. @param destPath the resultant stroked outline shape will be copied into this path.
  13496. Note that it's ok for the source and destination Paths to be
  13497. the same object, so you can easily turn a path into a stroked version
  13498. of itself.
  13499. @param sourcePath the path to use as the source
  13500. @param transform an optional transform to apply to the points from the source path
  13501. as they are being used
  13502. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13503. a higher resolution, which improved the quality if you'll later want
  13504. to enlarge the stroked path
  13505. @see createDashedStroke
  13506. */
  13507. void createStrokedPath (Path& destPath,
  13508. const Path& sourcePath,
  13509. const AffineTransform& transform = AffineTransform::identity,
  13510. const float extraAccuracy = 1.0f) const throw();
  13511. /** Applies this stroke type to a path, creating a dashed line.
  13512. This is similar to createStrokedPath, but uses the array passed in to
  13513. break the stroke up into a series of dashes.
  13514. @param destPath the resultant stroked outline shape will be copied into this path.
  13515. Note that it's ok for the source and destination Paths to be
  13516. the same object, so you can easily turn a path into a stroked version
  13517. of itself.
  13518. @param sourcePath the path to use as the source
  13519. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13520. a line of length 2, then skip a length of 3, then add a line of length 4,
  13521. skip 5, and keep repeating this pattern.
  13522. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13523. an even number, otherwise the pattern will get out of step as it
  13524. repeats.
  13525. @param transform an optional transform to apply to the points from the source path
  13526. as they are being used
  13527. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13528. a higher resolution, which improved the quality if you'll later want
  13529. to enlarge the stroked path
  13530. */
  13531. void createDashedStroke (Path& destPath,
  13532. const Path& sourcePath,
  13533. const float* dashLengths,
  13534. int numDashLengths,
  13535. const AffineTransform& transform = AffineTransform::identity,
  13536. const float extraAccuracy = 1.0f) const throw();
  13537. /** Returns the stroke thickness. */
  13538. float getStrokeThickness() const throw() { return thickness; }
  13539. /** Returns the joint style. */
  13540. JointStyle getJointStyle() const throw() { return jointStyle; }
  13541. /** Returns the end-cap style. */
  13542. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13543. juce_UseDebuggingNewOperator
  13544. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13545. bool operator== (const PathStrokeType& other) const throw();
  13546. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13547. bool operator!= (const PathStrokeType& other) const throw();
  13548. private:
  13549. float thickness;
  13550. JointStyle jointStyle;
  13551. EndCapStyle endStyle;
  13552. };
  13553. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13554. /********* End of inlined file: juce_PathStrokeType.h *********/
  13555. /********* Start of inlined file: juce_Line.h *********/
  13556. #ifndef __JUCE_LINE_JUCEHEADER__
  13557. #define __JUCE_LINE_JUCEHEADER__
  13558. /**
  13559. Represents a line, using 32-bit float co-ordinates.
  13560. This class contains a bunch of useful methods for various geometric
  13561. tasks.
  13562. @see Point, Rectangle, Path, Graphics::drawLine
  13563. */
  13564. class JUCE_API Line
  13565. {
  13566. public:
  13567. /** Creates a line, using (0, 0) as its start and end points. */
  13568. Line() throw();
  13569. /** Creates a copy of another line. */
  13570. Line (const Line& other) throw();
  13571. /** Creates a line based on the co-ordinates of its start and end points. */
  13572. Line (const float startX,
  13573. const float startY,
  13574. const float endX,
  13575. const float endY) throw();
  13576. /** Creates a line from its start and end points. */
  13577. Line (const Point& start,
  13578. const Point& end) throw();
  13579. /** Copies a line from another one. */
  13580. const Line& operator= (const Line& other) throw();
  13581. /** Destructor. */
  13582. ~Line() throw();
  13583. /** Returns the x co-ordinate of the line's start point. */
  13584. inline float getStartX() const throw() { return startX; }
  13585. /** Returns the y co-ordinate of the line's start point. */
  13586. inline float getStartY() const throw() { return startY; }
  13587. /** Returns the x co-ordinate of the line's end point. */
  13588. inline float getEndX() const throw() { return endX; }
  13589. /** Returns the y co-ordinate of the line's end point. */
  13590. inline float getEndY() const throw() { return endY; }
  13591. /** Returns the line's start point. */
  13592. const Point getStart() const throw();
  13593. /** Returns the line's end point. */
  13594. const Point getEnd() const throw();
  13595. /** Changes this line's start point */
  13596. void setStart (const float newStartX,
  13597. const float newStartY) throw();
  13598. /** Changes this line's end point */
  13599. void setEnd (const float newEndX,
  13600. const float newEndY) throw();
  13601. /** Changes this line's start point */
  13602. void setStart (const Point& newStart) throw();
  13603. /** Changes this line's end point */
  13604. void setEnd (const Point& newEnd) throw();
  13605. /** Applies an affine transform to the line's start and end points. */
  13606. void applyTransform (const AffineTransform& transform) throw();
  13607. /** Returns the length of the line. */
  13608. float getLength() const throw();
  13609. /** Returns true if the line's start and end x co-ordinates are the same. */
  13610. bool isVertical() const throw();
  13611. /** Returns true if the line's start and end y co-ordinates are the same. */
  13612. bool isHorizontal() const throw();
  13613. /** Returns the line's angle.
  13614. This value is the number of radians clockwise from the 3 o'clock direction,
  13615. where the line's start point is considered to be at the centre.
  13616. */
  13617. float getAngle() const throw();
  13618. /** Compares two lines. */
  13619. bool operator== (const Line& other) const throw();
  13620. /** Compares two lines. */
  13621. bool operator!= (const Line& other) const throw();
  13622. /** Finds the intersection between two lines.
  13623. @param line the other line
  13624. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13625. where they would meet if they were infinitely long)
  13626. the intersection (if the lines intersect). If the lines
  13627. are parallel, this will just be set to the position
  13628. of one of the line's endpoints.
  13629. @param intersectionY the y co-ordinate of the point where the lines meet
  13630. @returns true if the line segments intersect; false if they dont. Even if they
  13631. don't intersect, the intersection co-ordinates returned will still
  13632. be valid
  13633. */
  13634. bool intersects (const Line& line,
  13635. float& intersectionX,
  13636. float& intersectionY) const throw();
  13637. /** Returns the location of the point which is a given distance along this line.
  13638. @param distanceFromStart the distance to move along the line from its
  13639. start point. This value can be negative or longer
  13640. than the line itself
  13641. @see getPointAlongLineProportionally
  13642. */
  13643. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13644. /** Returns a point which is a certain distance along and to the side of this line.
  13645. This effectively moves a given distance along the line, then another distance
  13646. perpendicularly to this, and returns the resulting position.
  13647. @param distanceFromStart the distance to move along the line from its
  13648. start point. This value can be negative or longer
  13649. than the line itself
  13650. @param perpendicularDistance how far to move sideways from the line. If you're
  13651. looking along the line from its start towards its
  13652. end, then a positive value here will move to the
  13653. right, negative value move to the left.
  13654. */
  13655. const Point getPointAlongLine (const float distanceFromStart,
  13656. const float perpendicularDistance) const throw();
  13657. /** Returns the location of the point which is a given distance along this line
  13658. proportional to the line's length.
  13659. @param proportionOfLength the distance to move along the line from its
  13660. start point, in multiples of the line's length.
  13661. So a value of 0.0 will return the line's start point
  13662. and a value of 1.0 will return its end point. (This value
  13663. can be negative or greater than 1.0).
  13664. @see getPointAlongLine
  13665. */
  13666. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13667. /** Returns the smallest distance between this line segment and a given point.
  13668. So if the point is close to the line, this will return the perpendicular
  13669. distance from the line; if the point is a long way beyond one of the line's
  13670. end-point's, it'll return the straight-line distance to the nearest end-point.
  13671. @param x x position of the point to test
  13672. @param y y position of the point to test
  13673. @returns the point's distance from the line
  13674. @see getPositionAlongLineOfNearestPoint
  13675. */
  13676. float getDistanceFromLine (const float x,
  13677. const float y) const throw();
  13678. /** Finds the point on this line which is nearest to a given point, and
  13679. returns its position as a proportional position along the line.
  13680. @param x x position of the point to test
  13681. @param y y position of the point to test
  13682. @returns a value 0 to 1.0 which is the distance along this line from the
  13683. line's start to the point which is nearest to the point passed-in. To
  13684. turn this number into a position, use getPointAlongLineProportionally().
  13685. @see getDistanceFromLine, getPointAlongLineProportionally
  13686. */
  13687. float findNearestPointTo (const float x,
  13688. const float y) const throw();
  13689. /** Returns true if the given point lies above this line.
  13690. The return value is true if the point's y coordinate is less than the y
  13691. coordinate of this line at the given x (assuming the line extends infinitely
  13692. in both directions).
  13693. */
  13694. bool isPointAbove (const float x, const float y) const throw();
  13695. /** Returns a shortened copy of this line.
  13696. This will chop off part of the start of this line by a certain amount, (leaving the
  13697. end-point the same), and return the new line.
  13698. */
  13699. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13700. /** Returns a shortened copy of this line.
  13701. This will chop off part of the end of this line by a certain amount, (leaving the
  13702. start-point the same), and return the new line.
  13703. */
  13704. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13705. /** Cuts off parts of this line to keep the parts that are either inside or
  13706. outside a path.
  13707. Note that this isn't smart enough to cope with situations where the
  13708. line would need to be cut into multiple pieces to correctly clip against
  13709. a re-entrant shape.
  13710. @param path the path to clip against
  13711. @param keepSectionOutsidePath if true, it's the section outside the path
  13712. that will be kept; if false its the section inside
  13713. the path
  13714. @returns true if the line was changed.
  13715. */
  13716. bool clipToPath (const Path& path,
  13717. const bool keepSectionOutsidePath) throw();
  13718. juce_UseDebuggingNewOperator
  13719. private:
  13720. float startX, startY, endX, endY;
  13721. };
  13722. #endif // __JUCE_LINE_JUCEHEADER__
  13723. /********* End of inlined file: juce_Line.h *********/
  13724. /********* Start of inlined file: juce_Colours.h *********/
  13725. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13726. #define __JUCE_COLOURS_JUCEHEADER__
  13727. /********* Start of inlined file: juce_Colour.h *********/
  13728. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13729. #define __JUCE_COLOUR_JUCEHEADER__
  13730. /********* Start of inlined file: juce_PixelFormats.h *********/
  13731. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13732. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13733. #if JUCE_MSVC
  13734. #pragma pack (push, 1)
  13735. #define PACKED
  13736. #elif JUCE_GCC
  13737. #define PACKED __attribute__((packed))
  13738. #else
  13739. #define PACKED
  13740. #endif
  13741. /**
  13742. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13743. operations with it.
  13744. This is used internally by the imaging classes.
  13745. @see PixelRGB
  13746. */
  13747. class JUCE_API PixelARGB
  13748. {
  13749. public:
  13750. /** Creates a pixel without defining its colour. */
  13751. PixelARGB() throw() {}
  13752. ~PixelARGB() throw() {}
  13753. /** Creates a pixel from a 32-bit argb value.
  13754. */
  13755. PixelARGB (const uint32 argb_) throw()
  13756. : argb (argb_)
  13757. {
  13758. }
  13759. forcedinline uint32 getARGB() const throw() { return argb; }
  13760. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13761. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13762. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13763. forcedinline uint8 getRed() const throw() { return components.r; }
  13764. forcedinline uint8 getGreen() const throw() { return components.g; }
  13765. forcedinline uint8 getBlue() const throw() { return components.b; }
  13766. /** Blends another pixel onto this one.
  13767. This takes into account the opacity of the pixel being overlaid, and blends
  13768. it accordingly.
  13769. */
  13770. template <class Pixel>
  13771. forcedinline void blend (const Pixel& src) throw()
  13772. {
  13773. uint32 sargb = src.getARGB();
  13774. const uint32 alpha = 0x100 - (sargb >> 24);
  13775. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13776. sargb += 0xff00ff00 & (getAG() * alpha);
  13777. argb = sargb;
  13778. }
  13779. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13780. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13781. being used, so this can blend semi-transparently from a PixelRGB argument.
  13782. */
  13783. template <class Pixel>
  13784. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13785. {
  13786. ++extraAlpha;
  13787. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13788. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13789. const uint32 alpha = 0x100 - (sargb >> 24);
  13790. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13791. sargb += 0xff00ff00 & (getAG() * alpha);
  13792. argb = sargb;
  13793. }
  13794. /** Blends another pixel with this one, creating a colour that is somewhere
  13795. between the two, as specified by the amount.
  13796. */
  13797. template <class Pixel>
  13798. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13799. {
  13800. uint32 drb = getRB();
  13801. drb += (((src.getRB() - drb) * amount) >> 8);
  13802. drb &= 0x00ff00ff;
  13803. uint32 dag = getAG();
  13804. dag += (((src.getAG() - dag) * amount) >> 8);
  13805. dag &= 0x00ff00ff;
  13806. dag <<= 8;
  13807. dag |= drb;
  13808. argb = dag;
  13809. }
  13810. /** Copies another pixel colour over this one.
  13811. This doesn't blend it - this colour is simply replaced by the other one.
  13812. */
  13813. template <class Pixel>
  13814. forcedinline void set (const Pixel& src) throw()
  13815. {
  13816. argb = src.getARGB();
  13817. }
  13818. /** Replaces the colour's alpha value with another one. */
  13819. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13820. {
  13821. components.a = newAlpha;
  13822. }
  13823. /** Multiplies the colour's alpha value with another one. */
  13824. forcedinline void multiplyAlpha (int multiplier) throw()
  13825. {
  13826. ++multiplier;
  13827. argb = ((multiplier * getAG()) & 0xff00ff00)
  13828. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13829. }
  13830. forcedinline void multiplyAlpha (const float multiplier) throw()
  13831. {
  13832. multiplyAlpha ((int) (multiplier * 256.0f));
  13833. }
  13834. /** Sets the pixel's colour from individual components. */
  13835. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13836. {
  13837. components.b = b;
  13838. components.g = g;
  13839. components.r = r;
  13840. components.a = a;
  13841. }
  13842. /** Premultiplies the pixel's RGB values by its alpha. */
  13843. forcedinline void premultiply() throw()
  13844. {
  13845. const uint32 alpha = components.a;
  13846. if (alpha < 0xff)
  13847. {
  13848. if (alpha == 0)
  13849. {
  13850. components.b = 0;
  13851. components.g = 0;
  13852. components.r = 0;
  13853. }
  13854. else
  13855. {
  13856. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13857. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13858. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13859. }
  13860. }
  13861. }
  13862. /** Unpremultiplies the pixel's RGB values. */
  13863. forcedinline void unpremultiply() throw()
  13864. {
  13865. const uint32 alpha = components.a;
  13866. if (alpha < 0xff)
  13867. {
  13868. if (alpha == 0)
  13869. {
  13870. components.b = 0;
  13871. components.g = 0;
  13872. components.r = 0;
  13873. }
  13874. else
  13875. {
  13876. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13877. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13878. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13879. }
  13880. }
  13881. }
  13882. forcedinline void desaturate() throw()
  13883. {
  13884. if (components.a < 0xff && components.a > 0)
  13885. {
  13886. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13887. components.r = components.g = components.b
  13888. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13889. }
  13890. else
  13891. {
  13892. components.r = components.g = components.b
  13893. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13894. }
  13895. }
  13896. private:
  13897. union
  13898. {
  13899. uint32 argb;
  13900. struct
  13901. {
  13902. #if JUCE_BIG_ENDIAN
  13903. uint8 a : 8, r : 8, g : 8, b : 8;
  13904. #else
  13905. uint8 b, g, r, a;
  13906. #endif
  13907. } PACKED components;
  13908. };
  13909. } PACKED;
  13910. /**
  13911. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13912. This is used internally by the imaging classes.
  13913. @see PixelARGB
  13914. */
  13915. class JUCE_API PixelRGB
  13916. {
  13917. public:
  13918. /** Creates a pixel without defining its colour. */
  13919. PixelRGB() throw() {}
  13920. ~PixelRGB() throw() {}
  13921. /** Creates a pixel from a 32-bit argb value.
  13922. (The argb format is that used by PixelARGB)
  13923. */
  13924. PixelRGB (const uint32 argb) throw()
  13925. {
  13926. r = (uint8) (argb >> 16);
  13927. g = (uint8) (argb >> 8);
  13928. b = (uint8) (argb);
  13929. }
  13930. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13931. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13932. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13933. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13934. forcedinline uint8 getRed() const throw() { return r; }
  13935. forcedinline uint8 getGreen() const throw() { return g; }
  13936. forcedinline uint8 getBlue() const throw() { return b; }
  13937. /** Blends another pixel onto this one.
  13938. This takes into account the opacity of the pixel being overlaid, and blends
  13939. it accordingly.
  13940. */
  13941. forcedinline void blend (const PixelARGB& src) throw()
  13942. {
  13943. uint32 sargb = src.getARGB();
  13944. const uint32 alpha = 0x100 - (sargb >> 24);
  13945. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13946. sargb += 0x0000ff00 & (g * alpha);
  13947. r = (uint8) (sargb >> 16);
  13948. g = (uint8) (sargb >> 8);
  13949. b = (uint8) sargb;
  13950. }
  13951. forcedinline void blend (const PixelRGB& src) throw()
  13952. {
  13953. set (src);
  13954. }
  13955. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13956. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13957. being used, so this can blend semi-transparently from a PixelRGB argument.
  13958. */
  13959. template <class Pixel>
  13960. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13961. {
  13962. ++extraAlpha;
  13963. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13964. const uint32 sag = extraAlpha * src.getAG();
  13965. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13966. const uint32 alpha = 0x100 - (sargb >> 24);
  13967. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13968. sargb += 0x0000ff00 & (g * alpha);
  13969. b = (uint8) sargb;
  13970. g = (uint8) (sargb >> 8);
  13971. r = (uint8) (sargb >> 16);
  13972. }
  13973. /** Blends another pixel with this one, creating a colour that is somewhere
  13974. between the two, as specified by the amount.
  13975. */
  13976. template <class Pixel>
  13977. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13978. {
  13979. uint32 drb = getRB();
  13980. drb += (((src.getRB() - drb) * amount) >> 8);
  13981. uint32 dag = getAG();
  13982. dag += (((src.getAG() - dag) * amount) >> 8);
  13983. b = (uint8) drb;
  13984. g = (uint8) dag;
  13985. r = (uint8) (drb >> 16);
  13986. }
  13987. /** Copies another pixel colour over this one.
  13988. This doesn't blend it - this colour is simply replaced by the other one.
  13989. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13990. is thrown away.
  13991. */
  13992. template <class Pixel>
  13993. forcedinline void set (const Pixel& src) throw()
  13994. {
  13995. b = src.getBlue();
  13996. g = src.getGreen();
  13997. r = src.getRed();
  13998. }
  13999. /** This method is included for compatibility with the PixelARGB class. */
  14000. forcedinline void setAlpha (const uint8) throw() {}
  14001. /** Multiplies the colour's alpha value with another one. */
  14002. forcedinline void multiplyAlpha (int) throw() {}
  14003. /** Sets the pixel's colour from individual components. */
  14004. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  14005. {
  14006. r = r_;
  14007. g = g_;
  14008. b = b_;
  14009. }
  14010. /** Premultiplies the pixel's RGB values by its alpha. */
  14011. forcedinline void premultiply() throw() {}
  14012. /** Unpremultiplies the pixel's RGB values. */
  14013. forcedinline void unpremultiply() throw() {}
  14014. forcedinline void desaturate() throw()
  14015. {
  14016. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  14017. }
  14018. private:
  14019. #if JUCE_MAC
  14020. uint8 r, g, b;
  14021. #else
  14022. uint8 b, g, r;
  14023. #endif
  14024. } PACKED;
  14025. #if JUCE_MSVC
  14026. #pragma pack (pop)
  14027. #endif
  14028. #undef PACKED
  14029. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  14030. /********* End of inlined file: juce_PixelFormats.h *********/
  14031. /**
  14032. Represents a colour, also including a transparency value.
  14033. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  14034. */
  14035. class JUCE_API Colour
  14036. {
  14037. public:
  14038. /** Creates a transparent black colour. */
  14039. Colour() throw();
  14040. /** Creates a copy of another Colour object. */
  14041. Colour (const Colour& other) throw();
  14042. /** Creates a colour from a 32-bit ARGB value.
  14043. The format of this number is:
  14044. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14045. All components in the range 0x00 to 0xff.
  14046. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14047. @see getPixelARGB
  14048. */
  14049. explicit Colour (const uint32 argb) throw();
  14050. /** Creates an opaque colour using 8-bit red, green and blue values */
  14051. Colour (const uint8 red,
  14052. const uint8 green,
  14053. const uint8 blue) throw();
  14054. /** Creates an opaque colour using 8-bit red, green and blue values */
  14055. static const Colour fromRGB (const uint8 red,
  14056. const uint8 green,
  14057. const uint8 blue) throw();
  14058. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14059. Colour (const uint8 red,
  14060. const uint8 green,
  14061. const uint8 blue,
  14062. const uint8 alpha) throw();
  14063. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14064. static const Colour fromRGBA (const uint8 red,
  14065. const uint8 green,
  14066. const uint8 blue,
  14067. const uint8 alpha) throw();
  14068. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  14069. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  14070. Values outside the valid range will be clipped.
  14071. */
  14072. Colour (const uint8 red,
  14073. const uint8 green,
  14074. const uint8 blue,
  14075. const float alpha) throw();
  14076. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  14077. static const Colour fromRGBAFloat (const uint8 red,
  14078. const uint8 green,
  14079. const uint8 blue,
  14080. const float alpha) throw();
  14081. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14082. The floating point values must be between 0.0 and 1.0.
  14083. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14084. Values outside the valid range will be clipped.
  14085. */
  14086. Colour (const float hue,
  14087. const float saturation,
  14088. const float brightness,
  14089. const uint8 alpha) throw();
  14090. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  14091. All values must be between 0.0 and 1.0.
  14092. Numbers outside the valid range will be clipped.
  14093. */
  14094. Colour (const float hue,
  14095. const float saturation,
  14096. const float brightness,
  14097. const float alpha) throw();
  14098. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14099. The floating point values must be between 0.0 and 1.0.
  14100. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14101. Values outside the valid range will be clipped.
  14102. */
  14103. static const Colour fromHSV (const float hue,
  14104. const float saturation,
  14105. const float brightness,
  14106. const float alpha) throw();
  14107. /** Destructor. */
  14108. ~Colour() throw();
  14109. /** Copies another Colour object. */
  14110. const Colour& operator= (const Colour& other) throw();
  14111. /** Compares two colours. */
  14112. bool operator== (const Colour& other) const throw();
  14113. /** Compares two colours. */
  14114. bool operator!= (const Colour& other) const throw();
  14115. /** Returns the red component of this colour.
  14116. @returns a value between 0x00 and 0xff.
  14117. */
  14118. uint8 getRed() const throw() { return argb.getRed(); }
  14119. /** Returns the green component of this colour.
  14120. @returns a value between 0x00 and 0xff.
  14121. */
  14122. uint8 getGreen() const throw() { return argb.getGreen(); }
  14123. /** Returns the blue component of this colour.
  14124. @returns a value between 0x00 and 0xff.
  14125. */
  14126. uint8 getBlue() const throw() { return argb.getBlue(); }
  14127. /** Returns the red component of this colour as a floating point value.
  14128. @returns a value between 0.0 and 1.0
  14129. */
  14130. float getFloatRed() const throw();
  14131. /** Returns the green component of this colour as a floating point value.
  14132. @returns a value between 0.0 and 1.0
  14133. */
  14134. float getFloatGreen() const throw();
  14135. /** Returns the blue component of this colour as a floating point value.
  14136. @returns a value between 0.0 and 1.0
  14137. */
  14138. float getFloatBlue() const throw();
  14139. /** Returns a premultiplied ARGB pixel object that represents this colour.
  14140. */
  14141. const PixelARGB getPixelARGB() const throw();
  14142. /** Returns a 32-bit integer that represents this colour.
  14143. The format of this number is:
  14144. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14145. */
  14146. uint32 getARGB() const throw();
  14147. /** Returns the colour's alpha (opacity).
  14148. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  14149. */
  14150. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  14151. /** Returns the colour's alpha (opacity) as a floating point value.
  14152. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  14153. */
  14154. float getFloatAlpha() const throw();
  14155. /** Returns true if this colour is completely opaque.
  14156. Equivalent to (getAlpha() == 0xff).
  14157. */
  14158. bool isOpaque() const throw();
  14159. /** Returns true if this colour is completely transparent.
  14160. Equivalent to (getAlpha() == 0x00).
  14161. */
  14162. bool isTransparent() const throw();
  14163. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14164. const Colour withAlpha (const uint8 newAlpha) 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 float newAlpha) const throw();
  14167. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14168. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14169. */
  14170. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14171. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14172. If the foreground colour is semi-transparent, it is blended onto this colour
  14173. accordingly.
  14174. */
  14175. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14176. /** Returns the colour's hue component.
  14177. The value returned is in the range 0.0 to 1.0
  14178. */
  14179. float getHue() const throw();
  14180. /** Returns the colour's saturation component.
  14181. The value returned is in the range 0.0 to 1.0
  14182. */
  14183. float getSaturation() const throw();
  14184. /** Returns the colour's brightness component.
  14185. The value returned is in the range 0.0 to 1.0
  14186. */
  14187. float getBrightness() const throw();
  14188. /** Returns the colour's hue, saturation and brightness components all at once.
  14189. The values returned are in the range 0.0 to 1.0
  14190. */
  14191. void getHSB (float& hue,
  14192. float& saturation,
  14193. float& brightness) const throw();
  14194. /** Returns a copy of this colour with a different hue. */
  14195. const Colour withHue (const float newHue) const throw();
  14196. /** Returns a copy of this colour with a different saturation. */
  14197. const Colour withSaturation (const float newSaturation) const throw();
  14198. /** Returns a copy of this colour with a different brightness.
  14199. @see brighter, darker, withMultipliedBrightness
  14200. */
  14201. const Colour withBrightness (const float newBrightness) const throw();
  14202. /** Returns a copy of this colour with it hue rotated.
  14203. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14204. @see brighter, darker, withMultipliedBrightness
  14205. */
  14206. const Colour withRotatedHue (const float amountToRotate) const throw();
  14207. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14208. The new colour's saturation is (this->getSaturation() * multiplier)
  14209. (the result is clipped to legal limits).
  14210. */
  14211. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14212. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14213. The new colour's saturation is (this->getBrightness() * multiplier)
  14214. (the result is clipped to legal limits).
  14215. */
  14216. const Colour withMultipliedBrightness (const float amount) const throw();
  14217. /** Returns a brighter version of this colour.
  14218. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14219. unchanged, and higher values make it brighter
  14220. @see withMultipliedBrightness
  14221. */
  14222. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14223. /** Returns a darker version of this colour.
  14224. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14225. unchanged, and higher values make it darker
  14226. @see withMultipliedBrightness
  14227. */
  14228. const Colour darker (float amountDarker = 0.4f) const throw();
  14229. /** Returns a colour that will be clearly visible against this colour.
  14230. The amount parameter indicates how contrasting the new colour should
  14231. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14232. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14233. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14234. */
  14235. const Colour contrasting (const float amount = 1.0f) const throw();
  14236. /** Returns a colour that contrasts against two colours.
  14237. Looks for a colour that contrasts with both of the colours passed-in.
  14238. Handy for things like choosing a highlight colour in text editors, etc.
  14239. */
  14240. static const Colour contrasting (const Colour& colour1,
  14241. const Colour& colour2) throw();
  14242. /** Returns an opaque shade of grey.
  14243. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14244. */
  14245. static const Colour greyLevel (const float brightness) throw();
  14246. /** Returns a stringified version of this colour.
  14247. The string can be turned back into a colour using the fromString() method.
  14248. */
  14249. const String toString() const throw();
  14250. /** Reads the colour from a string that was created with toString().
  14251. */
  14252. static const Colour fromString (const String& encodedColourString);
  14253. juce_UseDebuggingNewOperator
  14254. private:
  14255. PixelARGB argb;
  14256. };
  14257. #endif // __JUCE_COLOUR_JUCEHEADER__
  14258. /********* End of inlined file: juce_Colour.h *********/
  14259. /**
  14260. Contains a set of predefined named colours (mostly standard HTML colours)
  14261. @see Colour, Colours::greyLevel
  14262. */
  14263. class Colours
  14264. {
  14265. public:
  14266. static JUCE_API const Colour
  14267. transparentBlack, /**< ARGB = 0x00000000 */
  14268. transparentWhite, /**< ARGB = 0x00ffffff */
  14269. black, /**< ARGB = 0xff000000 */
  14270. white, /**< ARGB = 0xffffffff */
  14271. blue, /**< ARGB = 0xff0000ff */
  14272. grey, /**< ARGB = 0xff808080 */
  14273. green, /**< ARGB = 0xff008000 */
  14274. red, /**< ARGB = 0xffff0000 */
  14275. yellow, /**< ARGB = 0xffffff00 */
  14276. aliceblue, antiquewhite, aqua, aquamarine,
  14277. azure, beige, bisque, blanchedalmond,
  14278. blueviolet, brown, burlywood, cadetblue,
  14279. chartreuse, chocolate, coral, cornflowerblue,
  14280. cornsilk, crimson, cyan, darkblue,
  14281. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14282. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14283. darkorchid, darkred, darksalmon, darkseagreen,
  14284. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14285. deeppink, deepskyblue, dimgrey, dodgerblue,
  14286. firebrick, floralwhite, forestgreen, fuchsia,
  14287. gainsboro, gold, goldenrod, greenyellow,
  14288. honeydew, hotpink, indianred, indigo,
  14289. ivory, khaki, lavender, lavenderblush,
  14290. lemonchiffon, lightblue, lightcoral, lightcyan,
  14291. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14292. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14293. lightsteelblue, lightyellow, lime, limegreen,
  14294. linen, magenta, maroon, mediumaquamarine,
  14295. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14296. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14297. midnightblue, mintcream, mistyrose, navajowhite,
  14298. navy, oldlace, olive, olivedrab,
  14299. orange, orangered, orchid, palegoldenrod,
  14300. palegreen, paleturquoise, palevioletred, papayawhip,
  14301. peachpuff, peru, pink, plum,
  14302. powderblue, purple, rosybrown, royalblue,
  14303. saddlebrown, salmon, sandybrown, seagreen,
  14304. seashell, sienna, silver, skyblue,
  14305. slateblue, slategrey, snow, springgreen,
  14306. steelblue, tan, teal, thistle,
  14307. tomato, turquoise, violet, wheat,
  14308. whitesmoke, yellowgreen;
  14309. /** Attempts to look up a string in the list of known colour names, and return
  14310. the appropriate colour.
  14311. A non-case-sensitive search is made of the list of predefined colours, and
  14312. if a match is found, that colour is returned. If no match is found, the
  14313. colour passed in as the defaultColour parameter is returned.
  14314. */
  14315. static JUCE_API const Colour findColourForName (const String& colourName,
  14316. const Colour& defaultColour);
  14317. private:
  14318. // this isn't a class you should ever instantiate - it's just here for the
  14319. // static values in it.
  14320. Colours();
  14321. };
  14322. #endif // __JUCE_COLOURS_JUCEHEADER__
  14323. /********* End of inlined file: juce_Colours.h *********/
  14324. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14325. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14326. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14327. /********* Start of inlined file: juce_Brush.h *********/
  14328. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14329. #define __JUCE_BRUSH_JUCEHEADER__
  14330. class Path;
  14331. class AffineTransform;
  14332. class LowLevelGraphicsContext;
  14333. class Image;
  14334. class Graphics;
  14335. /**
  14336. A brush is used to fill areas with colours, patterns, or images.
  14337. The Graphics class has an idea of a current brush which it uses to render
  14338. shapes, rectangles, lines, text, etc.
  14339. This is the base class - there are subclasses for useful types of fill pattern,
  14340. and applications can define their own brushes too.
  14341. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14342. */
  14343. class JUCE_API Brush
  14344. {
  14345. protected:
  14346. /** Creates a Brush.
  14347. (Nothing much happens in the base class).
  14348. */
  14349. Brush() throw();
  14350. public:
  14351. /** Destructor. */
  14352. virtual ~Brush() throw();
  14353. /** Creates a copy of whatever class of Brush this is. */
  14354. virtual Brush* createCopy() const throw() = 0;
  14355. /** Does whatever is relevent to transform the geometry of this brush. */
  14356. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14357. /** Does whatever is relevent to change the opacity of this brush. */
  14358. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14359. /** Must return true if this brush won't draw any pixels. */
  14360. virtual bool isInvisible() const throw() = 0;
  14361. virtual void paintPath (LowLevelGraphicsContext& context,
  14362. const Path& path, const AffineTransform& transform) throw() = 0;
  14363. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14364. int x, int y, int w, int h) throw() = 0;
  14365. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14366. const Image& alphaChannelImage, int imageX, int imageY,
  14367. int x, int y, int w, int h) throw() = 0;
  14368. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14369. int x, float y1, float y2) throw();
  14370. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14371. int y, float x1, float x2) throw();
  14372. virtual void paintLine (LowLevelGraphicsContext& context,
  14373. float x1, float y1, float x2, float y2) throw();
  14374. private:
  14375. Brush (const Brush&);
  14376. const Brush& operator= (const Brush&);
  14377. };
  14378. #endif // __JUCE_BRUSH_JUCEHEADER__
  14379. /********* End of inlined file: juce_Brush.h *********/
  14380. /**
  14381. A Brush that fills its area with a solid (or semi-transparent) colour.
  14382. An application won't normally need to use this class directly, as drawing
  14383. with solid colours is taken care of automatically by the Graphics class
  14384. (it actually uses one of these brushes internally when you set the colour
  14385. with the Graphics::setColour() method).
  14386. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14387. */
  14388. class JUCE_API SolidColourBrush : public Brush
  14389. {
  14390. public:
  14391. /** Creates a SolidColourBrush to draw with the given colour.
  14392. The colour can be changed later with the setColour() method.
  14393. */
  14394. SolidColourBrush (const Colour& colour) throw();
  14395. /** Creates a SolidColourBrush set to black.
  14396. The colour can be changed later with the setColour() method.
  14397. */
  14398. SolidColourBrush() throw();
  14399. /** Destructor. */
  14400. ~SolidColourBrush() throw();
  14401. /** Returns the colour currently being used. */
  14402. const Colour& getColour() const throw() { return colour; }
  14403. /** Sets the colour to use for drawing. */
  14404. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14405. Brush* createCopy() const throw();
  14406. void applyTransform (const AffineTransform& transform) throw();
  14407. bool isInvisible() const throw();
  14408. void multiplyOpacity (const float multiple) throw();
  14409. void paintPath (LowLevelGraphicsContext& context,
  14410. const Path& path, const AffineTransform& transform) throw();
  14411. void paintRectangle (LowLevelGraphicsContext& context,
  14412. int x, int y, int w, int h) throw();
  14413. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14414. const Image& alphaChannelImage, int imageX, int imageY,
  14415. int x, int y, int w, int h) throw();
  14416. void paintVerticalLine (LowLevelGraphicsContext& context,
  14417. int x, float y1, float y2) throw();
  14418. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14419. int y, float x1, float x2) throw();
  14420. void paintLine (LowLevelGraphicsContext& context,
  14421. float x1, float y1, float x2, float y2) throw();
  14422. juce_UseDebuggingNewOperator
  14423. private:
  14424. Colour colour;
  14425. SolidColourBrush (const SolidColourBrush&);
  14426. const SolidColourBrush& operator= (const SolidColourBrush&);
  14427. };
  14428. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14429. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14430. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14431. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14432. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14433. /**
  14434. Defines the method used to postion some kind of rectangular object within
  14435. a rectangular viewport.
  14436. Although similar to Justification, this is more specific, and has some extra
  14437. options.
  14438. */
  14439. class JUCE_API RectanglePlacement
  14440. {
  14441. public:
  14442. /** Creates a RectanglePlacement object using a combination of flags. */
  14443. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14444. /** Creates a copy of another Justification object. */
  14445. RectanglePlacement (const RectanglePlacement& other) throw();
  14446. /** Copies another Justification object. */
  14447. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14448. /** Flag values that can be combined and used in the constructor. */
  14449. enum
  14450. {
  14451. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14452. xLeft = 1,
  14453. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14454. xRight = 2,
  14455. /** Indicates that the source should be placed in the centre between the left and right
  14456. sides of the available space. */
  14457. xMid = 4,
  14458. /** Indicates that the source's top edge should be aligned with the top edge of the
  14459. destination rectangle. */
  14460. yTop = 8,
  14461. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14462. destination rectangle. */
  14463. yBottom = 16,
  14464. /** Indicates that the source should be placed in the centre between the top and bottom
  14465. sides of the available space. */
  14466. yMid = 32,
  14467. /** If this flag is set, then the source rectangle will be resized to completely fill
  14468. the destination rectangle, and all other flags are ignored.
  14469. */
  14470. stretchToFit = 64,
  14471. /** If this flag is set, then the source rectangle will be resized so that it is the
  14472. minimum size to completely fill the destination rectangle. This means that some
  14473. of the source rectangle may fall outside the destination.
  14474. If this flag is not set, the source will be given the maximum size at which none
  14475. of it falls outside the destination rectangle.
  14476. */
  14477. fillDestination = 128,
  14478. /** Indicates that the source rectangle can be reduced in size if required, but should
  14479. never be made larger than its original size.
  14480. */
  14481. onlyReduceInSize = 256,
  14482. /** Indicates that the source rectangle can be enlarged if required, but should
  14483. never be made smaller than its original size.
  14484. */
  14485. onlyIncreaseInSize = 512,
  14486. /** Indicates that the source rectangle's size should be left unchanged.
  14487. */
  14488. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14489. /** A shorthand value that is equivalent to (xMid | yMid). */
  14490. centred = 4 + 32
  14491. };
  14492. /** Returns the raw flags that are set for this object. */
  14493. inline int getFlags() const throw() { return flags; }
  14494. /** Tests a set of flags for this object.
  14495. @returns true if any of the flags passed in are set on this object.
  14496. */
  14497. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14498. /** Adjusts the position and size of a rectangle to fit it into a space.
  14499. The source rectangle co-ordinates will be adjusted so that they fit into
  14500. the destination rectangle based on this object's flags.
  14501. */
  14502. void applyTo (double& sourceX,
  14503. double& sourceY,
  14504. double& sourceW,
  14505. double& sourceH,
  14506. const double destinationX,
  14507. const double destinationY,
  14508. const double destinationW,
  14509. const double destinationH) const throw();
  14510. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14511. into the destination rectangle using the current flags.
  14512. */
  14513. const AffineTransform getTransformToFit (float sourceX,
  14514. float sourceY,
  14515. float sourceW,
  14516. float sourceH,
  14517. const float destinationX,
  14518. const float destinationY,
  14519. const float destinationW,
  14520. const float destinationH) const throw();
  14521. private:
  14522. int flags;
  14523. };
  14524. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14525. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14526. class LowLevelGraphicsContext;
  14527. class Image;
  14528. class RectangleList;
  14529. /**
  14530. A graphics context, used for drawing a component or image.
  14531. When a Component needs painting, a Graphics context is passed to its
  14532. Component::paint() method, and this you then call methods within this
  14533. object to actually draw the component's content.
  14534. A Graphics can also be created from an image, to allow drawing directly onto
  14535. that image.
  14536. @see Component::paint
  14537. */
  14538. class JUCE_API Graphics
  14539. {
  14540. public:
  14541. /** Creates a Graphics object to draw directly onto the given image.
  14542. The graphics object that is created will be set up to draw onto the image,
  14543. with the context's clipping area being the entire size of the image, and its
  14544. origin being the image's origin. To draw into a subsection of an image, use the
  14545. reduceClipRegion() and setOrigin() methods.
  14546. Obviously you shouldn't delete the image before this context is deleted.
  14547. */
  14548. Graphics (Image& imageToDrawOnto) throw();
  14549. /** Destructor. */
  14550. ~Graphics() throw();
  14551. /** Changes the current drawing colour.
  14552. This sets the colour that will now be used for drawing operations - it also
  14553. sets the opacity to that of the colour passed-in.
  14554. If a brush is being used when this method is called, the brush will be deselected,
  14555. and any subsequent drawing will be done with a solid colour brush instead.
  14556. @see setOpacity, setBrush, getColour
  14557. */
  14558. void setColour (const Colour& newColour) throw();
  14559. /** Returns the colour that's currently being used.
  14560. This will return the last colour set by setColour(), even if the colour's not
  14561. currently being used for drawing because a brush has been selected instead.
  14562. @see setColour
  14563. */
  14564. const Colour& getCurrentColour() const throw();
  14565. /** Changes the opacity to use with the current colour.
  14566. If a solid colour is being used for drawing, this changes its opacity (and this
  14567. will be reflected by calls to the getColour() method).
  14568. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14569. */
  14570. void setOpacity (const float newOpacity) throw();
  14571. /** Changes the current brush to use for drawing.
  14572. If a null pointer is passed in, the context will revert to using a solid
  14573. colour for drawing (using the last colour set by setColour()).
  14574. If a brush is passed in, a copy of it will be used for subsequent drawing
  14575. operations until setColour() or setBrush() is called.
  14576. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14577. */
  14578. void setBrush (const Brush* const newBrush) throw();
  14579. /** Changes the font to use for subsequent text-drawing functions.
  14580. Note there's also a setFont (float, int) method to quickly change the size and
  14581. style of the current font.
  14582. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14583. */
  14584. void setFont (const Font& newFont) throw();
  14585. /** Changes the size and style of the currently-selected font.
  14586. This is a convenient shortcut that changes the context's current font to a
  14587. different size or style. The typeface won't be changed.
  14588. @see Font
  14589. */
  14590. void setFont (const float newFontHeight,
  14591. const int fontStyleFlags = Font::plain) throw();
  14592. /** Returns the font that's currently being used for text operations.
  14593. @see setFont
  14594. */
  14595. const Font& getCurrentFont() const throw();
  14596. /** Draws a one-line text string.
  14597. This will use the current colour (or brush) to fill the text. The font is the last
  14598. one specified by setFont().
  14599. @param text the string to draw
  14600. @param startX the position to draw the left-hand edge of the text
  14601. @param baselineY the position of the text's baseline
  14602. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14603. */
  14604. void drawSingleLineText (const String& text,
  14605. const int startX,
  14606. const int baselineY) const throw();
  14607. /** Draws text across multiple lines.
  14608. This will break the text onto a new line where there's a new-line or
  14609. carriage-return character, or at a word-boundary when the text becomes wider
  14610. than the size specified by the maximumLineWidth parameter.
  14611. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14612. */
  14613. void drawMultiLineText (const String& text,
  14614. const int startX,
  14615. const int baselineY,
  14616. const int maximumLineWidth) const throw();
  14617. /** Renders a string of text as a vector path.
  14618. This allows a string to be transformed with an arbitrary AffineTransform and
  14619. rendered using the current colour/brush. It's much slower than the normal text methods
  14620. but more accurate.
  14621. @see setFont
  14622. */
  14623. void drawTextAsPath (const String& text,
  14624. const AffineTransform& transform) const throw();
  14625. /** Draws a line of text within a specified rectangle.
  14626. The text will be positioned within the rectangle based on the justification
  14627. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14628. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14629. flag is true).
  14630. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14631. */
  14632. void drawText (const String& text,
  14633. const int x,
  14634. const int y,
  14635. const int width,
  14636. const int height,
  14637. const Justification& justificationType,
  14638. const bool useEllipsesIfTooBig) const throw();
  14639. /** Tries to draw a text string inside a given space.
  14640. This does its best to make the given text readable within the specified rectangle,
  14641. so it useful for labelling things.
  14642. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14643. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14644. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14645. it's been truncated.
  14646. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14647. both horizontally and vertically.
  14648. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14649. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14650. can set this value to 1.0f.
  14651. @see GlyphArrangement::addFittedText
  14652. */
  14653. void drawFittedText (const String& text,
  14654. const int x,
  14655. const int y,
  14656. const int width,
  14657. const int height,
  14658. const Justification& justificationFlags,
  14659. const int maximumNumberOfLines,
  14660. const float minimumHorizontalScale = 0.7f) const throw();
  14661. /** Fills the context's entire clip region with the current colour or brush.
  14662. (See also the fillAll (const Colour&) method which is a quick way of filling
  14663. it with a given colour).
  14664. */
  14665. void fillAll() const throw();
  14666. /** Fills the context's entire clip region with a given colour.
  14667. This leaves the context's current colour and brush unchanged, it just
  14668. uses the specified colour temporarily.
  14669. */
  14670. void fillAll (const Colour& colourToUse) const throw();
  14671. /** Fills a rectangle with the current colour or brush.
  14672. @see drawRect, fillRoundedRectangle
  14673. */
  14674. void fillRect (int x,
  14675. int y,
  14676. int width,
  14677. int height) const throw();
  14678. /** Fills a rectangle with the current colour or brush. */
  14679. void fillRect (const Rectangle& rectangle) const throw();
  14680. /** Fills a rectangle with the current colour or brush.
  14681. This uses sub-pixel positioning so is slower than the fillRect method which
  14682. takes integer co-ordinates.
  14683. */
  14684. void fillRect (const float x,
  14685. const float y,
  14686. const float width,
  14687. const float height) const throw();
  14688. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14689. @see drawRoundedRectangle, Path::addRoundedRectangle
  14690. */
  14691. void fillRoundedRectangle (const float x,
  14692. const float y,
  14693. const float width,
  14694. const float height,
  14695. const float cornerSize) const throw();
  14696. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14697. @see drawRoundedRectangle, Path::addRoundedRectangle
  14698. */
  14699. void fillRoundedRectangle (const Rectangle& rectangle,
  14700. const float cornerSize) const throw();
  14701. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14702. */
  14703. void fillCheckerBoard (int x, int y,
  14704. int width, int height,
  14705. const int checkWidth,
  14706. const int checkHeight,
  14707. const Colour& colour1,
  14708. const Colour& colour2) const throw();
  14709. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14710. The lines are drawn inside the given rectangle, and greater line thicknesses
  14711. extend inwards.
  14712. @see fillRect
  14713. */
  14714. void drawRect (const int x,
  14715. const int y,
  14716. const int width,
  14717. const int height,
  14718. const int lineThickness = 1) const throw();
  14719. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14720. The lines are drawn inside the given rectangle, and greater line thicknesses
  14721. extend inwards.
  14722. @see fillRect
  14723. */
  14724. void drawRect (const float x,
  14725. const float y,
  14726. const float width,
  14727. const float height,
  14728. const float lineThickness = 1.0f) const throw();
  14729. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14730. The lines are drawn inside the given rectangle, and greater line thicknesses
  14731. extend inwards.
  14732. @see fillRect
  14733. */
  14734. void drawRect (const Rectangle& rectangle,
  14735. const int lineThickness = 1) const throw();
  14736. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14737. @see fillRoundedRectangle, Path::addRoundedRectangle
  14738. */
  14739. void drawRoundedRectangle (const float x,
  14740. const float y,
  14741. const float width,
  14742. const float height,
  14743. const float cornerSize,
  14744. const float lineThickness) const throw();
  14745. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14746. @see fillRoundedRectangle, Path::addRoundedRectangle
  14747. */
  14748. void drawRoundedRectangle (const Rectangle& rectangle,
  14749. const float cornerSize,
  14750. const float lineThickness) const throw();
  14751. /** Draws a 3D raised (or indented) bevel using two colours.
  14752. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14753. extend inwards.
  14754. The top-left colour is used for the top- and left-hand edges of the
  14755. bevel; the bottom-right colour is used for the bottom- and right-hand
  14756. edges.
  14757. If useGradient is true, then the bevel fades out to make it look more curved
  14758. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  14759. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  14760. the centre edges are sharp and it fades towards the outside.
  14761. */
  14762. void drawBevel (const int x,
  14763. const int y,
  14764. const int width,
  14765. const int height,
  14766. const int bevelThickness,
  14767. const Colour& topLeftColour = Colours::white,
  14768. const Colour& bottomRightColour = Colours::black,
  14769. const bool useGradient = true,
  14770. const bool sharpEdgeOnOutside = true) const throw();
  14771. /** Draws a pixel using the current colour or brush.
  14772. */
  14773. void setPixel (int x, int y) const throw();
  14774. /** Fills an ellipse with the current colour or brush.
  14775. The ellipse is drawn to fit inside the given rectangle.
  14776. @see drawEllipse, Path::addEllipse
  14777. */
  14778. void fillEllipse (const float x,
  14779. const float y,
  14780. const float width,
  14781. const float height) const throw();
  14782. /** Draws an elliptical stroke using the current colour or brush.
  14783. @see fillEllipse, Path::addEllipse
  14784. */
  14785. void drawEllipse (const float x,
  14786. const float y,
  14787. const float width,
  14788. const float height,
  14789. const float lineThickness) const throw();
  14790. /** Draws a line between two points.
  14791. The line is 1 pixel wide and drawn with the current colour or brush.
  14792. */
  14793. void drawLine (float startX,
  14794. float startY,
  14795. float endX,
  14796. float endY) const throw();
  14797. /** Draws a line between two points with a given thickness.
  14798. @see Path::addLineSegment
  14799. */
  14800. void drawLine (const float startX,
  14801. const float startY,
  14802. const float endX,
  14803. const float endY,
  14804. const float lineThickness) const throw();
  14805. /** Draws a line between two points.
  14806. The line is 1 pixel wide and drawn with the current colour or brush.
  14807. */
  14808. void drawLine (const Line& line) const throw();
  14809. /** Draws a line between two points with a given thickness.
  14810. @see Path::addLineSegment
  14811. */
  14812. void drawLine (const Line& line,
  14813. const float lineThickness) const throw();
  14814. /** Draws a dashed line using a custom set of dash-lengths.
  14815. @param startX the line's start x co-ordinate
  14816. @param startY the line's start y co-ordinate
  14817. @param endX the line's end x co-ordinate
  14818. @param endY the line's end y co-ordinate
  14819. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14820. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14821. draw 6 pixels, skip 7 pixels, and then repeat.
  14822. @param numDashLengths the number of elements in the array (this must be an even number).
  14823. @param lineThickness the thickness of the line to draw
  14824. @see PathStrokeType::createDashedStroke
  14825. */
  14826. void drawDashedLine (const float startX,
  14827. const float startY,
  14828. const float endX,
  14829. const float endY,
  14830. const float* const dashLengths,
  14831. const int numDashLengths,
  14832. const float lineThickness = 1.0f) const throw();
  14833. /** Draws a vertical line of pixels at a given x position.
  14834. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14835. positions, and these will be anti-aliased if necessary.
  14836. */
  14837. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14838. /** Draws a horizontal line of pixels at a given y position.
  14839. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14840. positions, and these will be anti-aliased if necessary.
  14841. */
  14842. void drawHorizontalLine (const int y, float left, float right) const throw();
  14843. /** Fills a path using the currently selected colour or brush.
  14844. */
  14845. void fillPath (const Path& path,
  14846. const AffineTransform& transform = AffineTransform::identity) const throw();
  14847. /** Draws a path's outline using the currently selected colour or brush.
  14848. */
  14849. void strokePath (const Path& path,
  14850. const PathStrokeType& strokeType,
  14851. const AffineTransform& transform = AffineTransform::identity) const throw();
  14852. /** Draws a line with an arrowhead.
  14853. @param startX the line's start x co-ordinate
  14854. @param startY the line's start y co-ordinate
  14855. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14856. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14857. @param lineThickness the thickness of the line
  14858. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14859. @param arrowheadLength the length of the arrow head (along the length of the line)
  14860. */
  14861. void drawArrow (const float startX,
  14862. const float startY,
  14863. const float endX,
  14864. const float endY,
  14865. const float lineThickness,
  14866. const float arrowheadWidth,
  14867. const float arrowheadLength) const throw();
  14868. /** Types of rendering quality that can be specified when drawing images.
  14869. @see blendImage, Graphics::setImageResamplingQuality
  14870. */
  14871. enum ResamplingQuality
  14872. {
  14873. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14874. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14875. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14876. };
  14877. /** Changes the quality that will be used when resampling images.
  14878. By default a Graphics object will be set to mediumRenderingQuality.
  14879. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14880. */
  14881. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14882. /** Draws an image.
  14883. This will draw the whole of an image, positioning its top-left corner at the
  14884. given co-ordinates, and keeping its size the same. This is the simplest image
  14885. drawing method - the others give more control over the scaling and clipping
  14886. of the images.
  14887. Images are composited using the context's current opacity, so if you
  14888. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14889. (or setColour() with an opaque colour) before drawing images.
  14890. */
  14891. void drawImageAt (const Image* const imageToDraw,
  14892. const int topLeftX,
  14893. const int topLeftY,
  14894. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14895. /** Draws part of an image, rescaling it to fit in a given target region.
  14896. The specified area of the source image is rescaled and drawn to fill the
  14897. specifed destination rectangle.
  14898. Images are composited using the context's current opacity, so if you
  14899. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14900. (or setColour() with an opaque colour) before drawing images.
  14901. @param imageToDraw the image to overlay
  14902. @param destX the left of the destination rectangle
  14903. @param destY the top of the destination rectangle
  14904. @param destWidth the width of the destination rectangle
  14905. @param destHeight the height of the destination rectangle
  14906. @param sourceX the left of the rectangle to copy from the source image
  14907. @param sourceY the top of the rectangle to copy from the source image
  14908. @param sourceWidth the width of the rectangle to copy from the source image
  14909. @param sourceHeight the height of the rectangle to copy from the source image
  14910. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14911. the source image's alpha channel is used as a mask with
  14912. which to fill the destination using the current colour
  14913. or brush. (If the source is has no alpha channel, then
  14914. it will just fill the target with a solid rectangle)
  14915. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14916. */
  14917. void drawImage (const Image* const imageToDraw,
  14918. int destX,
  14919. int destY,
  14920. int destWidth,
  14921. int destHeight,
  14922. int sourceX,
  14923. int sourceY,
  14924. int sourceWidth,
  14925. int sourceHeight,
  14926. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14927. /** Draws part of an image, having applied an affine transform to it.
  14928. This lets you throw the image around in some wacky ways, rotate it, shear,
  14929. scale it, etc.
  14930. A clipping subregion is specified within the source image and no pixels
  14931. outside this region will be used.
  14932. Images are composited using the context's current opacity, so if you
  14933. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14934. (or setColour() with an opaque colour) before drawing images.
  14935. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14936. are ignored and it is filled with the current brush, masked by its alpha channel.
  14937. @see setImageResamplingQuality, drawImage
  14938. */
  14939. void drawImageTransformed (const Image* const imageToDraw,
  14940. int sourceClipX,
  14941. int sourceClipY,
  14942. int sourceClipWidth,
  14943. int sourceClipHeight,
  14944. const AffineTransform& transform,
  14945. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14946. /** Draws an image to fit within a designated rectangle.
  14947. If the image is too big or too small for the space, it will be rescaled
  14948. to fit as nicely as it can do without affecting its aspect ratio. It will
  14949. then be placed within the target rectangle according to the justification flags
  14950. specified.
  14951. @param imageToDraw the source image to draw
  14952. @param destX top-left of the target rectangle to fit it into
  14953. @param destY top-left of the target rectangle to fit it into
  14954. @param destWidth size of the target rectangle to fit the image into
  14955. @param destHeight size of the target rectangle to fit the image into
  14956. @param placementWithinTarget this specifies how the image should be positioned
  14957. within the target rectangle - see the RectanglePlacement
  14958. class for more details about this.
  14959. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14960. alpha channel will be used as a mask with which to
  14961. draw with the current brush or colour. This is
  14962. similar to fillAlphaMap(), and see also drawImage()
  14963. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14964. */
  14965. void drawImageWithin (const Image* const imageToDraw,
  14966. const int destX,
  14967. const int destY,
  14968. const int destWidth,
  14969. const int destHeight,
  14970. const RectanglePlacement& placementWithinTarget,
  14971. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14972. /** Returns the position of the bounding box for the current clipping region.
  14973. @see getClipRegion, clipRegionIntersects
  14974. */
  14975. const Rectangle getClipBounds() const throw();
  14976. /** Checks whether a rectangle overlaps the context's clipping region.
  14977. If this returns false, no part of the given area can be drawn onto, so this
  14978. method can be used to optimise a component's paint() method, by letting it
  14979. avoid drawing complex objects that aren't within the region being repainted.
  14980. */
  14981. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14982. /** Intersects the current clipping region with another region.
  14983. @returns true if the resulting clipping region is non-zero in size
  14984. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14985. */
  14986. bool reduceClipRegion (const int x, const int y,
  14987. const int width, const int height) throw();
  14988. /** Intersects the current clipping region with a rectangle list region.
  14989. @returns true if the resulting clipping region is non-zero in size
  14990. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14991. */
  14992. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14993. /** Excludes a rectangle to stop it being drawn into. */
  14994. void excludeClipRegion (const int x, const int y,
  14995. const int width, const int height) throw();
  14996. /** Returns true if no drawing can be done because the clip region is zero. */
  14997. bool isClipEmpty() const throw();
  14998. /** Saves the current graphics state on an internal stack.
  14999. To restore the state, use restoreState().
  15000. */
  15001. void saveState() throw();
  15002. /** Restores a graphics state that was previously saved with saveState().
  15003. */
  15004. void restoreState() throw();
  15005. /** Moves the position of the context's origin.
  15006. This changes the position that the context considers to be (0, 0) to
  15007. the specified position.
  15008. So if you call setOrigin (100, 100), then the position that was previously
  15009. referred to as (100, 100) will subsequently be considered to be (0, 0).
  15010. @see reduceClipRegion
  15011. */
  15012. void setOrigin (const int newOriginX,
  15013. const int newOriginY) throw();
  15014. /** Resets the current colour, brush, and font to default settings. */
  15015. void resetToDefaultState() throw();
  15016. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  15017. bool isVectorDevice() const throw();
  15018. juce_UseDebuggingNewOperator
  15019. /** Create a graphics that uses a given low-level renderer.
  15020. For internal use only.
  15021. NB. The context will NOT be deleted by this object when it is deleted.
  15022. */
  15023. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  15024. /** @internal */
  15025. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  15026. private:
  15027. LowLevelGraphicsContext* const context;
  15028. const bool ownsContext;
  15029. struct GraphicsState
  15030. {
  15031. GraphicsState() throw();
  15032. GraphicsState (const GraphicsState&) throw();
  15033. ~GraphicsState() throw();
  15034. Colour colour;
  15035. Brush* brush;
  15036. Font font;
  15037. ResamplingQuality quality;
  15038. };
  15039. GraphicsState* state;
  15040. OwnedArray <GraphicsState> stateStack;
  15041. bool saveStatePending;
  15042. void saveStateIfPending() throw();
  15043. const Graphics& operator= (const Graphics& other);
  15044. Graphics (const Graphics&);
  15045. };
  15046. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  15047. /********* End of inlined file: juce_Graphics.h *********/
  15048. /**
  15049. A graphical effect filter that can be applied to components.
  15050. An ImageEffectFilter can be applied to the image that a component
  15051. paints before it hits the screen.
  15052. This is used for adding effects like shadows, blurs, etc.
  15053. @see Component::setComponentEffect
  15054. */
  15055. class JUCE_API ImageEffectFilter
  15056. {
  15057. public:
  15058. /** Overridden to render the effect.
  15059. The implementation of this method must use the image that is passed in
  15060. as its source, and should render its output to the graphics context passed in.
  15061. @param sourceImage the image that the source component has just rendered with
  15062. its paint() method. The image may or may not have an alpha
  15063. channel, depending on whether the component is opaque.
  15064. @param destContext the graphics context to use to draw the resultant image.
  15065. */
  15066. virtual void applyEffect (Image& sourceImage,
  15067. Graphics& destContext) = 0;
  15068. /** Destructor. */
  15069. virtual ~ImageEffectFilter() {}
  15070. };
  15071. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15072. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  15073. /********* Start of inlined file: juce_RectangleList.h *********/
  15074. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  15075. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  15076. /**
  15077. Maintains a set of rectangles as a complex region.
  15078. This class allows a set of rectangles to be treated as a solid shape, and can
  15079. add and remove rectangular sections of it, and simplify overlapping or
  15080. adjacent rectangles.
  15081. @see Rectangle
  15082. */
  15083. class JUCE_API RectangleList
  15084. {
  15085. public:
  15086. /** Creates an empty RectangleList */
  15087. RectangleList() throw();
  15088. /** Creates a copy of another list */
  15089. RectangleList (const RectangleList& other) throw();
  15090. /** Creates a list containing just one rectangle. */
  15091. RectangleList (const Rectangle& rect) throw();
  15092. /** Copies this list from another one. */
  15093. const RectangleList& operator= (const RectangleList& other) throw();
  15094. /** Destructor. */
  15095. ~RectangleList() throw();
  15096. /** Returns true if the region is empty. */
  15097. bool isEmpty() const throw();
  15098. /** Returns the number of rectangles in the list. */
  15099. int getNumRectangles() const throw() { return rects.size(); }
  15100. /** Returns one of the rectangles at a particular index.
  15101. @returns the rectangle at the index, or an empty rectangle if the
  15102. index is out-of-range.
  15103. */
  15104. const Rectangle getRectangle (const int index) const throw();
  15105. /** Removes all rectangles to leave an empty region. */
  15106. void clear() throw();
  15107. /** Merges a new rectangle into the list.
  15108. The rectangle being added will first be clipped to remove any parts of it
  15109. that overlap existing rectangles in the list.
  15110. */
  15111. void add (const int x, const int y,
  15112. const int w, const int h) throw();
  15113. /** Merges a new rectangle into the list.
  15114. The rectangle being added will first be clipped to remove any parts of it
  15115. that overlap existing rectangles in the list, and adjacent rectangles will be
  15116. merged into it.
  15117. */
  15118. void add (const Rectangle& rect) throw();
  15119. /** Dumbly adds a rectangle to the list without checking for overlaps.
  15120. This simply adds the rectangle to the end, it doesn't merge it or remove
  15121. any overlapping bits.
  15122. */
  15123. void addWithoutMerging (const Rectangle& rect) throw();
  15124. /** Merges another rectangle list into this one.
  15125. Any overlaps between the two lists will be clipped, so that the result is
  15126. the union of both lists.
  15127. */
  15128. void add (const RectangleList& other) throw();
  15129. /** Removes a rectangular region from the list.
  15130. Any rectangles in the list which overlap this will be clipped and subdivided
  15131. if necessary.
  15132. */
  15133. void subtract (const Rectangle& rect) throw();
  15134. /** Removes all areas in another RectangleList from this one.
  15135. Any rectangles in the list which overlap this will be clipped and subdivided
  15136. if necessary.
  15137. */
  15138. void subtract (const RectangleList& otherList) throw();
  15139. /** Removes any areas of the region that lie outside a given rectangle.
  15140. Any rectangles in the list which overlap this will be clipped and subdivided
  15141. if necessary.
  15142. Returns true if the resulting region is not empty, false if it is empty.
  15143. @see getIntersectionWith
  15144. */
  15145. bool clipTo (const Rectangle& rect) throw();
  15146. /** Removes any areas of the region that lie outside a given rectangle list.
  15147. Any rectangles in this object which overlap the specified list will be clipped
  15148. and subdivided if necessary.
  15149. Returns true if the resulting region is not empty, false if it is empty.
  15150. @see getIntersectionWith
  15151. */
  15152. bool clipTo (const RectangleList& other) throw();
  15153. /** Creates a region which is the result of clipping this one to a given rectangle.
  15154. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  15155. resulting region into the list whose reference is passed-in.
  15156. Returns true if the resulting region is not empty, false if it is empty.
  15157. @see clipTo
  15158. */
  15159. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15160. /** Swaps the contents of this and another list.
  15161. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15162. to swap them.
  15163. */
  15164. void swapWith (RectangleList& otherList) throw();
  15165. /** Checks whether the region contains a given point.
  15166. @returns true if the point lies within one of the rectangles in the list
  15167. */
  15168. bool containsPoint (const int x, const int y) const throw();
  15169. /** Checks whether the region contains the whole of a given rectangle.
  15170. @returns true all parts of the rectangle passed in lie within the region
  15171. defined by this object
  15172. @see intersectsRectangle, containsPoint
  15173. */
  15174. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15175. /** Checks whether the region contains any part of a given rectangle.
  15176. @returns true if any part of the rectangle passed in lies within the region
  15177. defined by this object
  15178. @see containsRectangle
  15179. */
  15180. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15181. /** Checks whether this region intersects any part of another one.
  15182. @see intersectsRectangle
  15183. */
  15184. bool intersects (const RectangleList& other) const throw();
  15185. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15186. const Rectangle getBounds() const throw();
  15187. /** Optimises the list into a minimum number of constituent rectangles.
  15188. This will try to combine any adjacent rectangles into larger ones where
  15189. possible, to simplify lists that might have been fragmented by repeated
  15190. add/subtract calls.
  15191. */
  15192. void consolidate() throw();
  15193. /** Adds an x and y value to all the co-ordinates. */
  15194. void offsetAll (const int dx, const int dy) throw();
  15195. /** Creates a Path object to represent this region. */
  15196. const Path toPath() const throw();
  15197. /** An iterator for accessing all the rectangles in a RectangleList. */
  15198. class Iterator
  15199. {
  15200. public:
  15201. Iterator (const RectangleList& list) throw();
  15202. ~Iterator() throw();
  15203. /** Advances to the next rectangle, and returns true if it's not finished.
  15204. Call this before using getRectangle() to find the rectangle that was returned.
  15205. */
  15206. bool next() throw();
  15207. /** Returns the current rectangle. */
  15208. const Rectangle* getRectangle() const throw() { return current; }
  15209. juce_UseDebuggingNewOperator
  15210. private:
  15211. const Rectangle* current;
  15212. const RectangleList& owner;
  15213. int index;
  15214. Iterator (const Iterator&);
  15215. const Iterator& operator= (const Iterator&);
  15216. };
  15217. juce_UseDebuggingNewOperator
  15218. private:
  15219. friend class Iterator;
  15220. Array <Rectangle> rects;
  15221. };
  15222. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15223. /********* End of inlined file: juce_RectangleList.h *********/
  15224. /********* Start of inlined file: juce_BorderSize.h *********/
  15225. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15226. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15227. /**
  15228. Specifies a set of gaps to be left around the sides of a rectangle.
  15229. This is basically the size of the spaces at the top, bottom, left and right of
  15230. a rectangle. It's used by various component classes to specify borders.
  15231. @see Rectangle
  15232. */
  15233. class JUCE_API BorderSize
  15234. {
  15235. public:
  15236. /** Creates a null border.
  15237. All sizes are left as 0.
  15238. */
  15239. BorderSize() throw();
  15240. /** Creates a copy of another border. */
  15241. BorderSize (const BorderSize& other) throw();
  15242. /** Creates a border with the given gaps. */
  15243. BorderSize (const int topGap,
  15244. const int leftGap,
  15245. const int bottomGap,
  15246. const int rightGap) throw();
  15247. /** Creates a border with the given gap on all sides. */
  15248. BorderSize (const int allGaps) throw();
  15249. /** Destructor. */
  15250. ~BorderSize() throw();
  15251. /** Returns the gap that should be left at the top of the region. */
  15252. int getTop() const throw() { return top; }
  15253. /** Returns the gap that should be left at the top of the region. */
  15254. int getLeft() const throw() { return left; }
  15255. /** Returns the gap that should be left at the top of the region. */
  15256. int getBottom() const throw() { return bottom; }
  15257. /** Returns the gap that should be left at the top of the region. */
  15258. int getRight() const throw() { return right; }
  15259. /** Returns the sum of the top and bottom gaps. */
  15260. int getTopAndBottom() const throw() { return top + bottom; }
  15261. /** Returns the sum of the left and right gaps. */
  15262. int getLeftAndRight() const throw() { return left + right; }
  15263. /** Changes the top gap. */
  15264. void setTop (const int newTopGap) throw();
  15265. /** Changes the left gap. */
  15266. void setLeft (const int newLeftGap) throw();
  15267. /** Changes the bottom gap. */
  15268. void setBottom (const int newBottomGap) throw();
  15269. /** Changes the right gap. */
  15270. void setRight (const int newRightGap) throw();
  15271. /** Returns a rectangle with these borders removed from it. */
  15272. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15273. /** Removes this border from a given rectangle. */
  15274. void subtractFrom (Rectangle& rectangle) const throw();
  15275. /** Returns a rectangle with these borders added around it. */
  15276. const Rectangle addedTo (const Rectangle& original) const throw();
  15277. /** Adds this border around a given rectangle. */
  15278. void addTo (Rectangle& original) const throw();
  15279. bool operator== (const BorderSize& other) const throw();
  15280. bool operator!= (const BorderSize& other) const throw();
  15281. juce_UseDebuggingNewOperator
  15282. private:
  15283. int top, left, bottom, right;
  15284. };
  15285. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15286. /********* End of inlined file: juce_BorderSize.h *********/
  15287. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15288. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15289. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15290. class Component;
  15291. class Graphics;
  15292. /********* Start of inlined file: juce_MessageListener.h *********/
  15293. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15294. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15295. /********* Start of inlined file: juce_Message.h *********/
  15296. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15297. #define __JUCE_MESSAGE_JUCEHEADER__
  15298. class MessageListener;
  15299. class MessageManager;
  15300. /** The base class for objects that can be delivered to a MessageListener.
  15301. The simplest Message object contains a few integer and pointer parameters
  15302. that the user can set, and this is enough for a lot of purposes. For passing more
  15303. complex data, subclasses of Message can also be used.
  15304. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15305. */
  15306. class JUCE_API Message
  15307. {
  15308. public:
  15309. /** Creates an uninitialised message.
  15310. The class's variables will also be left uninitialised.
  15311. */
  15312. Message() throw();
  15313. /** Creates a message object, filling in the member variables.
  15314. The corresponding public member variables will be set from the parameters
  15315. passed in.
  15316. */
  15317. Message (const int intParameter1,
  15318. const int intParameter2,
  15319. const int intParameter3,
  15320. void* const pointerParameter) throw();
  15321. /** Destructor. */
  15322. virtual ~Message() throw();
  15323. // These values can be used for carrying simple data that the application needs to
  15324. // pass around. For more complex messages, just create a subclass.
  15325. int intParameter1; /**< user-defined integer value. */
  15326. int intParameter2; /**< user-defined integer value. */
  15327. int intParameter3; /**< user-defined integer value. */
  15328. void* pointerParameter; /**< user-defined pointer value. */
  15329. juce_UseDebuggingNewOperator
  15330. private:
  15331. friend class MessageListener;
  15332. friend class MessageManager;
  15333. MessageListener* messageRecipient;
  15334. Message (const Message&);
  15335. const Message& operator= (const Message&);
  15336. };
  15337. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15338. /********* End of inlined file: juce_Message.h *********/
  15339. /**
  15340. MessageListener subclasses can post and receive Message objects.
  15341. @see Message, MessageManager, ActionListener, ChangeListener
  15342. */
  15343. class JUCE_API MessageListener
  15344. {
  15345. protected:
  15346. /** Creates a MessageListener. */
  15347. MessageListener() throw();
  15348. public:
  15349. /** Destructor.
  15350. When a MessageListener is deleted, it removes itself from a global list
  15351. of registered listeners, so that the isValidMessageListener() method
  15352. will no longer return true.
  15353. */
  15354. virtual ~MessageListener();
  15355. /** This is the callback method that receives incoming messages.
  15356. This is called by the MessageManager from its dispatch loop.
  15357. @see postMessage
  15358. */
  15359. virtual void handleMessage (const Message& message) = 0;
  15360. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15361. later on.
  15362. This method can be called safely by any thread.
  15363. @param message the message object to send - this will be deleted
  15364. automatically by the message queue, so don't keep any
  15365. references to it after calling this method.
  15366. @see handleMessage
  15367. */
  15368. void postMessage (Message* const message) const throw();
  15369. /** Checks whether this MessageListener has been deleted.
  15370. Although not foolproof, this method is safe to call on dangling or null
  15371. pointers. A list of active MessageListeners is kept internally, so this
  15372. checks whether the object is on this list or not.
  15373. Note that it's possible to get a false-positive here, if an object is
  15374. deleted and another is subsequently created that happens to be at the
  15375. exact same memory location, but I can't think of a good way of avoiding
  15376. this.
  15377. */
  15378. bool isValidMessageListener() const throw();
  15379. };
  15380. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15381. /********* End of inlined file: juce_MessageListener.h *********/
  15382. class ComponentBoundsConstrainer;
  15383. class ComponentDeletionWatcher;
  15384. /**
  15385. The base class for window objects that wrap a component as a real operating
  15386. system object.
  15387. This is an abstract base class - the platform specific code contains default
  15388. implementations of it that create and manage windows.
  15389. @see Component::createNewPeer
  15390. */
  15391. class JUCE_API ComponentPeer : public MessageListener
  15392. {
  15393. public:
  15394. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15395. enum StyleFlags
  15396. {
  15397. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15398. entry on the taskbar (ignored on MacOSX) */
  15399. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15400. tooltip, etc. */
  15401. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15402. through it (may not be possible on some platforms). */
  15403. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15404. title bar and frame\. if not specified, the window will be
  15405. borderless. */
  15406. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15407. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15408. minimise button on it. */
  15409. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15410. maximise button on it. */
  15411. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15412. close button on it. */
  15413. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15414. not be possible on all platforms). */
  15415. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15416. do its own repainting, but only to repaint when the
  15417. performAnyPendingRepaintsNow() method is called. */
  15418. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15419. be used for things like plugin windows, to stop them interfering
  15420. with the host's shortcut keys */
  15421. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15422. };
  15423. /** Creates a peer.
  15424. The component is the one that we intend to represent, and the style flags are
  15425. a combination of the values in the StyleFlags enum
  15426. */
  15427. ComponentPeer (Component* const component,
  15428. const int styleFlags) throw();
  15429. /** Destructor. */
  15430. virtual ~ComponentPeer();
  15431. /** Returns the component being represented by this peer. */
  15432. Component* getComponent() const throw() { return component; }
  15433. /** Returns the set of style flags that were set when the window was created.
  15434. @see Component::addToDesktop
  15435. */
  15436. int getStyleFlags() const throw() { return styleFlags; }
  15437. /** Returns the raw handle to whatever kind of window is being used.
  15438. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15439. but rememeber there's no guarantees what you'll get back.
  15440. */
  15441. virtual void* getNativeHandle() const = 0;
  15442. /** Shows or hides the window. */
  15443. virtual void setVisible (bool shouldBeVisible) = 0;
  15444. /** Changes the title of the window. */
  15445. virtual void setTitle (const String& title) = 0;
  15446. /** Moves the window without changing its size.
  15447. If the native window is contained in another window, then the co-ordinates are
  15448. relative to the parent window's origin, not the screen origin.
  15449. This should result in a callback to handleMovedOrResized().
  15450. */
  15451. virtual void setPosition (int x, int y) = 0;
  15452. /** Resizes the window without changing its position.
  15453. This should result in a callback to handleMovedOrResized().
  15454. */
  15455. virtual void setSize (int w, int h) = 0;
  15456. /** Moves and resizes the window.
  15457. If the native window is contained in another window, then the co-ordinates are
  15458. relative to the parent window's origin, not the screen origin.
  15459. This should result in a callback to handleMovedOrResized().
  15460. */
  15461. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15462. /** Returns the current position and size of the window.
  15463. If the native window is contained in another window, then the co-ordinates are
  15464. relative to the parent window's origin, not the screen origin.
  15465. */
  15466. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15467. /** Returns the x-position of this window, relative to the screen's origin. */
  15468. virtual int getScreenX() const = 0;
  15469. /** Returns the y-position of this window, relative to the screen's origin. */
  15470. virtual int getScreenY() const = 0;
  15471. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15472. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15473. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15474. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15475. /** Minimises the window. */
  15476. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15477. /** True if the window is currently minimised. */
  15478. virtual bool isMinimised() const = 0;
  15479. /** Enable/disable fullscreen mode for the window. */
  15480. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15481. /** True if the window is currently full-screen. */
  15482. virtual bool isFullScreen() const = 0;
  15483. /** Sets the size to restore to if fullscreen mode is turned off. */
  15484. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15485. /** Returns the size to restore to if fullscreen mode is turned off. */
  15486. const Rectangle& getNonFullScreenBounds() const throw();
  15487. /** Attempts to change the icon associated with this window.
  15488. */
  15489. virtual void setIcon (const Image& newIcon) = 0;
  15490. /** Sets a constrainer to use if the peer can resize itself.
  15491. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15492. */
  15493. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15494. /** Returns the current constrainer, if one has been set. */
  15495. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15496. /** Checks if a point is in the window.
  15497. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15498. is false, then this returns false if the point is actually inside a child of this
  15499. window.
  15500. */
  15501. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15502. /** Returns the size of the window frame that's around this window.
  15503. Whether or not the window has a normal window frame depends on the flags
  15504. that were set when the window was created by Component::addToDesktop()
  15505. */
  15506. virtual const BorderSize getFrameSize() const = 0;
  15507. /** This is called when the window's bounds change.
  15508. A peer implementation must call this when the window is moved and resized, so that
  15509. this method can pass the message on to the component.
  15510. */
  15511. void handleMovedOrResized();
  15512. /** This is called if the screen resolution changes.
  15513. A peer implementation must call this if the monitor arrangement changes or the available
  15514. screen size changes.
  15515. */
  15516. void handleScreenSizeChange();
  15517. /** This is called to repaint the component into the given context. */
  15518. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15519. /** Sets this window to either be always-on-top or normal.
  15520. Some kinds of window might not be able to do this, so should return false.
  15521. */
  15522. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15523. /** Brings the window to the top, optionally also giving it focus. */
  15524. virtual void toFront (bool makeActive) = 0;
  15525. /** Moves the window to be just behind another one. */
  15526. virtual void toBehind (ComponentPeer* other) = 0;
  15527. /** Called when the window is brought to the front, either by the OS or by a call
  15528. to toFront().
  15529. */
  15530. void handleBroughtToFront();
  15531. /** True if the window has the keyboard focus. */
  15532. virtual bool isFocused() const = 0;
  15533. /** Tries to give the window keyboard focus. */
  15534. virtual void grabFocus() = 0;
  15535. /** Tells the window that text input may be required at the given position.
  15536. This may cause things like a virtual on-screen keyboard to appear, depending
  15537. on the OS.
  15538. */
  15539. virtual void textInputRequired (int x, int y) = 0;
  15540. /** Called when the window gains keyboard focus. */
  15541. void handleFocusGain();
  15542. /** Called when the window loses keyboard focus. */
  15543. void handleFocusLoss();
  15544. Component* getLastFocusedSubcomponent() const throw();
  15545. /** Called when a key is pressed.
  15546. For keycode info, see the KeyPress class.
  15547. Returns true if the keystroke was used.
  15548. */
  15549. bool handleKeyPress (const int keyCode,
  15550. const juce_wchar textCharacter);
  15551. /** Called whenever a key is pressed or released.
  15552. Returns true if the keystroke was used.
  15553. */
  15554. bool handleKeyUpOrDown();
  15555. /** Called whenever a modifier key is pressed or released. */
  15556. void handleModifierKeysChange();
  15557. /** Invalidates a region of the window to be repainted asynchronously. */
  15558. virtual void repaint (int x, int y, int w, int h) = 0;
  15559. /** This can be called (from the message thread) to cause the immediate redrawing
  15560. of any areas of this window that need repainting.
  15561. You shouldn't ever really need to use this, it's mainly for special purposes
  15562. like supporting audio plugins where the host's event loop is out of our control.
  15563. */
  15564. virtual void performAnyPendingRepaintsNow() = 0;
  15565. void handleMouseEnter (int x, int y, const int64 time);
  15566. void handleMouseMove (int x, int y, const int64 time);
  15567. void handleMouseDown (int x, int y, const int64 time);
  15568. void handleMouseDrag (int x, int y, const int64 time);
  15569. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15570. void handleMouseExit (int x, int y, const int64 time);
  15571. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15572. /** Causes a mouse-move callback to be made asynchronously. */
  15573. void sendFakeMouseMove() throw();
  15574. void handleUserClosingWindow();
  15575. void handleFileDragMove (const StringArray& files, int x, int y);
  15576. void handleFileDragExit (const StringArray& files);
  15577. void handleFileDragDrop (const StringArray& files, int x, int y);
  15578. /** Resets the masking region.
  15579. The subclass should call this every time it's about to call the handlePaint
  15580. method.
  15581. @see addMaskedRegion
  15582. */
  15583. void clearMaskedRegion() throw();
  15584. /** Adds a rectangle to the set of areas not to paint over.
  15585. A component can call this on its peer during its paint() method, to signal
  15586. that the painting code should ignore a given region. The reason
  15587. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15588. The masked region is cleared each time before a paint happens, so a component
  15589. will have to make sure it calls this every time it's painted.
  15590. */
  15591. void addMaskedRegion (int x, int y, int w, int h) throw();
  15592. /** Returns the number of currently-active peers.
  15593. @see getPeer
  15594. */
  15595. static int getNumPeers() throw();
  15596. /** Returns one of the currently-active peers.
  15597. @see getNumPeers
  15598. */
  15599. static ComponentPeer* getPeer (const int index) throw();
  15600. /** Checks if this peer object is valid.
  15601. @see getNumPeers
  15602. */
  15603. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15604. juce_UseDebuggingNewOperator
  15605. protected:
  15606. Component* const component;
  15607. const int styleFlags;
  15608. RectangleList maskedRegion;
  15609. Rectangle lastNonFullscreenBounds;
  15610. uint32 lastPaintTime;
  15611. ComponentBoundsConstrainer* constrainer;
  15612. static void updateCurrentModifiers() throw();
  15613. /** @internal */
  15614. void handleMessage (const Message& message);
  15615. private:
  15616. Component* lastFocusedComponent;
  15617. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15618. Component* lastDragAndDropCompUnderMouse;
  15619. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15620. friend class Component;
  15621. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15622. void setLastDragDropTarget (Component* comp);
  15623. ComponentPeer (const ComponentPeer&);
  15624. const ComponentPeer& operator= (const ComponentPeer&);
  15625. };
  15626. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15627. /********* End of inlined file: juce_ComponentPeer.h *********/
  15628. class LookAndFeel;
  15629. /**
  15630. The base class for all JUCE user-interface objects.
  15631. */
  15632. class JUCE_API Component : public MouseListener,
  15633. protected MessageListener
  15634. {
  15635. public:
  15636. /** Creates a component.
  15637. To get it to actually appear, you'll also need to:
  15638. - Either add it to a parent component or use the addToDesktop() method to
  15639. make it a desktop window
  15640. - Set its size and position to something sensible
  15641. - Use setVisible() to make it visible
  15642. And for it to serve any useful purpose, you'll need to write a
  15643. subclass of Component or use one of the other types of component from
  15644. the library.
  15645. */
  15646. Component() throw();
  15647. /** Destructor.
  15648. Note that when a component is deleted, any child components it might
  15649. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15650. */
  15651. virtual ~Component();
  15652. /** Creates a component, setting its name at the same time.
  15653. @see getName, setName
  15654. */
  15655. Component (const String& componentName) throw();
  15656. /** Returns the name of this component.
  15657. @see setName
  15658. */
  15659. const String& getName() const throw() { return componentName_; }
  15660. /** Sets the name of this component.
  15661. When the name changes, all registered ComponentListeners will receive a
  15662. ComponentListener::componentNameChanged() callback.
  15663. @see getName
  15664. */
  15665. virtual void setName (const String& newName);
  15666. /** Checks whether this Component object has been deleted.
  15667. This will check whether this object is still a valid component, or whether
  15668. it's been deleted.
  15669. It's safe to call this on null or dangling pointers, but note that there is a
  15670. small risk if another new (but different) component has been created at the
  15671. same memory address which this one occupied, this methods can return a
  15672. false positive.
  15673. */
  15674. bool isValidComponent() const throw();
  15675. /** Makes the component visible or invisible.
  15676. This method will show or hide the component.
  15677. Note that components default to being non-visible when first created.
  15678. Also note that visible components won't be seen unless all their parent components
  15679. are also visible.
  15680. This method will call visibilityChanged() and also componentVisibilityChanged()
  15681. for any component listeners that are interested in this component.
  15682. @param shouldBeVisible whether to show or hide the component
  15683. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15684. */
  15685. virtual void setVisible (bool shouldBeVisible);
  15686. /** Tests whether the component is visible or not.
  15687. this doesn't necessarily tell you whether this comp is actually on the screen
  15688. because this depends on whether all the parent components are also visible - use
  15689. isShowing() to find this out.
  15690. @see isShowing, setVisible
  15691. */
  15692. bool isVisible() const throw() { return flags.visibleFlag; }
  15693. /** Called when this component's visiblility changes.
  15694. @see setVisible, isVisible
  15695. */
  15696. virtual void visibilityChanged();
  15697. /** Tests whether this component and all its parents are visible.
  15698. @returns true only if this component and all its parents are visible.
  15699. @see isVisible
  15700. */
  15701. bool isShowing() const throw();
  15702. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15703. To do this, this function will cunningly:
  15704. - take a snapshot of the component as it currently looks
  15705. - call setVisible(false) on the component
  15706. - replace it with a special component that will continue drawing the
  15707. snapshot, animating it and gradually making it more transparent
  15708. - when it's gone, the special component will also be deleted
  15709. As soon as this method returns, the component can be safely removed and deleted
  15710. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15711. component's destructor.
  15712. Passing non-zero x and y values will cause the ghostly component image to
  15713. also whizz off by this distance while fading out. If the scale factor is
  15714. not 1.0, it will also zoom from the component's current size to this new size.
  15715. One thing to be careful about is that the parent component must be able to cope
  15716. with this unknown component type being added to it.
  15717. */
  15718. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15719. const int deltaXToMove = 0,
  15720. const int deltaYToMove = 0,
  15721. const float scaleFactorAtEnd = 1.0f);
  15722. /** Makes this component appear as a window on the desktop.
  15723. Note that before calling this, you should make sure that the component's opacity is
  15724. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15725. system will try to create a special transparent window for it, which will generally take
  15726. a lot more CPU to operate (and might not even be possible on some platforms).
  15727. If the component is inside a parent component at the time this method is called, it
  15728. will be first be removed from that parent. Likewise if a component on the desktop
  15729. is subsequently added to another component, it'll be removed from the desktop.
  15730. @param windowStyleFlags a combination of the flags specified in the
  15731. ComponentPeer::StyleFlags enum, which define the
  15732. window's characteristics.
  15733. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15734. in which the juce component should place itself. On Windows,
  15735. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15736. supported on all platforms, and best left as 0 unless you know
  15737. what you're doing
  15738. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15739. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15740. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15741. */
  15742. virtual void addToDesktop (int windowStyleFlags,
  15743. void* nativeWindowToAttachTo = 0);
  15744. /** If the component is currently showing on the desktop, this will hide it.
  15745. You can also use setVisible() to hide a desktop window temporarily, but
  15746. removeFromDesktop() will free any system resources that are being used up.
  15747. @see addToDesktop, isOnDesktop
  15748. */
  15749. void removeFromDesktop();
  15750. /** Returns true if this component is currently showing on the desktop.
  15751. @see addToDesktop, removeFromDesktop
  15752. */
  15753. bool isOnDesktop() const throw();
  15754. /** Returns the heavyweight window that contains this component.
  15755. If this component is itself on the desktop, this will return the window
  15756. object that it is using. Otherwise, it will return the window of
  15757. its top-level parent component.
  15758. This may return 0 if there isn't a desktop component.
  15759. @see addToDesktop, isOnDesktop
  15760. */
  15761. ComponentPeer* getPeer() const throw();
  15762. /** For components on the desktop, this is called if the system wants to close the window.
  15763. This is a signal that either the user or the system wants the window to close. The
  15764. default implementation of this method will trigger an assertion to warn you that your
  15765. component should do something about it, but you can override this to ignore the event
  15766. if you want.
  15767. */
  15768. virtual void userTriedToCloseWindow();
  15769. /** Called for a desktop component which has just been minimised or un-minimised.
  15770. This will only be called for components on the desktop.
  15771. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15772. */
  15773. virtual void minimisationStateChanged (bool isNowMinimised);
  15774. /** Brings the component to the front of its siblings.
  15775. If some of the component's siblings have had their 'always-on-top' flag set,
  15776. then they will still be kept in front of this one (unless of course this
  15777. one is also 'always-on-top').
  15778. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15779. to the component (see grabKeyboardFocus() for more details)
  15780. @see toBack, toBehind, setAlwaysOnTop
  15781. */
  15782. void toFront (const bool shouldAlsoGainFocus);
  15783. /** Changes this component's z-order to be at the back of all its siblings.
  15784. If the component is set to be 'always-on-top', it will only be moved to the
  15785. back of the other other 'always-on-top' components.
  15786. @see toFront, toBehind, setAlwaysOnTop
  15787. */
  15788. void toBack();
  15789. /** Changes this component's z-order so that it's just behind another component.
  15790. @see toFront, toBack
  15791. */
  15792. void toBehind (Component* const other);
  15793. /** Sets whether the component should always be kept at the front of its siblings.
  15794. @see isAlwaysOnTop
  15795. */
  15796. void setAlwaysOnTop (const bool shouldStayOnTop);
  15797. /** Returns true if this component is set to always stay in front of its siblings.
  15798. @see setAlwaysOnTop
  15799. */
  15800. bool isAlwaysOnTop() const throw();
  15801. /** Returns the x co-ordinate of the component's left edge.
  15802. This is a distance in pixels from the left edge of the component's parent.
  15803. @see getScreenX
  15804. */
  15805. inline int getX() const throw() { return bounds_.getX(); }
  15806. /** Returns the y co-ordinate of the top of this component.
  15807. This is a distance in pixels from the top edge of the component's parent.
  15808. @see getScreenY
  15809. */
  15810. inline int getY() const throw() { return bounds_.getY(); }
  15811. /** Returns the component's width in pixels. */
  15812. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15813. /** Returns the component's height in pixels. */
  15814. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15815. /** Returns the x co-ordinate of the component's right-hand edge.
  15816. This is a distance in pixels from the left edge of the component's parent.
  15817. */
  15818. int getRight() const throw() { return bounds_.getRight(); }
  15819. /** Returns the y co-ordinate of the bottom edge of this component.
  15820. This is a distance in pixels from the top edge of the component's parent.
  15821. */
  15822. int getBottom() const throw() { return bounds_.getBottom(); }
  15823. /** Returns this component's bounding box.
  15824. The rectangle returned is relative to the top-left of the component's parent.
  15825. */
  15826. const Rectangle& getBounds() const throw() { return bounds_; }
  15827. /** Returns the region of this component that's not obscured by other, opaque components.
  15828. The RectangleList that is returned represents the area of this component
  15829. which isn't covered by opaque child components.
  15830. If includeSiblings is true, it will also take into account any siblings
  15831. that may be overlapping the component.
  15832. */
  15833. void getVisibleArea (RectangleList& result,
  15834. const bool includeSiblings) const;
  15835. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15836. @see getX, relativePositionToGlobal
  15837. */
  15838. int getScreenX() const throw();
  15839. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15840. @see getY, relativePositionToGlobal
  15841. */
  15842. int getScreenY() const throw();
  15843. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15844. @see globalPositionToRelative, relativePositionToOtherComponent
  15845. */
  15846. void relativePositionToGlobal (int& x, int& y) const throw();
  15847. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15848. @see relativePositionToGlobal, relativePositionToOtherComponent
  15849. */
  15850. void globalPositionToRelative (int& x, int& y) const throw();
  15851. /** Converts a position relative to this component's top-left into a position
  15852. relative to another component's top-left.
  15853. @see relativePositionToGlobal, globalPositionToRelative
  15854. */
  15855. void relativePositionToOtherComponent (const Component* const targetComponent,
  15856. int& x, int& y) const throw();
  15857. /** Moves the component to a new position.
  15858. Changes the component's top-left position (without changing its size).
  15859. The position is relative to the top-left of the component's parent.
  15860. If the component actually moves, this method will make a synchronous call to moved().
  15861. @see setBounds, ComponentListener::componentMovedOrResized
  15862. */
  15863. void setTopLeftPosition (const int x, const int y);
  15864. /** Moves the component to a new position.
  15865. Changes the position of the component's top-right corner (keeping it the same size).
  15866. The position is relative to the top-left of the component's parent.
  15867. If the component actually moves, this method will make a synchronous call to moved().
  15868. */
  15869. void setTopRightPosition (const int x, const int y);
  15870. /** Changes the size of the component.
  15871. A synchronous call to resized() will be occur if the size actually changes.
  15872. */
  15873. void setSize (const int newWidth, const int newHeight);
  15874. /** Changes the component's position and size.
  15875. The co-ordinates are relative to the top-left of the component's parent, or relative
  15876. to the origin of the screen is the component is on the desktop.
  15877. If this method changes the component's top-left position, it will make a synchronous
  15878. call to moved(). If it changes the size, it will also make a call to resized().
  15879. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15880. */
  15881. void setBounds (int x, int y, int width, int height);
  15882. /** Changes the component's position and size.
  15883. @see setBounds
  15884. */
  15885. void setBounds (const Rectangle& newBounds);
  15886. /** Changes the component's position and size in terms of fractions of its parent's size.
  15887. The values are factors of the parent's size, so for example
  15888. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15889. width and height of the parent, with its top-left position 20% of
  15890. the way across and down the parent.
  15891. */
  15892. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15893. const float proportionalWidth, const float proportionalHeight);
  15894. /** Changes the component's position and size based on the amount of space to leave around it.
  15895. This will position the component within its parent, leaving the specified number of
  15896. pixels around each edge.
  15897. */
  15898. void setBoundsInset (const BorderSize& borders);
  15899. /** Positions the component within a given rectangle, keeping its proportions
  15900. unchanged.
  15901. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15902. rectangle as possible without changing its aspect ratio (the component's
  15903. current size is used to determine its aspect ratio, so a zero-size component
  15904. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15905. too big to fit inside the rectangle.
  15906. It will then be positioned within the rectangle according to the justification flags
  15907. specified.
  15908. */
  15909. void setBoundsToFit (int x, int y, int width, int height,
  15910. const Justification& justification,
  15911. const bool onlyReduceInSize);
  15912. /** Changes the position of the component's centre.
  15913. Leaves the component's size unchanged, but sets the position of its centre
  15914. relative to its parent's top-left.
  15915. */
  15916. void setCentrePosition (const int x, const int y);
  15917. /** Changes the position of the component's centre.
  15918. Leaves the position unchanged, but positions its centre relative to its
  15919. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15920. its parent.
  15921. */
  15922. void setCentreRelative (const float x, const float y);
  15923. /** Changes the component's size and centres it within its parent.
  15924. After changing the size, the component will be moved so that it's
  15925. centred within its parent.
  15926. */
  15927. void centreWithSize (const int width, const int height);
  15928. /** Returns a proportion of the component's width.
  15929. This is a handy equivalent of (getWidth() * proportion).
  15930. */
  15931. int proportionOfWidth (const float proportion) const throw();
  15932. /** Returns a proportion of the component's height.
  15933. This is a handy equivalent of (getHeight() * proportion).
  15934. */
  15935. int proportionOfHeight (const float proportion) const throw();
  15936. /** Returns the width of the component's parent.
  15937. If the component has no parent (i.e. if it's on the desktop), this will return
  15938. the width of the screen.
  15939. */
  15940. int getParentWidth() const throw();
  15941. /** Returns the height of the component's parent.
  15942. If the component has no parent (i.e. if it's on the desktop), this will return
  15943. the height of the screen.
  15944. */
  15945. int getParentHeight() const throw();
  15946. /** Returns the screen co-ordinates of the monitor that contains this component.
  15947. If there's only one monitor, this will return its size - if there are multiple
  15948. monitors, it will return the area of the monitor that contains the component's
  15949. centre.
  15950. */
  15951. const Rectangle getParentMonitorArea() const throw();
  15952. /** Returns the number of child components that this component contains.
  15953. @see getChildComponent, getIndexOfChildComponent
  15954. */
  15955. int getNumChildComponents() const throw();
  15956. /** Returns one of this component's child components, by it index.
  15957. The component with index 0 is at the back of the z-order, the one at the
  15958. front will have index (getNumChildComponents() - 1).
  15959. If the index is out-of-range, this will return a null pointer.
  15960. @see getNumChildComponents, getIndexOfChildComponent
  15961. */
  15962. Component* getChildComponent (const int index) const throw();
  15963. /** Returns the index of this component in the list of child components.
  15964. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15965. values are further towards the front.
  15966. Returns -1 if the component passed-in is not a child of this component.
  15967. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15968. */
  15969. int getIndexOfChildComponent (const Component* const child) const throw();
  15970. /** Adds a child component to this one.
  15971. @param child the new component to add. If the component passed-in is already
  15972. the child of another component, it'll first be removed from that.
  15973. @param zOrder The index in the child-list at which this component should be inserted.
  15974. A value of -1 will insert it in front of the others, 0 is the back.
  15975. @see removeChildComponent, addAndMakeVisible, getChild,
  15976. ComponentListener::componentChildrenChanged
  15977. */
  15978. void addChildComponent (Component* const child,
  15979. int zOrder = -1);
  15980. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15981. Quite a useful function, this is just the same as calling addChildComponent()
  15982. followed by setVisible (true) on the child.
  15983. */
  15984. void addAndMakeVisible (Component* const child,
  15985. int zOrder = -1);
  15986. /** Removes one of this component's child-components.
  15987. If the child passed-in isn't actually a child of this component (either because
  15988. it's invalid or is the child of a different parent), then nothing is done.
  15989. Note that removing a child will not delete it!
  15990. @see addChildComponent, ComponentListener::componentChildrenChanged
  15991. */
  15992. void removeChildComponent (Component* const childToRemove);
  15993. /** Removes one of this component's child-components by index.
  15994. This will return a pointer to the component that was removed, or null if
  15995. the index was out-of-range.
  15996. Note that removing a child will not delete it!
  15997. @see addChildComponent, ComponentListener::componentChildrenChanged
  15998. */
  15999. Component* removeChildComponent (const int childIndexToRemove);
  16000. /** Removes all this component's children.
  16001. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  16002. */
  16003. void removeAllChildren();
  16004. /** Removes all this component's children, and deletes them.
  16005. @see removeAllChildren
  16006. */
  16007. void deleteAllChildren();
  16008. /** Returns the component which this component is inside.
  16009. If this is the highest-level component or hasn't yet been added to
  16010. a parent, this will return null.
  16011. */
  16012. Component* getParentComponent() const throw() { return parentComponent_; }
  16013. /** Searches the parent components for a component of a specified class.
  16014. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  16015. component that can be dynamically cast to a MyComp, or will return 0 if none
  16016. of the parents are suitable.
  16017. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  16018. */
  16019. template <class TargetClass>
  16020. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  16021. {
  16022. (void) dummyParameter;
  16023. Component* p = parentComponent_;
  16024. while (p != 0)
  16025. {
  16026. TargetClass* target = dynamic_cast <TargetClass*> (p);
  16027. if (target != 0)
  16028. return target;
  16029. p = p->parentComponent_;
  16030. }
  16031. return 0;
  16032. }
  16033. /** Returns the highest-level component which contains this one or its parents.
  16034. This will search upwards in the parent-hierarchy from this component, until it
  16035. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  16036. not yet added to a parent), and will return that.
  16037. */
  16038. Component* getTopLevelComponent() const throw();
  16039. /** Checks whether a component is anywhere inside this component or its children.
  16040. This will recursively check through this components children to see if the
  16041. given component is anywhere inside.
  16042. */
  16043. bool isParentOf (const Component* possibleChild) const throw();
  16044. /** Called to indicate that the component's parents have changed.
  16045. When a component is added or removed from its parent, this method will
  16046. be called on all of its children (recursively - so all children of its
  16047. children will also be called as well).
  16048. Subclasses can override this if they need to react to this in some way.
  16049. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  16050. */
  16051. virtual void parentHierarchyChanged();
  16052. /** Subclasses can use this callback to be told when children are added or removed.
  16053. @see parentHierarchyChanged
  16054. */
  16055. virtual void childrenChanged();
  16056. /** Tests whether a given point inside the component.
  16057. Overriding this method allows you to create components which only intercept
  16058. mouse-clicks within a user-defined area.
  16059. This is called to find out whether a particular x, y co-ordinate is
  16060. considered to be inside the component or not, and is used by methods such
  16061. as contains() and getComponentAt() to work out which component
  16062. the mouse is clicked on.
  16063. Components with custom shapes will probably want to override it to perform
  16064. some more complex hit-testing.
  16065. The default implementation of this method returns either true or false,
  16066. depending on the value that was set by calling setInterceptsMouseClicks() (true
  16067. is the default return value).
  16068. Note that the hit-test region is not related to the opacity with which
  16069. areas of a component are painted.
  16070. Applications should never call hitTest() directly - instead use the
  16071. contains() method, because this will also test for occlusion by the
  16072. component's parent.
  16073. Note that for components on the desktop, this method will be ignored, because it's
  16074. not always possible to implement this behaviour on all platforms.
  16075. @param x the x co-ordinate to test, relative to the left hand edge of this
  16076. component. This value is guaranteed to be greater than or equal to
  16077. zero, and less than the component's width
  16078. @param y the y co-ordinate to test, relative to the top edge of this
  16079. component. This value is guaranteed to be greater than or equal to
  16080. zero, and less than the component's height
  16081. @returns true if the click is considered to be inside the component
  16082. @see setInterceptsMouseClicks, contains
  16083. */
  16084. virtual bool hitTest (int x, int y);
  16085. /** Changes the default return value for the hitTest() method.
  16086. Setting this to false is an easy way to make a component pass its mouse-clicks
  16087. through to the components behind it.
  16088. When a component is created, the default setting for this is true.
  16089. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  16090. return false (or true for child components if allowClicksOnChildComponents
  16091. is true)
  16092. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  16093. components can be clicked on as normal but clicks on this component pass
  16094. straight through; if this is false and allowClicksOnThisComponent
  16095. is false, then neither this component nor any child components can
  16096. be clicked on
  16097. @see hitTest, getInterceptsMouseClicks
  16098. */
  16099. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  16100. const bool allowClicksOnChildComponents) throw();
  16101. /** Retrieves the current state of the mouse-click interception flags.
  16102. On return, the two parameters are set to the state used in the last call to
  16103. setInterceptsMouseClicks().
  16104. @see setInterceptsMouseClicks
  16105. */
  16106. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  16107. bool& allowsClicksOnChildComponents) const throw();
  16108. /** Returns true if a given point lies within this component or one of its children.
  16109. Never override this method! Use hitTest to create custom hit regions.
  16110. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16111. @param y the y co-ordinate to test, relative to this component's top edge.
  16112. @returns true if the point is within the component's hit-test area, but only if
  16113. that part of the component isn't clipped by its parent component. Note
  16114. that this won't take into account any overlapping sibling components
  16115. which might be in the way - for that, see reallyContains()
  16116. @see hitTest, reallyContains, getComponentAt
  16117. */
  16118. virtual bool contains (int x, int y);
  16119. /** Returns true if a given point lies in this component, taking any overlapping
  16120. siblings into account.
  16121. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16122. @param y the y co-ordinate to test, relative to this component's top edge.
  16123. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  16124. component, this determines the value that will
  16125. be returned.
  16126. @see contains, getComponentAt
  16127. */
  16128. bool reallyContains (int x, int y,
  16129. const bool returnTrueIfWithinAChild);
  16130. /** Returns the component at a certain point within this one.
  16131. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16132. @param y the y co-ordinate to test, relative to this component's top edge.
  16133. @returns the component that is at this position - which may be 0, this component,
  16134. or one of its children. Note that overlapping siblings that might actually
  16135. be in the way are not taken into account by this method - to account for these,
  16136. instead call getComponentAt on the top-level parent of this component.
  16137. @see hitTest, contains, reallyContains
  16138. */
  16139. Component* getComponentAt (const int x, const int y);
  16140. /** Marks the whole component as needing to be redrawn.
  16141. Calling this will not do any repainting immediately, but will mark the component
  16142. as 'dirty'. At some point in the near future the operating system will send a paint
  16143. message, which will redraw all the dirty regions of all components.
  16144. There's no guarantee about how soon after calling repaint() the redraw will actually
  16145. happen, and other queued events may be delivered before a redraw is done.
  16146. If the setBufferedToImage() method has been used to cause this component
  16147. to use a buffer, the repaint() call will invalidate the component's buffer.
  16148. To redraw just a subsection of the component rather than the whole thing,
  16149. use the repaint (int, int, int, int) method.
  16150. @see paint
  16151. */
  16152. void repaint() throw();
  16153. /** Marks a subsection of this component as needing to be redrawn.
  16154. Calling this will not do any repainting immediately, but will mark the given region
  16155. of the component as 'dirty'. At some point in the near future the operating system
  16156. will send a paint message, which will redraw all the dirty regions of all components.
  16157. There's no guarantee about how soon after calling repaint() the redraw will actually
  16158. happen, and other queued events may be delivered before a redraw is done.
  16159. The region that is passed in will be clipped to keep it within the bounds of this
  16160. component.
  16161. @see repaint()
  16162. */
  16163. void repaint (const int x, const int y,
  16164. const int width, const int height) throw();
  16165. /** Makes the component use an internal buffer to optimise its redrawing.
  16166. Setting this flag to true will cause the component to allocate an
  16167. internal buffer into which it paints itself, so that when asked to
  16168. redraw itself, it can use this buffer rather than actually calling the
  16169. paint() method.
  16170. The buffer is kept until the repaint() method is called directly on
  16171. this component (or until it is resized), when the image is invalidated
  16172. and then redrawn the next time the component is painted.
  16173. Note that only the drawing that happens within the component's paint()
  16174. method is drawn into the buffer, it's child components are not buffered, and
  16175. nor is the paintOverChildren() method.
  16176. @see repaint, paint, createComponentSnapshot
  16177. */
  16178. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16179. /** Generates a snapshot of part of this component.
  16180. This will return a new Image, the size of the rectangle specified,
  16181. containing a snapshot of the specified area of the component and all
  16182. its children.
  16183. The image may or may not have an alpha-channel, depending on whether the
  16184. image is opaque or not.
  16185. If the clipImageToComponentBounds parameter is true and the area is greater than
  16186. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16187. then parts of the component beyond its bounds can be drawn.
  16188. The caller is responsible for deleting the image that is returned.
  16189. @see paintEntireComponent
  16190. */
  16191. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16192. const bool clipImageToComponentBounds = true);
  16193. /** Draws this component and all its subcomponents onto the specified graphics
  16194. context.
  16195. You should very rarely have to use this method, it's simply there in case you need
  16196. to draw a component with a custom graphics context for some reason, e.g. for
  16197. creating a snapshot of the component.
  16198. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16199. on its children in order to render the entire tree.
  16200. The graphics context may be left in an undefined state after this method returns,
  16201. so you may need to reset it if you're going to use it again.
  16202. */
  16203. void paintEntireComponent (Graphics& context);
  16204. /** Adds an effect filter to alter the component's appearance.
  16205. When a component has an effect filter set, then this is applied to the
  16206. results of its paint() method. There are a few preset effects, such as
  16207. a drop-shadow or glow, but they can be user-defined as well.
  16208. The effect that is passed in will not be deleted by the component - the
  16209. caller must take care of deleting it.
  16210. To remove an effect from a component, pass a null pointer in as the parameter.
  16211. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16212. */
  16213. void setComponentEffect (ImageEffectFilter* const newEffect);
  16214. /** Returns the current component effect.
  16215. @see setComponentEffect
  16216. */
  16217. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16218. /** Finds the appropriate look-and-feel to use for this component.
  16219. If the component hasn't had a look-and-feel explicitly set, this will
  16220. return the parent's look-and-feel, or just the default one if there's no
  16221. parent.
  16222. @see setLookAndFeel, lookAndFeelChanged
  16223. */
  16224. LookAndFeel& getLookAndFeel() const throw();
  16225. /** Sets the look and feel to use for this component.
  16226. This will also change the look and feel for any child components that haven't
  16227. had their look set explicitly.
  16228. The object passed in will not be deleted by the component, so it's the caller's
  16229. responsibility to manage it. It may be used at any time until this component
  16230. has been deleted.
  16231. Calling this method will also invoke the sendLookAndFeelChange() method.
  16232. @see getLookAndFeel, lookAndFeelChanged
  16233. */
  16234. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16235. /** Called to let the component react to a change in the look-and-feel setting.
  16236. When the look-and-feel is changed for a component, this will be called in
  16237. all its child components, recursively.
  16238. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16239. an application uses a LookAndFeel class that might have changed internally.
  16240. @see sendLookAndFeelChange, getLookAndFeel
  16241. */
  16242. virtual void lookAndFeelChanged();
  16243. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16244. This will recurse through the children and their children, calling lookAndFeelChanged()
  16245. on them all.
  16246. @see lookAndFeelChanged
  16247. */
  16248. void sendLookAndFeelChange();
  16249. /** Indicates whether any parts of the component might be transparent.
  16250. Components that always paint all of their contents with solid colour and
  16251. thus completely cover any components behind them should use this method
  16252. to tell the repaint system that they are opaque.
  16253. This information is used to optimise drawing, because it means that
  16254. objects underneath opaque windows don't need to be painted.
  16255. By default, components are considered transparent, unless this is used to
  16256. make it otherwise.
  16257. @see isOpaque, getVisibleArea
  16258. */
  16259. void setOpaque (const bool shouldBeOpaque) throw();
  16260. /** Returns true if no parts of this component are transparent.
  16261. @returns the value that was set by setOpaque, (the default being false)
  16262. @see setOpaque
  16263. */
  16264. bool isOpaque() const throw();
  16265. /** Indicates whether the component should be brought to the front when clicked.
  16266. Setting this flag to true will cause the component to be brought to the front
  16267. when the mouse is clicked somewhere inside it or its child components.
  16268. Note that a top-level desktop window might still be brought to the front by the
  16269. operating system when it's clicked, depending on how the OS works.
  16270. By default this is set to false.
  16271. @see setMouseClickGrabsKeyboardFocus
  16272. */
  16273. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16274. /** Indicates whether the component should be brought to the front when clicked-on.
  16275. @see setBroughtToFrontOnMouseClick
  16276. */
  16277. bool isBroughtToFrontOnMouseClick() const throw();
  16278. // Keyboard focus methods
  16279. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16280. By default components aren't actually interested in gaining the
  16281. focus, but this method can be used to turn this on.
  16282. See the grabKeyboardFocus() method for details about the way a component
  16283. is chosen to receive the focus.
  16284. @see grabKeyboardFocus, getWantsKeyboardFocus
  16285. */
  16286. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16287. /** Returns true if the component is interested in getting keyboard focus.
  16288. This returns the flag set by setWantsKeyboardFocus(). The default
  16289. setting is false.
  16290. @see setWantsKeyboardFocus
  16291. */
  16292. bool getWantsKeyboardFocus() const throw();
  16293. /** Chooses whether a click on this component automatically grabs the focus.
  16294. By default this is set to true, but you might want a component which can
  16295. be focused, but where you don't want the user to be able to affect it directly
  16296. by clicking.
  16297. */
  16298. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16299. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16300. See setMouseClickGrabsKeyboardFocus() for more info.
  16301. */
  16302. bool getMouseClickGrabsKeyboardFocus() const throw();
  16303. /** Tries to give keyboard focus to this component.
  16304. When the user clicks on a component or its grabKeyboardFocus()
  16305. method is called, the following procedure is used to work out which
  16306. component should get it:
  16307. - if the component that was clicked on actually wants focus (as indicated
  16308. by calling getWantsKeyboardFocus), it gets it.
  16309. - if the component itself doesn't want focus, it will try to pass it
  16310. on to whichever of its children is the default component, as determined by
  16311. KeyboardFocusTraverser::getDefaultComponent()
  16312. - if none of its children want focus at all, it will pass it up to its
  16313. parent instead, unless it's a top-level component without a parent,
  16314. in which case it just takes the focus itself.
  16315. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16316. getCurrentlyFocusedComponent, focusGained, focusLost,
  16317. keyPressed, keyStateChanged
  16318. */
  16319. void grabKeyboardFocus();
  16320. /** Returns true if this component currently has the keyboard focus.
  16321. @param trueIfChildIsFocused if this is true, then the method returns true if
  16322. either this component or any of its children (recursively)
  16323. have the focus. If false, the method only returns true if
  16324. this component has the focus.
  16325. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16326. focusGained, focusLost
  16327. */
  16328. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16329. /** Returns the component that currently has the keyboard focus.
  16330. @returns the focused component, or null if nothing is focused.
  16331. */
  16332. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16333. /** Tries to move the keyboard focus to one of this component's siblings.
  16334. This will try to move focus to either the next or previous component. (This
  16335. is the method that is used when shifting focus by pressing the tab key).
  16336. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16337. @param moveToNext if true, the focus will move forwards; if false, it will
  16338. move backwards
  16339. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16340. */
  16341. void moveKeyboardFocusToSibling (const bool moveToNext);
  16342. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16343. which focus should be passed from this component.
  16344. The default implementation of this method will return a default
  16345. KeyboardFocusTraverser if this component is a focus container (as determined
  16346. by the setFocusContainer() method). If the component isn't a focus
  16347. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16348. If you overrride this to return a custom KeyboardFocusTraverser, then
  16349. this component and all its sub-components will use the new object to
  16350. make their focusing decisions.
  16351. The method should return a new object, which the caller is required to
  16352. delete when no longer needed.
  16353. */
  16354. virtual KeyboardFocusTraverser* createFocusTraverser();
  16355. /** Returns the focus order of this component, if one has been specified.
  16356. By default components don't have a focus order - in that case, this
  16357. will return 0. Lower numbers indicate that the component will be
  16358. earlier in the focus traversal order.
  16359. To change the order, call setExplicitFocusOrder().
  16360. The focus order may be used by the KeyboardFocusTraverser class as part of
  16361. its algorithm for deciding the order in which components should be traversed.
  16362. See the KeyboardFocusTraverser class for more details on this.
  16363. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16364. */
  16365. int getExplicitFocusOrder() const throw();
  16366. /** Sets the index used in determining the order in which focusable components
  16367. should be traversed.
  16368. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16369. that traversal should use other factors, like the component's position.
  16370. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16371. */
  16372. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16373. /** Indicates whether this component is a parent for components that can have
  16374. their focus traversed.
  16375. This flag is used by the default implementation of the createFocusTraverser()
  16376. method, which uses the flag to find the first parent component (of the currently
  16377. focused one) which wants to be a focus container.
  16378. So using this method to set the flag to 'true' causes this component to
  16379. act as the top level within which focus is passed around.
  16380. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16381. */
  16382. void setFocusContainer (const bool isFocusContainer) throw();
  16383. /** Returns true if this component has been marked as a focus container.
  16384. See setFocusContainer() for more details.
  16385. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16386. */
  16387. bool isFocusContainer() const throw();
  16388. /** Returns true if the component (and all its parents) are enabled.
  16389. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16390. what difference this makes to the component depends on the type. E.g. buttons
  16391. and sliders will choose to draw themselves differently, etc.
  16392. Note that if one of this component's parents is disabled, this will always
  16393. return false, even if this component itself is enabled.
  16394. @see setEnabled, enablementChanged
  16395. */
  16396. bool isEnabled() const throw();
  16397. /** Enables or disables this component.
  16398. Disabling a component will also cause all of its child components to become
  16399. disabled.
  16400. Similarly, enabling a component which is inside a disabled parent
  16401. component won't make any difference until the parent is re-enabled.
  16402. @see isEnabled, enablementChanged
  16403. */
  16404. void setEnabled (const bool shouldBeEnabled);
  16405. /** Callback to indicate that this component has been enabled or disabled.
  16406. This can be triggered by one of the component's parent components
  16407. being enabled or disabled, as well as changes to the component itself.
  16408. The default implementation of this method does nothing; your class may
  16409. wish to repaint itself or something when this happens.
  16410. @see setEnabled, isEnabled
  16411. */
  16412. virtual void enablementChanged();
  16413. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16414. Note that the cursor set by this method can be overridden by the getMouseCursor
  16415. method.
  16416. @see MouseCursor
  16417. */
  16418. void setMouseCursor (const MouseCursor& cursorType) throw();
  16419. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16420. The default implementation will return the cursor that was set by setCursor()
  16421. but can be overridden for more specialised purposes, e.g. returning different
  16422. cursors depending on the mouse position.
  16423. @see MouseCursor
  16424. */
  16425. virtual const MouseCursor getMouseCursor();
  16426. /** Forces the current mouse cursor to be updated.
  16427. If you're overriding the getMouseCursor() method to control which cursor is
  16428. displayed, then this will only be checked each time the user moves the mouse. So
  16429. if you want to force the system to check that the cursor being displayed is
  16430. up-to-date (even if the mouse is just sitting there), call this method.
  16431. This isn't needed if you're only using setMouseCursor().
  16432. */
  16433. void updateMouseCursor() const throw();
  16434. /** Components can override this method to draw their content.
  16435. The paint() method gets called when a region of a component needs redrawing,
  16436. either because the component's repaint() method has been called, or because
  16437. something has happened on the screen that means a section of a window needs
  16438. to be redrawn.
  16439. Any child components will draw themselves over whatever this method draws. If
  16440. you need to paint over the top of your child components, you can also implement
  16441. the paintOverChildren() method to do this.
  16442. If you want to cause a component to redraw itself, this is done asynchronously -
  16443. calling the repaint() method marks a region of the component as "dirty", and the
  16444. paint() method will automatically be called sometime later, by the message thread,
  16445. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16446. you never redraw something synchronously.
  16447. You should never need to call this method directly - to take a snapshot of the
  16448. component you could use createComponentSnapshot() or paintEntireComponent().
  16449. @param g the graphics context that must be used to do the drawing operations.
  16450. @see repaint, paintOverChildren, Graphics
  16451. */
  16452. virtual void paint (Graphics& g);
  16453. /** Components can override this method to draw over the top of their children.
  16454. For most drawing operations, it's better to use the normal paint() method,
  16455. but if you need to overlay something on top of the children, this can be
  16456. used.
  16457. @see paint, Graphics
  16458. */
  16459. virtual void paintOverChildren (Graphics& g);
  16460. /** Called when the mouse moves inside this component.
  16461. If the mouse button isn't pressed and the mouse moves over a component,
  16462. this will be called to let the component react to this.
  16463. A component will always get a mouseEnter callback before a mouseMove.
  16464. @param e details about the position and status of the mouse event
  16465. @see mouseEnter, mouseExit, mouseDrag, contains
  16466. */
  16467. virtual void mouseMove (const MouseEvent& e);
  16468. /** Called when the mouse first enters this component.
  16469. If the mouse button isn't pressed and the mouse moves into a component,
  16470. this will be called to let the component react to this.
  16471. When the mouse button is pressed and held down while being moved in
  16472. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16473. mouseDrag messages are sent to the component that the mouse was originally
  16474. clicked on, until the button is released.
  16475. If you're writing a component that needs to repaint itself when the mouse
  16476. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16477. method.
  16478. @param e details about the position and status of the mouse event
  16479. @see mouseExit, mouseDrag, mouseMove, contains
  16480. */
  16481. virtual void mouseEnter (const MouseEvent& e);
  16482. /** Called when the mouse moves out of this component.
  16483. This will be called when the mouse moves off the edge of this
  16484. component.
  16485. If the mouse button was pressed, and it was then dragged off the
  16486. edge of the component and released, then this callback will happen
  16487. when the button is released, after the mouseUp callback.
  16488. If you're writing a component that needs to repaint itself when the mouse
  16489. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16490. method.
  16491. @param e details about the position and status of the mouse event
  16492. @see mouseEnter, mouseDrag, mouseMove, contains
  16493. */
  16494. virtual void mouseExit (const MouseEvent& e);
  16495. /** Called when a mouse button is pressed while it's over this component.
  16496. The MouseEvent object passed in contains lots of methods for finding out
  16497. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16498. were held down at the time.
  16499. Once a button is held down, the mouseDrag method will be called when the
  16500. mouse moves, until the button is released.
  16501. @param e details about the position and status of the mouse event
  16502. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16503. */
  16504. virtual void mouseDown (const MouseEvent& e);
  16505. /** Called when the mouse is moved while a button is held down.
  16506. When a mouse button is pressed inside a component, that component
  16507. receives mouseDrag callbacks each time the mouse moves, even if the
  16508. mouse strays outside the component's bounds.
  16509. If you want to be able to drag things off the edge of a component
  16510. and have the component scroll when you get to the edges, the
  16511. beginDragAutoRepeat() method might be useful.
  16512. @param e details about the position and status of the mouse event
  16513. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16514. */
  16515. virtual void mouseDrag (const MouseEvent& e);
  16516. /** Called when a mouse button is released.
  16517. A mouseUp callback is sent to the component in which a button was pressed
  16518. even if the mouse is actually over a different component when the
  16519. button is released.
  16520. The MouseEvent object passed in contains lots of methods for finding out
  16521. which buttons were down just before they were released.
  16522. @param e details about the position and status of the mouse event
  16523. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16524. */
  16525. virtual void mouseUp (const MouseEvent& e);
  16526. /** Called when a mouse button has been double-clicked in this component.
  16527. The MouseEvent object passed in contains lots of methods for finding out
  16528. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16529. were held down at the time.
  16530. For altering the time limit used to detect double-clicks,
  16531. see MouseEvent::setDoubleClickTimeout.
  16532. @param e details about the position and status of the mouse event
  16533. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16534. MouseEvent::getDoubleClickTimeout
  16535. */
  16536. virtual void mouseDoubleClick (const MouseEvent& e);
  16537. /** Called when the mouse-wheel is moved.
  16538. This callback is sent to the component that the mouse is over when the
  16539. wheel is moved.
  16540. If not overridden, the component will forward this message to its parent, so
  16541. that parent components can collect mouse-wheel messages that happen to
  16542. child components which aren't interested in them.
  16543. @param e details about the position and status of the mouse event
  16544. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16545. value means the wheel has been pushed to the right, negative means it
  16546. was pushed to the left
  16547. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16548. value means the wheel has been pushed upwards, negative means it
  16549. was pushed downwards
  16550. */
  16551. virtual void mouseWheelMove (const MouseEvent& e,
  16552. float wheelIncrementX,
  16553. float wheelIncrementY);
  16554. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16555. next mouse-drag operation.
  16556. This allows you to make sure that mouseDrag() events sent continuously, even
  16557. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16558. components when the mouse is near an edge.
  16559. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16560. minimum interval between consecutive mouse drag callbacks. The callbacks
  16561. will continue until the mouse is released, and then the interval will be reset,
  16562. so you need to make sure it's called every time you begin a drag event. If it
  16563. is called when the mouse isn't actually being pressed, it will apply to the next
  16564. mouse-drag operation that happens.
  16565. Passing an interval of 0 or less will cancel the auto-repeat.
  16566. @see mouseDrag
  16567. */
  16568. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16569. /** Causes automatic repaints when the mouse enters or exits this component.
  16570. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16571. on the component, it will trigger a repaint.
  16572. This is handy for things like buttons that need to draw themselves differently when
  16573. the mouse moves over them, and it avoids having to override all the different mouse
  16574. callbacks and call repaint().
  16575. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16576. */
  16577. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16578. /** Registers a listener to be told when mouse events occur in this component.
  16579. If you need to get informed about mouse events in a component but can't or
  16580. don't want to override its methods, you can attach any number of listeners
  16581. to the component, and these will get told about the events in addition to
  16582. the component's own callbacks being called.
  16583. Note that a MouseListener can also be attached to more than one component.
  16584. @param newListener the listener to register
  16585. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16586. for events that happen to any child component
  16587. within this component, including deeply-nested
  16588. child components. If false, it will only be
  16589. told about events that this component handles.
  16590. @see MouseListener, removeMouseListener
  16591. */
  16592. void addMouseListener (MouseListener* const newListener,
  16593. const bool wantsEventsForAllNestedChildComponents) throw();
  16594. /** Deregisters a mouse listener.
  16595. @see addMouseListener, MouseListener
  16596. */
  16597. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16598. /** Adds a listener that wants to hear about keypresses that this component receives.
  16599. The listeners that are registered with a component are called by its keyPressed() or
  16600. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16601. If you add an object as a key listener, be careful to remove it when the object
  16602. is deleted, or the component will be left with a dangling pointer.
  16603. @see keyPressed, keyStateChanged, removeKeyListener
  16604. */
  16605. void addKeyListener (KeyListener* const newListener) throw();
  16606. /** Removes a previously-registered key listener.
  16607. @see addKeyListener
  16608. */
  16609. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16610. /** Called when a key is pressed.
  16611. When a key is pressed, the component that has the keyboard focus will have this
  16612. method called. Remember that a component will only be given the focus if its
  16613. setWantsKeyboardFocus() method has been used to enable this.
  16614. If your implementation returns true, the event will be consumed and not passed
  16615. on to any other listeners. If it returns false, the key will be passed to any
  16616. KeyListeners that have been registered with this component. As soon as one of these
  16617. returns true, the process will stop, but if they all return false, the event will
  16618. be passed upwards to this component's parent, and so on.
  16619. The default implementation of this method does nothing and returns false.
  16620. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16621. */
  16622. virtual bool keyPressed (const KeyPress& key);
  16623. /** Called when a key is pressed or released.
  16624. Whenever a key on the keyboard is pressed or released (including modifier keys
  16625. like shift and ctrl), this method will be called on the component that currently
  16626. has the keyboard focus. Remember that a component will only be given the focus if
  16627. its setWantsKeyboardFocus() method has been used to enable this.
  16628. If your implementation returns true, the event will be consumed and not passed
  16629. on to any other listeners. If it returns false, then any KeyListeners that have
  16630. been registered with this component will have their keyStateChanged methods called.
  16631. As soon as one of these returns true, the process will stop, but if they all return
  16632. false, the event will be passed upwards to this component's parent, and so on.
  16633. The default implementation of this method does nothing and returns false.
  16634. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16635. method.
  16636. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16637. */
  16638. virtual bool keyStateChanged();
  16639. /** Called when a modifier key is pressed or released.
  16640. Whenever the shift, control, alt or command keys are pressed or released,
  16641. this method will be called on the component that currently has the keyboard focus.
  16642. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16643. method has been used to enable this.
  16644. The default implementation of this method actually calls its parent's modifierKeysChanged
  16645. method, so that focused components which aren't interested in this will give their
  16646. parents a chance to act on the event instead.
  16647. @see keyStateChanged, ModifierKeys
  16648. */
  16649. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16650. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16651. enum FocusChangeType
  16652. {
  16653. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16654. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16655. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16656. };
  16657. /** Called to indicate that this component has just acquired the keyboard focus.
  16658. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16659. */
  16660. virtual void focusGained (FocusChangeType cause);
  16661. /** Called to indicate that this component has just lost the keyboard focus.
  16662. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16663. */
  16664. virtual void focusLost (FocusChangeType cause);
  16665. /** Called to indicate that one of this component's children has been focused or unfocused.
  16666. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16667. changed. It happens when focus moves from one of this component's children (at any depth)
  16668. to a component that isn't contained in this one, (or vice-versa).
  16669. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16670. */
  16671. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16672. /** Returns true if the mouse is currently over this component.
  16673. If the mouse isn't over the component, this will return false, even if the
  16674. mouse is currently being dragged - so you can use this in your mouseDrag
  16675. method to find out whether it's really over the component or not.
  16676. Note that when the mouse button is being held down, then the only component
  16677. for which this method will return true is the one that was originally
  16678. clicked on.
  16679. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16680. */
  16681. bool isMouseOver() const throw();
  16682. /** Returns true if the mouse button is currently held down in this component.
  16683. Note that this is a test to see whether the mouse is being pressed in this
  16684. component, so it'll return false if called on component A when the mouse
  16685. is actually being dragged in component B.
  16686. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16687. */
  16688. bool isMouseButtonDown() const throw();
  16689. /** True if the mouse is over this component, or if it's being dragged in this component.
  16690. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16691. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16692. */
  16693. bool isMouseOverOrDragging() const throw();
  16694. /** Returns true if a mouse button is currently down.
  16695. Unlike isMouseButtonDown, this will test the current state of the
  16696. buttons without regard to which component (if any) it has been
  16697. pressed in.
  16698. @see isMouseButtonDown, ModifierKeys
  16699. */
  16700. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16701. /** Returns the mouse's current position, relative to this component.
  16702. The co-ordinates are relative to the component's top-left corner.
  16703. */
  16704. void getMouseXYRelative (int& x, int& y) const throw();
  16705. /** Returns the component that's currently underneath the mouse.
  16706. @returns the component or 0 if there isn't one.
  16707. @see contains, getComponentAt
  16708. */
  16709. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16710. /** Allows the mouse to move beyond the edges of the screen.
  16711. Calling this method when the mouse button is currently pressed inside this component
  16712. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16713. the edges of the screen.
  16714. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16715. can be used for things like custom slider controls or dragging objects around, where
  16716. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16717. The unbounded mode is automatically turned off when the mouse button is released, or
  16718. it can be turned off explicitly by calling this method again.
  16719. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16720. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16721. hidden; if true, it will only be hidden when it
  16722. is moved beyond the edge of the screen
  16723. */
  16724. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16725. bool keepCursorVisibleUntilOffscreen = false) throw();
  16726. /** Called when this component's size has been changed.
  16727. A component can implement this method to do things such as laying out its
  16728. child components when its width or height changes.
  16729. The method is called synchronously as a result of the setBounds or setSize
  16730. methods, so repeatedly changing a components size will repeatedly call its
  16731. resized method (unlike things like repainting, where multiple calls to repaint
  16732. are coalesced together).
  16733. If the component is a top-level window on the desktop, its size could also
  16734. be changed by operating-system factors beyond the application's control.
  16735. @see moved, setSize
  16736. */
  16737. virtual void resized();
  16738. /** Called when this component's position has been changed.
  16739. This is called when the position relative to its parent changes, not when
  16740. its absolute position on the screen changes (so it won't be called for
  16741. all child components when a parent component is moved).
  16742. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16743. or any of the other repositioning methods, and like resized(), it will be
  16744. called each time those methods are called.
  16745. If the component is a top-level window on the desktop, its position could also
  16746. be changed by operating-system factors beyond the application's control.
  16747. @see resized, setBounds
  16748. */
  16749. virtual void moved();
  16750. /** Called when one of this component's children is moved or resized.
  16751. If the parent wants to know about changes to its immediate children (not
  16752. to children of its children), this is the method to override.
  16753. @see moved, resized, parentSizeChanged
  16754. */
  16755. virtual void childBoundsChanged (Component* child);
  16756. /** Called when this component's immediate parent has been resized.
  16757. If the component is a top-level window, this indicates that the screen size
  16758. has changed.
  16759. @see childBoundsChanged, moved, resized
  16760. */
  16761. virtual void parentSizeChanged();
  16762. /** Called when this component has been moved to the front of its siblings.
  16763. The component may have been brought to the front by the toFront() method, or
  16764. by the operating system if it's a top-level window.
  16765. @see toFront
  16766. */
  16767. virtual void broughtToFront();
  16768. /** Adds a listener to be told about changes to the component hierarchy or position.
  16769. Component listeners get called when this component's size, position or children
  16770. change - see the ComponentListener class for more details.
  16771. @param newListener the listener to register - if this is already registered, it
  16772. will be ignored.
  16773. @see ComponentListener, removeComponentListener
  16774. */
  16775. void addComponentListener (ComponentListener* const newListener) throw();
  16776. /** Removes a component listener.
  16777. @see addComponentListener
  16778. */
  16779. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16780. /** Dispatches a numbered message to this component.
  16781. This is a quick and cheap way of allowing simple asynchronous messages to
  16782. be sent to components. It's also safe, because if the component that you
  16783. send the message to is a null or dangling pointer, this won't cause an error.
  16784. The command ID is later delivered to the component's handleCommandMessage() method by
  16785. the application's message queue.
  16786. @see handleCommandMessage
  16787. */
  16788. void postCommandMessage (const int commandId) throw();
  16789. /** Called to handle a command that was sent by postCommandMessage().
  16790. This is called by the message thread when a command message arrives, and
  16791. the component can override this method to process it in any way it needs to.
  16792. @see postCommandMessage
  16793. */
  16794. virtual void handleCommandMessage (int commandId);
  16795. /** Runs a component modally, waiting until the loop terminates.
  16796. This method first makes the component visible, brings it to the front and
  16797. gives it the keyboard focus.
  16798. It then runs a loop, dispatching messages from the system message queue, but
  16799. blocking all mouse or keyboard messages from reaching any components other
  16800. than this one and its children.
  16801. This loop continues until the component's exitModalState() method is called (or
  16802. the component is deleted), and then this method returns, returning the value
  16803. passed into exitModalState().
  16804. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16805. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16806. */
  16807. int runModalLoop();
  16808. /** Puts the component into a modal state.
  16809. This makes the component modal, so that messages are blocked from reaching
  16810. any components other than this one and its children, but unlike runModalLoop(),
  16811. this method returns immediately.
  16812. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16813. get the focus, which is usually what you'll want it to do. If not, it will leave
  16814. the focus unchanged.
  16815. @see exitModalState, runModalLoop
  16816. */
  16817. void enterModalState (const bool takeKeyboardFocus = true);
  16818. /** Ends a component's modal state.
  16819. If this component is currently modal, this will turn of its modalness, and return
  16820. a value to the runModalLoop() method that might have be running its modal loop.
  16821. @see runModalLoop, enterModalState, isCurrentlyModal
  16822. */
  16823. void exitModalState (const int returnValue);
  16824. /** Returns true if this component is the modal one.
  16825. It's possible to have nested modal components, e.g. a pop-up dialog box
  16826. that launches another pop-up, but this will only return true for
  16827. the one at the top of the stack.
  16828. @see getCurrentlyModalComponent
  16829. */
  16830. bool isCurrentlyModal() const throw();
  16831. /** Returns the number of components that are currently in a modal state.
  16832. @see getCurrentlyModalComponent
  16833. */
  16834. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  16835. /** Returns one of the components that are currently modal.
  16836. The index specifies which of the possible modal components to return. The order
  16837. of the components in this list is the reverse of the order in which they became
  16838. modal - so the component at index 0 is always the active component, and the others
  16839. are progressively earlier ones that are themselves now blocked by later ones.
  16840. @returns the modal component, or null if no components are modal (or if the
  16841. index is out of range)
  16842. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  16843. */
  16844. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  16845. /** Checks whether there's a modal component somewhere that's stopping this one
  16846. from receiving messages.
  16847. If there is a modal component, its canModalEventBeSentToComponent() method
  16848. will be called to see if it will still allow this component to receive events.
  16849. @see runModalLoop, getCurrentlyModalComponent
  16850. */
  16851. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16852. /** When a component is modal, this callback allows it to choose which other
  16853. components can still receive events.
  16854. When a modal component is active and the user clicks on a non-modal component,
  16855. this method is called on the modal component, and if it returns true, the
  16856. event is allowed to reach its target. If it returns false, the event is blocked
  16857. and the inputAttemptWhenModal() callback is made.
  16858. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16859. implementation just returns false in all cases.
  16860. */
  16861. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16862. /** Called when the user tries to click on a component that is blocked by another
  16863. modal component.
  16864. When a component is modal and the user clicks on one of the other components,
  16865. the modal component will receive this callback.
  16866. The default implementation of this method will play a beep, and bring the currently
  16867. modal component to the front, but it can be overridden to do other tasks.
  16868. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16869. */
  16870. virtual void inputAttemptWhenModal();
  16871. /** Returns one of the component's properties as a string.
  16872. @param keyName the name of the property to retrieve
  16873. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16874. properties, then it will check whether the parent component has
  16875. the key.
  16876. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16877. */
  16878. const String getComponentProperty (const String& keyName,
  16879. const bool useParentComponentIfNotFound,
  16880. const String& defaultReturnValue = String::empty) const throw();
  16881. /** Returns one of the properties as an integer.
  16882. @param keyName the name of the property to retrieve
  16883. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16884. properties, then it will check whether the parent component has
  16885. the key.
  16886. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16887. */
  16888. int getComponentPropertyInt (const String& keyName,
  16889. const bool useParentComponentIfNotFound,
  16890. const int defaultReturnValue = 0) const throw();
  16891. /** Returns one of the properties as an double.
  16892. @param keyName the name of the property to retrieve
  16893. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16894. properties, then it will check whether the parent component has
  16895. the key.
  16896. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16897. */
  16898. double getComponentPropertyDouble (const String& keyName,
  16899. const bool useParentComponentIfNotFound,
  16900. const double defaultReturnValue = 0.0) const throw();
  16901. /** Returns one of the properties as an boolean.
  16902. The result will be true if the string found for this key name can be parsed as a non-zero
  16903. integer.
  16904. @param keyName the name of the property to retrieve
  16905. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16906. properties, then it will check whether the parent component has
  16907. the key.
  16908. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16909. */
  16910. bool getComponentPropertyBool (const String& keyName,
  16911. const bool useParentComponentIfNotFound,
  16912. const bool defaultReturnValue = false) const throw();
  16913. /** Returns one of the properties as an colour.
  16914. @param keyName the name of the property to retrieve
  16915. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16916. properties, then it will check whether the parent component has
  16917. the key.
  16918. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16919. */
  16920. const Colour getComponentPropertyColour (const String& keyName,
  16921. const bool useParentComponentIfNotFound,
  16922. const Colour& defaultReturnValue = Colours::black) const throw();
  16923. /** Sets a named property as a string.
  16924. @param keyName the name of the property to set. (This mustn't be an empty string)
  16925. @param value the new value to set it to
  16926. @see removeComponentProperty
  16927. */
  16928. void setComponentProperty (const String& keyName, const String& value) throw();
  16929. /** Sets a named property to an integer.
  16930. @param keyName the name of the property to set. (This mustn't be an empty string)
  16931. @param value the new value to set it to
  16932. @see removeComponentProperty
  16933. */
  16934. void setComponentProperty (const String& keyName, const int value) throw();
  16935. /** Sets a named property to a double.
  16936. @param keyName the name of the property to set. (This mustn't be an empty string)
  16937. @param value the new value to set it to
  16938. @see removeComponentProperty
  16939. */
  16940. void setComponentProperty (const String& keyName, const double value) throw();
  16941. /** Sets a named property to a boolean.
  16942. @param keyName the name of the property to set. (This mustn't be an empty string)
  16943. @param value the new value to set it to
  16944. @see removeComponentProperty
  16945. */
  16946. void setComponentProperty (const String& keyName, const bool value) throw();
  16947. /** Sets a named property to a colour.
  16948. @param keyName the name of the property to set. (This mustn't be an empty string)
  16949. @param newColour the new colour to set it to
  16950. @see removeComponentProperty
  16951. */
  16952. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16953. /** Deletes a named component property.
  16954. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16955. @see setComponentProperty, getComponentProperty
  16956. */
  16957. void removeComponentProperty (const String& keyName) throw();
  16958. /** Returns the complete set of properties that have been set for this component.
  16959. If no properties have been set, this will return a null pointer.
  16960. @see getComponentProperty, setComponentProperty
  16961. */
  16962. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16963. /** Looks for a colour that has been registered with the given colour ID number.
  16964. If a colour has been set for this ID number using setColour(), then it is
  16965. returned. If none has been set, the method will try calling the component's
  16966. LookAndFeel class's findColour() method. If none has been registered with the
  16967. look-and-feel either, it will just return black.
  16968. The colour IDs for various purposes are stored as enums in the components that
  16969. they are relevent to - for an example, see Slider::ColourIds,
  16970. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16971. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16972. */
  16973. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16974. /** Registers a colour to be used for a particular purpose.
  16975. Changing a colour will cause a synchronous callback to the colourChanged()
  16976. method, which your component can override if it needs to do something when
  16977. colours are altered.
  16978. For more details about colour IDs, see the comments for findColour().
  16979. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16980. */
  16981. void setColour (const int colourId, const Colour& colour);
  16982. /** If a colour has been set with setColour(), this will remove it.
  16983. This allows you to make a colour revert to its default state.
  16984. */
  16985. void removeColour (const int colourId);
  16986. /** Returns true if the specified colour ID has been explicitly set for this
  16987. component using the setColour() method.
  16988. */
  16989. bool isColourSpecified (const int colourId) const throw();
  16990. /** This looks for any colours that have been specified for this component,
  16991. and copies them to the specified target component.
  16992. */
  16993. void copyAllExplicitColoursTo (Component& target) const throw();
  16994. /** This method is called when a colour is changed by the setColour() method.
  16995. @see setColour, findColour
  16996. */
  16997. virtual void colourChanged();
  16998. /** Returns the underlying native window handle for this component.
  16999. This is platform-dependent and strictly for power-users only!
  17000. */
  17001. void* getWindowHandle() const throw();
  17002. /** When created, each component is given a number to uniquely identify it.
  17003. The number is incremented each time a new component is created, so it's a more
  17004. unique way of identifying a component than using its memory location (which
  17005. may be reused after the component is deleted, of course).
  17006. */
  17007. uint32 getComponentUID() const throw() { return componentUID; }
  17008. juce_UseDebuggingNewOperator
  17009. private:
  17010. friend class ComponentPeer;
  17011. friend class InternalDragRepeater;
  17012. static Component* currentlyFocusedComponent;
  17013. static Component* componentUnderMouse;
  17014. String componentName_;
  17015. Component* parentComponent_;
  17016. uint32 componentUID;
  17017. Rectangle bounds_;
  17018. unsigned short numDeepMouseListeners;
  17019. Array <Component*> childComponentList_;
  17020. LookAndFeel* lookAndFeel_;
  17021. MouseCursor cursor_;
  17022. ImageEffectFilter* effect_;
  17023. Image* bufferedImage_;
  17024. VoidArray* mouseListeners_;
  17025. VoidArray* keyListeners_;
  17026. VoidArray* componentListeners_;
  17027. PropertySet* propertySet_;
  17028. struct ComponentFlags
  17029. {
  17030. bool hasHeavyweightPeerFlag : 1;
  17031. bool visibleFlag : 1;
  17032. bool opaqueFlag : 1;
  17033. bool ignoresMouseClicksFlag : 1;
  17034. bool allowChildMouseClicksFlag : 1;
  17035. bool wantsFocusFlag : 1;
  17036. bool isFocusContainerFlag : 1;
  17037. bool dontFocusOnMouseClickFlag : 1;
  17038. bool alwaysOnTopFlag : 1;
  17039. bool bufferToImageFlag : 1;
  17040. bool bringToFrontOnClickFlag : 1;
  17041. bool repaintOnMouseActivityFlag : 1;
  17042. bool draggingFlag : 1;
  17043. bool mouseOverFlag : 1;
  17044. bool mouseInsideFlag : 1;
  17045. bool currentlyModalFlag : 1;
  17046. bool isDisabledFlag : 1;
  17047. bool childCompFocusedFlag : 1;
  17048. #ifdef JUCE_DEBUG
  17049. bool isInsidePaintCall : 1;
  17050. #endif
  17051. };
  17052. union
  17053. {
  17054. uint32 componentFlags_;
  17055. ComponentFlags flags;
  17056. };
  17057. void internalMouseEnter (int x, int y, const int64 time);
  17058. void internalMouseExit (int x, int y, const int64 time);
  17059. void internalMouseDown (int x, int y);
  17060. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  17061. void internalMouseDrag (int x, int y, const int64 time);
  17062. void internalMouseMove (int x, int y, const int64 time);
  17063. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  17064. void internalBroughtToFront();
  17065. void internalFocusGain (const FocusChangeType cause);
  17066. void internalFocusLoss (const FocusChangeType cause);
  17067. void internalChildFocusChange (FocusChangeType cause);
  17068. void internalModalInputAttempt();
  17069. void internalModifierKeysChanged();
  17070. void internalChildrenChanged();
  17071. void internalHierarchyChanged();
  17072. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  17073. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  17074. void repaintParent() throw();
  17075. void sendFakeMouseMove() const;
  17076. void takeKeyboardFocus (const FocusChangeType cause);
  17077. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  17078. static void giveAwayFocus();
  17079. void sendEnablementChangeMessage();
  17080. static void* runModalLoopCallback (void*);
  17081. void subtractObscuredRegions (RectangleList& result,
  17082. const int deltaX, const int deltaY,
  17083. const Rectangle& clipRect,
  17084. const Component* const compToAvoid) const throw();
  17085. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  17086. const int deltaX, const int deltaY) const throw();
  17087. // how much of the component is not off the edges of its parents
  17088. const Rectangle getUnclippedArea() const;
  17089. void sendVisibilityChangeMessage();
  17090. // This is included here just to cause a compile error if your code is still handling
  17091. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  17092. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  17093. // implement its methods instead of this Component method).
  17094. virtual void filesDropped (const StringArray&, int, int) {}
  17095. // components aren't allowed to have copy constructors, as this would mess up parent
  17096. // hierarchies. You might need to give your subclasses a private dummy constructor like
  17097. // this one to avoid compiler warnings.
  17098. Component (const Component&);
  17099. const Component& operator= (const Component&);
  17100. protected:
  17101. /** @internal */
  17102. virtual void internalRepaint (int x, int y, int w, int h);
  17103. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  17104. /** Overridden from the MessageListener parent class.
  17105. You can override this if you really need to, but be sure to pass your unwanted messages up
  17106. to this base class implementation, as the Component class needs to send itself messages
  17107. to work properly.
  17108. */
  17109. void handleMessage (const Message&);
  17110. };
  17111. #endif // __JUCE_COMPONENT_JUCEHEADER__
  17112. /********* End of inlined file: juce_Component.h *********/
  17113. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  17114. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17115. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17116. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  17117. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17118. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17119. /** A type used to hold the unique ID for an application command.
  17120. This is a numeric type, so it can be stored as an integer.
  17121. @see ApplicationCommandInfo, ApplicationCommandManager,
  17122. ApplicationCommandTarget, KeyPressMappingSet
  17123. */
  17124. typedef int CommandID;
  17125. /** A set of general-purpose application command IDs.
  17126. Because these commands are likely to be used in most apps, they're defined
  17127. here to help different apps to use the same numeric values for them.
  17128. Of course you don't have to use these, but some of them are used internally by
  17129. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  17130. @see ApplicationCommandInfo, ApplicationCommandManager,
  17131. ApplicationCommandTarget, KeyPressMappingSet
  17132. */
  17133. namespace StandardApplicationCommandIDs
  17134. {
  17135. /** This command ID should be used to send a "Quit the App" command.
  17136. This command is recognised by the JUCEApplication class, so if it is invoked
  17137. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  17138. object will catch it and call JUCEApplication::systemRequestedQuit().
  17139. */
  17140. static const CommandID quit = 0x1001;
  17141. /** The command ID that should be used to send a "Delete" command. */
  17142. static const CommandID del = 0x1002;
  17143. /** The command ID that should be used to send a "Cut" command. */
  17144. static const CommandID cut = 0x1003;
  17145. /** The command ID that should be used to send a "Copy to clipboard" command. */
  17146. static const CommandID copy = 0x1004;
  17147. /** The command ID that should be used to send a "Paste from clipboard" command. */
  17148. static const CommandID paste = 0x1005;
  17149. /** The command ID that should be used to send a "Select all" command. */
  17150. static const CommandID selectAll = 0x1006;
  17151. /** The command ID that should be used to send a "Deselect all" command. */
  17152. static const CommandID deselectAll = 0x1007;
  17153. }
  17154. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17155. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  17156. /**
  17157. Holds information describing an application command.
  17158. This object is used to pass information about a particular command, such as its
  17159. name, description and other usage flags.
  17160. When an ApplicationCommandTarget is asked to provide information about the commands
  17161. it can perform, this is the structure gets filled-in to describe each one.
  17162. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  17163. ApplicationCommandManager
  17164. */
  17165. struct JUCE_API ApplicationCommandInfo
  17166. {
  17167. ApplicationCommandInfo (const CommandID commandID) throw();
  17168. /** Sets a number of the structures values at once.
  17169. The meanings of each of the parameters is described below, in the appropriate
  17170. member variable's description.
  17171. */
  17172. void setInfo (const String& shortName,
  17173. const String& description,
  17174. const String& categoryName,
  17175. const int flags) throw();
  17176. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17177. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17178. is false, the bit is set.
  17179. */
  17180. void setActive (const bool isActive) throw();
  17181. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17182. */
  17183. void setTicked (const bool isTicked) throw();
  17184. /** Handy method for adding a keypress to the defaultKeypresses array.
  17185. This is just so you can write things like:
  17186. @code
  17187. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17188. @endcode
  17189. instead of
  17190. @code
  17191. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17192. @endcode
  17193. */
  17194. void addDefaultKeypress (const int keyCode,
  17195. const ModifierKeys& modifiers) throw();
  17196. /** The command's unique ID number.
  17197. */
  17198. CommandID commandID;
  17199. /** A short name to describe the command.
  17200. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17201. You can use the setInfo() method to quickly set this and some of the command's
  17202. other properties.
  17203. */
  17204. String shortName;
  17205. /** A longer description of the command.
  17206. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17207. pop-up tooltip describing what the command does.
  17208. You can use the setInfo() method to quickly set this and some of the command's
  17209. other properties.
  17210. */
  17211. String description;
  17212. /** A named category that the command fits into.
  17213. You can give your commands any category you like, and these will be displayed in
  17214. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17215. commands together.
  17216. You can use the setInfo() method to quickly set this and some of the command's
  17217. other properties.
  17218. */
  17219. String categoryName;
  17220. /** A list of zero or more keypresses that should be used as the default keys for
  17221. this command.
  17222. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17223. this list to initialise the default set of key-to-command mappings.
  17224. @see addDefaultKeypress
  17225. */
  17226. Array <KeyPress> defaultKeypresses;
  17227. /** Flags describing the ways in which this command should be used.
  17228. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17229. variable.
  17230. */
  17231. enum CommandFlags
  17232. {
  17233. /** Indicates that the command can't currently be performed.
  17234. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17235. not currently permissable to perform the command. If the flag is set, then
  17236. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17237. command or show themselves as not being enabled.
  17238. @see ApplicationCommandInfo::setActive
  17239. */
  17240. isDisabled = 1 << 0,
  17241. /** Indicates that the command should have a tick next to it on a menu.
  17242. If your command is shown on a menu and this is set, it'll show a tick next to
  17243. it. Other components such as buttons may also use this flag to indicate that it
  17244. is a value that can be toggled, and is currently in the 'on' state.
  17245. @see ApplicationCommandInfo::setTicked
  17246. */
  17247. isTicked = 1 << 1,
  17248. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17249. it will call the command twice, once on key-down and again on key-up.
  17250. @see ApplicationCommandTarget::InvocationInfo
  17251. */
  17252. wantsKeyUpDownCallbacks = 1 << 2,
  17253. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17254. command in its list.
  17255. */
  17256. hiddenFromKeyEditor = 1 << 3,
  17257. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17258. command in its list, but won't allow the assigned keypress to be changed.
  17259. */
  17260. readOnlyInKeyEditor = 1 << 4,
  17261. /** If this flag is present and the command is invoked from a keypress, then any
  17262. buttons or menus that are also connected to the command will not flash to
  17263. indicate that they've been triggered.
  17264. */
  17265. dontTriggerVisualFeedback = 1 << 5
  17266. };
  17267. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17268. You can use the setInfo() method to quickly set this and some of the command's
  17269. other properties.
  17270. */
  17271. int flags;
  17272. };
  17273. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17274. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17275. /**
  17276. A command target publishes a list of command IDs that it can perform.
  17277. An ApplicationCommandManager despatches commands to targets, which must be
  17278. able to provide information about what commands they can handle.
  17279. To create a target, you'll need to inherit from this class, implementing all of
  17280. its pure virtual methods.
  17281. For info about how a target is chosen to receive a command, see
  17282. ApplicationCommandManager::getFirstCommandTarget().
  17283. @see ApplicationCommandManager, ApplicationCommandInfo
  17284. */
  17285. class JUCE_API ApplicationCommandTarget
  17286. {
  17287. public:
  17288. /** Creates a command target. */
  17289. ApplicationCommandTarget();
  17290. /** Destructor. */
  17291. virtual ~ApplicationCommandTarget();
  17292. /**
  17293. */
  17294. struct JUCE_API InvocationInfo
  17295. {
  17296. InvocationInfo (const CommandID commandID) throw();
  17297. /** The UID of the command that should be performed. */
  17298. CommandID commandID;
  17299. /** The command's flags.
  17300. See ApplicationCommandInfo for a description of these flag values.
  17301. */
  17302. int commandFlags;
  17303. /** The types of context in which the command might be called. */
  17304. enum InvocationMethod
  17305. {
  17306. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17307. fromKeyPress, /**< The command is being invoked by a key-press. */
  17308. fromMenu, /**< The command is being invoked by a menu selection. */
  17309. fromButton /**< The command is being invoked by a button click. */
  17310. };
  17311. /** The type of event that triggered this command. */
  17312. InvocationMethod invocationMethod;
  17313. /** If triggered by a keypress or menu, this will be the component that had the
  17314. keyboard focus at the time.
  17315. If triggered by a button, it may be set to that component, or it may be null.
  17316. */
  17317. Component* originatingComponent;
  17318. /** The keypress that was used to invoke it.
  17319. Note that this will be an invalid keypress if the command was invoked
  17320. by some other means than a keyboard shortcut.
  17321. */
  17322. KeyPress keyPress;
  17323. /** True if the callback is being invoked when the key is pressed,
  17324. false if the key is being released.
  17325. @see KeyPressMappingSet::addCommand()
  17326. */
  17327. bool isKeyDown;
  17328. /** If the key is being released, this indicates how long it had been held
  17329. down for.
  17330. (Only relevant if isKeyDown is false.)
  17331. */
  17332. int millisecsSinceKeyPressed;
  17333. };
  17334. /** This must return the next target to try after this one.
  17335. When a command is being sent, and the first target can't handle
  17336. that command, this method is used to determine the next target that should
  17337. be tried.
  17338. It may return 0 if it doesn't know of another target.
  17339. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17340. method to return a parent component that might want to handle it.
  17341. @see invoke
  17342. */
  17343. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17344. /** This must return a complete list of commands that this target can handle.
  17345. Your target should add all the command IDs that it handles to the array that is
  17346. passed-in.
  17347. */
  17348. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17349. /** This must provide details about one of the commands that this target can perform.
  17350. This will be called with one of the command IDs that the target provided in its
  17351. getAllCommands() methods.
  17352. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17353. suitable information about the command. (The commandID field will already have been filled-in
  17354. by the caller).
  17355. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17356. set all the fields at once.
  17357. If the command is currently inactive for some reason, this method must use
  17358. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17359. bit of the ApplicationCommandInfo::flags field).
  17360. Any default key-presses for the command should be appended to the
  17361. ApplicationCommandInfo::defaultKeypresses field.
  17362. Note that if you change something that affects the status of the commands
  17363. that would be returned by this method (e.g. something that makes some commands
  17364. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17365. to cause the manager to refresh its status.
  17366. */
  17367. virtual void getCommandInfo (const CommandID commandID,
  17368. ApplicationCommandInfo& result) = 0;
  17369. /** This must actually perform the specified command.
  17370. If this target is able to perform the command specified by the commandID field of the
  17371. InvocationInfo structure, then it should do so, and must return true.
  17372. If it can't handle this command, it should return false, which tells the caller to pass
  17373. the command on to the next target in line.
  17374. @see invoke, ApplicationCommandManager::invoke
  17375. */
  17376. virtual bool perform (const InvocationInfo& info) = 0;
  17377. /** Makes this target invoke a command.
  17378. Your code can call this method to invoke a command on this target, but normally
  17379. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17380. ApplicationCommandManager::invokeDirectly().
  17381. If this target can perform the given command, it will call its perform() method to
  17382. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17383. to try, and the command will be passed along to it.
  17384. @param invocationInfo this must be correctly filled-in, describing the context for
  17385. the invocation.
  17386. @param asynchronously if false, the command will be performed before this method returns.
  17387. If true, a message will be posted so that the command will be performed
  17388. later on the message thread, and this method will return immediately.
  17389. @see perform, ApplicationCommandManager::invoke
  17390. */
  17391. bool invoke (const InvocationInfo& invocationInfo,
  17392. const bool asynchronously);
  17393. /** Invokes a given command directly on this target.
  17394. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17395. structure.
  17396. */
  17397. bool invokeDirectly (const CommandID commandID,
  17398. const bool asynchronously);
  17399. /** Searches this target and all subsequent ones for the first one that can handle
  17400. the specified command.
  17401. This will use getNextCommandTarget() to determine the chain of targets to try
  17402. after this one.
  17403. */
  17404. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17405. /** Checks whether this command can currently be performed by this target.
  17406. This will return true only if a call to getCommandInfo() doesn't set the
  17407. isDisabled flag to indicate that the command is inactive.
  17408. */
  17409. bool isCommandActive (const CommandID commandID);
  17410. /** If this object is a Component, this method will seach upwards in its current
  17411. UI hierarchy for the next parent component that implements the
  17412. ApplicationCommandTarget class.
  17413. If your target is a Component, this is a very handy method to use in your
  17414. getNextCommandTarget() implementation.
  17415. */
  17416. ApplicationCommandTarget* findFirstTargetParentComponent();
  17417. juce_UseDebuggingNewOperator
  17418. private:
  17419. // (for async invocation of commands)
  17420. class CommandTargetMessageInvoker : public MessageListener
  17421. {
  17422. public:
  17423. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17424. ~CommandTargetMessageInvoker();
  17425. void handleMessage (const Message& message);
  17426. private:
  17427. ApplicationCommandTarget* const owner;
  17428. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17429. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17430. };
  17431. CommandTargetMessageInvoker* messageInvoker;
  17432. friend class CommandTargetMessageInvoker;
  17433. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17434. };
  17435. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17436. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17437. /********* Start of inlined file: juce_ActionListener.h *********/
  17438. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17439. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17440. /**
  17441. Receives callbacks to indicate that some kind of event has occurred.
  17442. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17443. about something that's happened.
  17444. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17445. */
  17446. class JUCE_API ActionListener
  17447. {
  17448. public:
  17449. /** Destructor. */
  17450. virtual ~ActionListener() {}
  17451. /** Overridden by your subclass to receive the callback.
  17452. @param message the string that was specified when the event was triggered
  17453. by a call to ActionListenerList::sendActionMessage()
  17454. */
  17455. virtual void actionListenerCallback (const String& message) = 0;
  17456. };
  17457. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17458. /********* End of inlined file: juce_ActionListener.h *********/
  17459. /**
  17460. An instance of this class is used to specify initialisation and shutdown
  17461. code for the application.
  17462. An application that wants to run in the JUCE framework needs to declare a
  17463. subclass of JUCEApplication and implement its various pure virtual methods.
  17464. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17465. to declare an instance of this class and generate a suitable platform-specific
  17466. main() function.
  17467. e.g. @code
  17468. class MyJUCEApp : public JUCEApplication
  17469. {
  17470. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17471. // objects, which you must create in the initialise() method.
  17472. MyApplicationWindow* myMainWindow;
  17473. public:
  17474. MyJUCEApp()
  17475. : myMainWindow (0)
  17476. {
  17477. // never create any Juce objects in the constructor - do all your initialisation
  17478. // in the initialise() method.
  17479. }
  17480. ~MyJUCEApp()
  17481. {
  17482. // all your shutdown code must have already been done in the shutdown() method -
  17483. // nothing should happen in this destructor.
  17484. }
  17485. void initialise (const String& commandLine)
  17486. {
  17487. myMainWindow = new MyApplicationWindow();
  17488. myMainWindow->setBounds (100, 100, 400, 500);
  17489. myMainWindow->setVisible (true);
  17490. }
  17491. void shutdown()
  17492. {
  17493. delete myMainWindow;
  17494. }
  17495. const String getApplicationName()
  17496. {
  17497. return T("Super JUCE-o-matic");
  17498. }
  17499. const String getApplicationVersion()
  17500. {
  17501. return T("1.0");
  17502. }
  17503. };
  17504. // this creates wrapper code to actually launch the app properly.
  17505. START_JUCE_APPLICATION (MyJUCEApp)
  17506. @endcode
  17507. Because this object will be created before Juce has properly initialised, you must
  17508. NEVER add any member variable objects that will be automatically constructed. Likewise
  17509. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17510. you want to add to the class must be pointers, which you should instantiate during the
  17511. initialise() method, and delete in the shutdown() method.
  17512. @see MessageManager, DeletedAtShutdown
  17513. */
  17514. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17515. private ActionListener
  17516. {
  17517. protected:
  17518. /** Constructs a JUCE app object.
  17519. If subclasses implement a constructor or destructor, they shouldn't call any
  17520. JUCE code in there - put your startup/shutdown code in initialise() and
  17521. shutdown() instead.
  17522. */
  17523. JUCEApplication();
  17524. public:
  17525. /** Destructor.
  17526. If subclasses implement a constructor or destructor, they shouldn't call any
  17527. JUCE code in there - put your startup/shutdown code in initialise() and
  17528. shutdown() instead.
  17529. */
  17530. virtual ~JUCEApplication();
  17531. /** Returns the global instance of the application object being run. */
  17532. static JUCEApplication* getInstance() throw();
  17533. /** Called when the application starts.
  17534. This will be called once to let the application do whatever initialisation
  17535. it needs, create its windows, etc.
  17536. After the method returns, the normal event-dispatch loop will be run,
  17537. until the quit() method is called, at which point the shutdown()
  17538. method will be called to let the application clear up anything it needs
  17539. to delete.
  17540. If during the initialise() method, the application decides not to start-up
  17541. after all, it can just call the quit() method and the event loop won't be run.
  17542. @param commandLineParameters the line passed in does not include the
  17543. name of the executable, just the parameter list.
  17544. @see shutdown, quit
  17545. */
  17546. virtual void initialise (const String& commandLineParameters) = 0;
  17547. /** Returns true if the application hasn't yet completed its initialise() method
  17548. and entered the main event loop.
  17549. This is handy for things like splash screens to know when the app's up-and-running
  17550. properly.
  17551. */
  17552. bool isInitialising() const throw();
  17553. /* Called to allow the application to clear up before exiting.
  17554. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17555. terminate, and this method will get called to allow the app to sort itself
  17556. out.
  17557. Be careful that nothing happens in this method that might rely on messages
  17558. being sent, or any kind of window activity, because the message loop is no
  17559. longer running at this point.
  17560. @see DeletedAtShutdown
  17561. */
  17562. virtual void shutdown() = 0;
  17563. /** Returns the application's name.
  17564. An application must implement this to name itself.
  17565. */
  17566. virtual const String getApplicationName() = 0;
  17567. /** Returns the application's version number.
  17568. An application can implement this to give itself a version.
  17569. (The default implementation of this just returns an empty string).
  17570. */
  17571. virtual const String getApplicationVersion();
  17572. /** Checks whether multiple instances of the app are allowed.
  17573. If you application class returns true for this, more than one instance is
  17574. permitted to run (except on the Mac where this isn't possible).
  17575. If it's false, the second instance won't start, but it you will still get a
  17576. callback to anotherInstanceStarted() to tell you about this - which
  17577. gives you a chance to react to what the user was trying to do.
  17578. */
  17579. virtual bool moreThanOneInstanceAllowed();
  17580. /** Indicates that the user has tried to start up another instance of the app.
  17581. This will get called even if moreThanOneInstanceAllowed() is false.
  17582. */
  17583. virtual void anotherInstanceStarted (const String& commandLine);
  17584. /** Called when the operating system is trying to close the application.
  17585. The default implementation of this method is to call quit(), but it may
  17586. be overloaded to ignore the request or do some other special behaviour
  17587. instead. For example, you might want to offer the user the chance to save
  17588. their changes before quitting, and give them the chance to cancel.
  17589. If you want to send a quit signal to your app, this is the correct method
  17590. to call, because it means that requests that come from the system get handled
  17591. in the same way as those from your own application code. So e.g. you'd
  17592. call this method from a "quit" item on a menu bar.
  17593. */
  17594. virtual void systemRequestedQuit();
  17595. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17596. callback will be triggered, in case you want to log them or do some other
  17597. type of error-handling.
  17598. If the type of exception is derived from the std::exception class, the pointer
  17599. passed-in will be valid. If the exception is of unknown type, this pointer
  17600. will be null.
  17601. */
  17602. virtual void unhandledException (const std::exception* e,
  17603. const String& sourceFilename,
  17604. const int lineNumber);
  17605. /** Signals that the main message loop should stop and the application should terminate.
  17606. This isn't synchronous, it just posts a quit message to the main queue, and
  17607. when this message arrives, the message loop will stop, the shutdown() method
  17608. will be called, and the app will exit.
  17609. Note that this will cause an unconditional quit to happen, so if you need an
  17610. extra level before this, e.g. to give the user the chance to save their work
  17611. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17612. method - see that method's help for more info.
  17613. @see MessageManager, DeletedAtShutdown
  17614. */
  17615. static void quit();
  17616. /** Sets the value that should be returned as the application's exit code when the
  17617. app quits.
  17618. This is the value that's returned by the main() function. Normally you'd leave this
  17619. as 0 unless you want to indicate an error code.
  17620. @see getApplicationReturnValue
  17621. */
  17622. void setApplicationReturnValue (const int newReturnValue) throw();
  17623. /** Returns the value that has been set as the application's exit code.
  17624. @see setApplicationReturnValue
  17625. */
  17626. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17627. /** Returns the application's command line params.
  17628. */
  17629. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  17630. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17631. /** @internal */
  17632. static int main (String& commandLine, JUCEApplication* const newApp);
  17633. /** @internal */
  17634. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17635. /** @internal */
  17636. static void sendUnhandledException (const std::exception* const e,
  17637. const char* const sourceFile,
  17638. const int lineNumber);
  17639. /** @internal */
  17640. ApplicationCommandTarget* getNextCommandTarget();
  17641. /** @internal */
  17642. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17643. /** @internal */
  17644. void getAllCommands (Array <CommandID>& commands);
  17645. /** @internal */
  17646. bool perform (const InvocationInfo& info);
  17647. /** @internal */
  17648. void actionListenerCallback (const String& message);
  17649. private:
  17650. String commandLineParameters;
  17651. int appReturnValue;
  17652. bool stillInitialising;
  17653. static int shutdownAppAndClearUp();
  17654. };
  17655. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17656. /********* End of inlined file: juce_Application.h *********/
  17657. #endif
  17658. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17659. #endif
  17660. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17661. #endif
  17662. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17663. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17664. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17665. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17666. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17667. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17668. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17669. /**
  17670. Has a callback method that is triggered asynchronously.
  17671. This object allows an asynchronous callback function to be triggered, for
  17672. tasks such as coalescing multiple updates into a single callback later on.
  17673. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17674. message thread calling handleAsyncUpdate() as soon as it can.
  17675. */
  17676. class JUCE_API AsyncUpdater
  17677. {
  17678. public:
  17679. /** Creates an AsyncUpdater object. */
  17680. AsyncUpdater() throw();
  17681. /** Destructor.
  17682. If there are any pending callbacks when the object is deleted, these are lost.
  17683. */
  17684. virtual ~AsyncUpdater();
  17685. /** Causes the callback to be triggered at a later time.
  17686. This method returns immediately, having made sure that a callback
  17687. to the handleAsyncUpdate() method will occur as soon as possible.
  17688. If an update callback is already pending but hasn't happened yet, calls
  17689. to this method will be ignored.
  17690. It's thread-safe to call this method from any number of threads without
  17691. needing to worry about locking.
  17692. */
  17693. void triggerAsyncUpdate() throw();
  17694. /** This will stop any pending updates from happening.
  17695. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17696. callback happens, this will cancel the handleAsyncUpdate() callback.
  17697. */
  17698. void cancelPendingUpdate() throw();
  17699. /** If an update has been triggered and is pending, this will invoke it
  17700. synchronously.
  17701. Use this as a kind of "flush" operation - if an update is pending, the
  17702. handleAsyncUpdate() method will be called immediately; if no update is
  17703. pending, then nothing will be done.
  17704. */
  17705. void handleUpdateNowIfNeeded();
  17706. /** Called back to do whatever your class needs to do.
  17707. This method is called by the message thread at the next convenient time
  17708. after the triggerAsyncUpdate() method has been called.
  17709. */
  17710. virtual void handleAsyncUpdate() = 0;
  17711. private:
  17712. class AsyncUpdaterInternal : public MessageListener
  17713. {
  17714. public:
  17715. AsyncUpdaterInternal() throw() {}
  17716. ~AsyncUpdaterInternal() {}
  17717. void handleMessage (const Message&);
  17718. AsyncUpdater* owner;
  17719. private:
  17720. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17721. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17722. };
  17723. AsyncUpdaterInternal internalAsyncHandler;
  17724. bool asyncMessagePending;
  17725. };
  17726. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17727. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17728. /********* Start of inlined file: juce_Desktop.h *********/
  17729. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17730. #define __JUCE_DESKTOP_JUCEHEADER__
  17731. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17732. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17733. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17734. /**
  17735. Classes derived from this will be automatically deleted when the application exits.
  17736. After JUCEApplication::shutdown() has been called, any objects derived from
  17737. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17738. order to that in which they were created.
  17739. So if you've got a singleton and don't want to have to explicitly delete it, just
  17740. inherit from this and it'll be taken care of.
  17741. */
  17742. class JUCE_API DeletedAtShutdown
  17743. {
  17744. protected:
  17745. /** Creates a DeletedAtShutdown object. */
  17746. DeletedAtShutdown() throw();
  17747. /** Destructor.
  17748. It's ok to delete these objects explicitly - it's only the ones left
  17749. dangling at the end that will be deleted automatically.
  17750. */
  17751. virtual ~DeletedAtShutdown();
  17752. public:
  17753. /** Deletes all extant objects.
  17754. This shouldn't be used by applications, as it's called automatically
  17755. in the shutdown code of the JUCEApplication class.
  17756. */
  17757. static void deleteAll();
  17758. private:
  17759. DeletedAtShutdown (const DeletedAtShutdown&);
  17760. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17761. };
  17762. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17763. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17764. /********* Start of inlined file: juce_Timer.h *********/
  17765. #ifndef __JUCE_TIMER_JUCEHEADER__
  17766. #define __JUCE_TIMER_JUCEHEADER__
  17767. class InternalTimerThread;
  17768. /**
  17769. Repeatedly calls a user-defined method at a specified time interval.
  17770. A Timer's timerCallback() method will be repeatedly called at a given
  17771. interval. Initially when a Timer object is created, they will do nothing
  17772. until the startTimer() method is called, then the message thread will
  17773. start calling it back until stopTimer() is called.
  17774. The time interval isn't guaranteed to be precise to any more than maybe
  17775. 10-20ms, and the intervals may end up being much longer than requested if the
  17776. system is busy. Because it's the message thread that is doing the callbacks,
  17777. any messages that take a significant amount of time to process will block
  17778. all the timers for that period.
  17779. If you need to have a single callback that is shared by multiple timers with
  17780. different frequencies, then the MultiTimer class allows you to do that - its
  17781. structure is very similar to the Timer class, but contains multiple timers
  17782. internally, each one identified by an ID number.
  17783. @see MultiTimer
  17784. */
  17785. class JUCE_API Timer
  17786. {
  17787. protected:
  17788. /** Creates a Timer.
  17789. When created, the timer is stopped, so use startTimer() to get it going.
  17790. */
  17791. Timer() throw();
  17792. /** Creates a copy of another timer.
  17793. Note that this timer won't be started, even if the one you're copying
  17794. is running.
  17795. */
  17796. Timer (const Timer& other) throw();
  17797. public:
  17798. /** Destructor. */
  17799. virtual ~Timer();
  17800. /** The user-defined callback routine that actually gets called periodically.
  17801. It's perfectly ok to call startTimer() or stopTimer() from within this
  17802. callback to change the subsequent intervals.
  17803. */
  17804. virtual void timerCallback() = 0;
  17805. /** Starts the timer and sets the length of interval required.
  17806. If the timer is already started, this will reset it, so the
  17807. time between calling this method and the next timer callback
  17808. will not be less than the interval length passed in.
  17809. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17810. rounded up to 1)
  17811. */
  17812. void startTimer (const int intervalInMilliseconds) throw();
  17813. /** Stops the timer.
  17814. No more callbacks will be made after this method returns.
  17815. If this is called from a different thread, any callbacks that may
  17816. be currently executing may be allowed to finish before the method
  17817. returns.
  17818. */
  17819. void stopTimer() throw();
  17820. /** Checks if the timer has been started.
  17821. @returns true if the timer is running.
  17822. */
  17823. bool isTimerRunning() const throw() { return periodMs > 0; }
  17824. /** Returns the timer's interval.
  17825. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17826. */
  17827. int getTimerInterval() const throw() { return periodMs; }
  17828. private:
  17829. friend class InternalTimerThread;
  17830. int countdownMs, periodMs;
  17831. Timer* previous;
  17832. Timer* next;
  17833. const Timer& operator= (const Timer&);
  17834. };
  17835. #endif // __JUCE_TIMER_JUCEHEADER__
  17836. /********* End of inlined file: juce_Timer.h *********/
  17837. /**
  17838. Classes can implement this interface and register themselves with the Desktop class
  17839. to receive callbacks when the currently focused component changes.
  17840. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17841. */
  17842. class JUCE_API FocusChangeListener
  17843. {
  17844. public:
  17845. /** Destructor. */
  17846. virtual ~FocusChangeListener() {}
  17847. /** Callback to indicate that the currently focused component has changed. */
  17848. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17849. };
  17850. /**
  17851. Describes and controls aspects of the computer's desktop.
  17852. */
  17853. class JUCE_API Desktop : private DeletedAtShutdown,
  17854. private Timer,
  17855. private AsyncUpdater
  17856. {
  17857. public:
  17858. /** There's only one dektop object, and this method will return it.
  17859. */
  17860. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17861. /** Returns a list of the positions of all the monitors available.
  17862. The first rectangle in the list will be the main monitor area.
  17863. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17864. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17865. */
  17866. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17867. /** Returns the position and size of the main monitor.
  17868. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17869. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17870. */
  17871. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17872. /** Returns the position and size of the monitor which contains this co-ordinate.
  17873. If none of the monitors contains the point, this will just return the
  17874. main monitor.
  17875. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17876. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17877. */
  17878. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17879. /** Returns the mouse position.
  17880. The co-ordinates are relative to the top-left of the main monitor.
  17881. */
  17882. static void getMousePosition (int& x, int& y) throw();
  17883. /** Makes the mouse pointer jump to a given location.
  17884. The co-ordinates are relative to the top-left of the main monitor.
  17885. */
  17886. static void setMousePosition (int x, int y) throw();
  17887. /** Returns the last position at which a mouse button was pressed.
  17888. */
  17889. static void getLastMouseDownPosition (int& x, int& y) throw();
  17890. /** Returns the number of times the mouse button has been clicked since the
  17891. app started.
  17892. Each mouse-down event increments this number by 1.
  17893. */
  17894. static int getMouseButtonClickCounter() throw();
  17895. /** This lets you prevent the screensaver from becoming active.
  17896. Handy if you're running some sort of presentation app where having a screensaver
  17897. appear would be annoying.
  17898. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17899. won't enable a screensaver unless the user has actually set one up).
  17900. The disablement will only happen while the Juce application is the foreground
  17901. process - if another task is running in front of it, then the screensaver will
  17902. be unaffected.
  17903. @see isScreenSaverEnabled
  17904. */
  17905. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17906. /** Returns true if the screensaver has not been turned off.
  17907. This will return the last value passed into setScreenSaverEnabled(). Note that
  17908. it won't tell you whether the user is actually using a screen saver, just
  17909. whether this app is deliberately preventing one from running.
  17910. @see setScreenSaverEnabled
  17911. */
  17912. static bool isScreenSaverEnabled() throw();
  17913. /** Registers a MouseListener that will receive all mouse events that occur on
  17914. any component.
  17915. @see removeGlobalMouseListener
  17916. */
  17917. void addGlobalMouseListener (MouseListener* const listener) throw();
  17918. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17919. method.
  17920. @see addGlobalMouseListener
  17921. */
  17922. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17923. /** Registers a MouseListener that will receive a callback whenever the focused
  17924. component changes.
  17925. */
  17926. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17927. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17928. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17929. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  17930. The component must already be on the desktop for this method to work. It will
  17931. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  17932. etc will be hidden.
  17933. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  17934. the component that's currently being used will be resized back to the size
  17935. and position it was in before being put into this mode.
  17936. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  17937. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  17938. to hide as much on-screen paraphenalia as possible.
  17939. */
  17940. void setKioskModeComponent (Component* componentToUse,
  17941. const bool allowMenusAndBars = true);
  17942. /** Returns the component that is currently being used in kiosk-mode.
  17943. This is the component that was last set by setKioskModeComponent(). If none
  17944. has been set, this returns 0.
  17945. */
  17946. Component* getKioskModeComponent() const { return kioskModeComponent; }
  17947. /** Returns the number of components that are currently active as top-level
  17948. desktop windows.
  17949. @see getComponent, Component::addToDesktop
  17950. */
  17951. int getNumComponents() const throw();
  17952. /** Returns one of the top-level desktop window components.
  17953. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17954. index is out-of-range.
  17955. @see getNumComponents, Component::addToDesktop
  17956. */
  17957. Component* getComponent (const int index) const throw();
  17958. /** Finds the component at a given screen location.
  17959. This will drill down into top-level windows to find the child component at
  17960. the given position.
  17961. Returns 0 if the co-ordinates are inside a non-Juce window.
  17962. */
  17963. Component* findComponentAt (const int screenX,
  17964. const int screenY) const;
  17965. juce_UseDebuggingNewOperator
  17966. /** Tells this object to refresh its idea of what the screen resolution is.
  17967. (Called internally by the native code).
  17968. */
  17969. void refreshMonitorSizes() throw();
  17970. /** True if the OS supports semitransparent windows */
  17971. static bool canUseSemiTransparentWindows() throw();
  17972. private:
  17973. friend class Component;
  17974. friend class ComponentPeer;
  17975. SortedSet <void*> mouseListeners, focusListeners;
  17976. VoidArray desktopComponents;
  17977. friend class DeletedAtShutdown;
  17978. friend class TopLevelWindowManager;
  17979. Desktop() throw();
  17980. ~Desktop() throw();
  17981. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17982. int lastMouseX, lastMouseY;
  17983. Component* kioskModeComponent;
  17984. Rectangle kioskComponentOriginalBounds;
  17985. void timerCallback();
  17986. void sendMouseMove();
  17987. void resetTimer() throw();
  17988. int getNumDisplayMonitors() const throw();
  17989. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17990. void addDesktopComponent (Component* const c) throw();
  17991. void removeDesktopComponent (Component* const c) throw();
  17992. void componentBroughtToFront (Component* const c) throw();
  17993. void triggerFocusCallback() throw();
  17994. void handleAsyncUpdate();
  17995. Desktop (const Desktop&);
  17996. const Desktop& operator= (const Desktop&);
  17997. };
  17998. #endif // __JUCE_DESKTOP_JUCEHEADER__
  17999. /********* End of inlined file: juce_Desktop.h *********/
  18000. class KeyPressMappingSet;
  18001. class ApplicationCommandManagerListener;
  18002. /**
  18003. One of these objects holds a list of all the commands your app can perform,
  18004. and despatches these commands when needed.
  18005. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  18006. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  18007. to invoke automatically, which means you don't have to handle the result of a menu
  18008. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  18009. which can choose which events they want to handle.
  18010. This architecture also allows for nested ApplicationCommandTargets, so that for example
  18011. you could have two different objects, one inside the other, both of which can respond to
  18012. a "delete" command. Depending on which one has focus, the command will be sent to the
  18013. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  18014. method.
  18015. To set up your app to use commands, you'll need to do the following:
  18016. - Create a global ApplicationCommandManager to hold the list of all possible
  18017. commands. (This will also manage a set of key-mappings for them).
  18018. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  18019. This allows the object to provide a list of commands that it can perform, and
  18020. to handle them.
  18021. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  18022. or ApplicationCommandManager::registerCommand().
  18023. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  18024. method to access the key-mapper object, which you will need to register as a key-listener
  18025. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  18026. about setting this up.
  18027. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  18028. cause these commands to be invoked automatically.
  18029. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  18030. When a command is invoked, the ApplicationCommandManager will try to choose the best
  18031. ApplicationCommandTarget to receive the specified command. To do this it will use the
  18032. current keyboard focus to see which component might be interested, and will search the
  18033. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  18034. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  18035. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  18036. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  18037. point if the command still hasn't been performed, it will be passed to the current
  18038. JUCEApplication object (which is itself an ApplicationCommandTarget).
  18039. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  18040. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  18041. the object yourself.
  18042. @see ApplicationCommandTarget, ApplicationCommandInfo
  18043. */
  18044. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  18045. private FocusChangeListener
  18046. {
  18047. public:
  18048. /** Creates an ApplicationCommandManager.
  18049. Once created, you'll need to register all your app's commands with it, using
  18050. ApplicationCommandManager::registerAllCommandsForTarget() or
  18051. ApplicationCommandManager::registerCommand().
  18052. */
  18053. ApplicationCommandManager();
  18054. /** Destructor.
  18055. Make sure that you don't delete this if pointers to it are still being used by
  18056. objects such as PopupMenus or Buttons.
  18057. */
  18058. virtual ~ApplicationCommandManager();
  18059. /** Clears the current list of all commands.
  18060. Note that this will also clear the contents of the KeyPressMappingSet.
  18061. */
  18062. void clearCommands();
  18063. /** Adds a command to the list of registered commands.
  18064. @see registerAllCommandsForTarget
  18065. */
  18066. void registerCommand (const ApplicationCommandInfo& newCommand);
  18067. /** Adds all the commands that this target publishes to the manager's list.
  18068. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  18069. to get details about all the commands that this target can do, and will call
  18070. registerCommand() to add each one to the manger's list.
  18071. @see registerCommand
  18072. */
  18073. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  18074. /** Removes the command with a specified ID.
  18075. Note that this will also remove any key mappings that are mapped to the command.
  18076. */
  18077. void removeCommand (const CommandID commandID);
  18078. /** This should be called to tell the manager that one of its registered commands may have changed
  18079. its active status.
  18080. Because the command manager only finds out whether a command is active or inactive by querying
  18081. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  18082. allows things like buttons to update their enablement, etc.
  18083. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  18084. for any registered listeners.
  18085. */
  18086. void commandStatusChanged();
  18087. /** Returns the number of commands that have been registered.
  18088. @see registerCommand
  18089. */
  18090. int getNumCommands() const throw() { return commands.size(); }
  18091. /** Returns the details about one of the registered commands.
  18092. The index is between 0 and (getNumCommands() - 1).
  18093. */
  18094. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  18095. /** Returns the details about a given command ID.
  18096. This will search the list of registered commands for one with the given command
  18097. ID number, and return its associated info. If no matching command is found, this
  18098. will return 0.
  18099. */
  18100. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  18101. /** Returns the name field for a command.
  18102. An empty string is returned if no command with this ID has been registered.
  18103. @see getDescriptionOfCommand
  18104. */
  18105. const String getNameOfCommand (const CommandID commandID) const throw();
  18106. /** Returns the description field for a command.
  18107. An empty string is returned if no command with this ID has been registered. If the
  18108. command has no description, this will return its short name field instead.
  18109. @see getNameOfCommand
  18110. */
  18111. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  18112. /** Returns the list of categories.
  18113. This will go through all registered commands, and return a list of all the distict
  18114. categoryName values from their ApplicationCommandInfo structure.
  18115. @see getCommandsInCategory()
  18116. */
  18117. const StringArray getCommandCategories() const throw();
  18118. /** Returns a list of all the command UIDs in a particular category.
  18119. @see getCommandCategories()
  18120. */
  18121. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  18122. /** Returns the manager's internal set of key mappings.
  18123. This object can be used to edit the keypresses. To actually link this object up
  18124. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  18125. class.
  18126. @see KeyPressMappingSet
  18127. */
  18128. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  18129. /** Invokes the given command directly, sending it to the default target.
  18130. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18131. structure.
  18132. */
  18133. bool invokeDirectly (const CommandID commandID,
  18134. const bool asynchronously);
  18135. /** Sends a command to the default target.
  18136. This will choose a target using getFirstCommandTarget(), and send the specified command
  18137. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  18138. first target can't handle the command, it will be passed on to targets further down the
  18139. chain (see ApplicationCommandTarget::invoke() for more info).
  18140. @param invocationInfo this must be correctly filled-in, describing the context for
  18141. the invocation.
  18142. @param asynchronously if false, the command will be performed before this method returns.
  18143. If true, a message will be posted so that the command will be performed
  18144. later on the message thread, and this method will return immediately.
  18145. @see ApplicationCommandTarget::invoke
  18146. */
  18147. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  18148. const bool asynchronously);
  18149. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  18150. Whenever the manager needs to know which target a command should be sent to, it calls
  18151. this method to determine the first one to try.
  18152. By default, this method will return the target that was set by calling setFirstCommandTarget().
  18153. If no target is set, it will return the result of findDefaultComponentTarget().
  18154. If you need to make sure all commands go via your own custom target, then you can
  18155. either use setFirstCommandTarget() to specify a single target, or override this method
  18156. if you need more complex logic to choose one.
  18157. It may return 0 if no targets are available.
  18158. @see getTargetForCommand, invoke, invokeDirectly
  18159. */
  18160. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  18161. /** Sets a target to be returned by getFirstCommandTarget().
  18162. If this is set to 0, then getFirstCommandTarget() will by default return the
  18163. result of findDefaultComponentTarget().
  18164. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  18165. deleting the target object.
  18166. */
  18167. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  18168. /** Tries to find the best target to use to perform a given command.
  18169. This will call getFirstCommandTarget() to find the preferred target, and will
  18170. check whether that target can handle the given command. If it can't, then it'll use
  18171. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  18172. so on until no more are available.
  18173. If no targets are found that can perform the command, this method will return 0.
  18174. If a target is found, then it will get the target to fill-in the upToDateInfo
  18175. structure with the latest info about that command, so that the caller can see
  18176. whether the command is disabled, ticked, etc.
  18177. */
  18178. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18179. ApplicationCommandInfo& upToDateInfo);
  18180. /** Registers a listener that will be called when various events occur. */
  18181. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18182. /** Deregisters a previously-added listener. */
  18183. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18184. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18185. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18186. but is exposed here in case it's useful.
  18187. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18188. windows, etc., and using the findTargetForComponent() method.
  18189. */
  18190. static ApplicationCommandTarget* findDefaultComponentTarget();
  18191. /** Examines this component and all its parents in turn, looking for the first one
  18192. which is a ApplicationCommandTarget.
  18193. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18194. that class.
  18195. */
  18196. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18197. juce_UseDebuggingNewOperator
  18198. private:
  18199. OwnedArray <ApplicationCommandInfo> commands;
  18200. SortedSet <void*> listeners;
  18201. KeyPressMappingSet* keyMappings;
  18202. ApplicationCommandTarget* firstTarget;
  18203. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18204. void handleAsyncUpdate();
  18205. void globalFocusChanged (Component*);
  18206. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18207. // version of this method.
  18208. virtual short getFirstCommandTarget() { return 0; }
  18209. };
  18210. /**
  18211. A listener that receives callbacks from an ApplicationCommandManager when
  18212. commands are invoked or the command list is changed.
  18213. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18214. */
  18215. class JUCE_API ApplicationCommandManagerListener
  18216. {
  18217. public:
  18218. /** Destructor. */
  18219. virtual ~ApplicationCommandManagerListener() {}
  18220. /** Called when an app command is about to be invoked. */
  18221. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18222. /** Called when commands are registered or deregistered from the
  18223. command manager, or when commands are made active or inactive.
  18224. Note that if you're using this to watch for changes to whether a command is disabled,
  18225. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18226. whenever the status of your command might have changed.
  18227. */
  18228. virtual void applicationCommandListChanged() = 0;
  18229. };
  18230. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18231. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18232. #endif
  18233. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18234. #endif
  18235. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18236. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18237. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18238. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18239. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18240. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18241. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18242. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18243. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18244. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18245. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18246. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18247. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18248. /********* Start of inlined file: juce_ChangeListener.h *********/
  18249. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18250. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18251. /**
  18252. Receives callbacks about changes to some kind of object.
  18253. Many objects use a ChangeListenerList to keep a set of listeners which they
  18254. will inform when something changes. A subclass of ChangeListener
  18255. is used to receive these callbacks.
  18256. Note that the major difference between an ActionListener and a ChangeListener
  18257. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18258. callbacks, but ActionListeners perform one callback for every event posted.
  18259. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18260. */
  18261. class JUCE_API ChangeListener
  18262. {
  18263. public:
  18264. /** Destructor. */
  18265. virtual ~ChangeListener() {}
  18266. /** Overridden by your subclass to receive the callback.
  18267. @param objectThatHasChanged the value that was passed to the
  18268. ChangeListenerList::sendChangeMessage() method
  18269. */
  18270. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18271. };
  18272. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18273. /********* End of inlined file: juce_ChangeListener.h *********/
  18274. /**
  18275. A set of ChangeListeners.
  18276. Listeners can be added and removed from the list, and change messages can be
  18277. broadcast to all the listeners.
  18278. @see ChangeListener, ChangeBroadcaster
  18279. */
  18280. class JUCE_API ChangeListenerList : public MessageListener
  18281. {
  18282. public:
  18283. /** Creates an empty list. */
  18284. ChangeListenerList() throw();
  18285. /** Destructor. */
  18286. ~ChangeListenerList() throw();
  18287. /** Adds a listener to the list.
  18288. (Trying to add a listener that's already on the list will have no effect).
  18289. */
  18290. void addChangeListener (ChangeListener* const listener) throw();
  18291. /** Removes a listener from the list.
  18292. If the listener isn't on the list, this won't have any effect.
  18293. */
  18294. void removeChangeListener (ChangeListener* const listener) throw();
  18295. /** Removes all listeners from the list. */
  18296. void removeAllChangeListeners() throw();
  18297. /** Posts an asynchronous change message to all the listeners.
  18298. If a message has already been sent and hasn't yet been delivered, this
  18299. method won't send another - in this way it coalesces multiple frequent
  18300. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18301. with the ActionListener, which posts a new event for every call to its
  18302. sendActionMessage() method.
  18303. Only listeners which are on the list when the change event is delivered
  18304. will receive the event - and this may include listeners that weren't on
  18305. the list when the change message was sent.
  18306. @param objectThatHasChanged this pointer is passed to the
  18307. ChangeListener::changeListenerCallback() method,
  18308. and can be any value the application needs
  18309. @see sendSynchronousChangeMessage
  18310. */
  18311. void sendChangeMessage (void* objectThatHasChanged) throw();
  18312. /** This will synchronously callback all the ChangeListeners.
  18313. Use this if you need to synchronously force a call to all the
  18314. listeners' ChangeListener::changeListenerCallback() methods.
  18315. */
  18316. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18317. /** If a change message has been sent but not yet dispatched, this will
  18318. use sendSynchronousChangeMessage() to make the callback immediately.
  18319. */
  18320. void dispatchPendingMessages();
  18321. /** @internal */
  18322. void handleMessage (const Message&);
  18323. juce_UseDebuggingNewOperator
  18324. private:
  18325. SortedSet <void*> listeners;
  18326. CriticalSection lock;
  18327. void* lastChangedObject;
  18328. bool messagePending;
  18329. ChangeListenerList (const ChangeListenerList&);
  18330. const ChangeListenerList& operator= (const ChangeListenerList&);
  18331. };
  18332. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18333. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18334. /** Manages a list of ChangeListeners, and can send them messages.
  18335. To quickly add methods to your class that can add/remove change
  18336. listeners and broadcast to them, you can derive from this.
  18337. @see ChangeListenerList, ChangeListener
  18338. */
  18339. class JUCE_API ChangeBroadcaster
  18340. {
  18341. public:
  18342. /** Creates an ChangeBroadcaster. */
  18343. ChangeBroadcaster() throw();
  18344. /** Destructor. */
  18345. virtual ~ChangeBroadcaster();
  18346. /** Adds a listener to the list.
  18347. (Trying to add a listener that's already on the list will have no effect).
  18348. */
  18349. void addChangeListener (ChangeListener* const listener) throw();
  18350. /** Removes a listener from the list.
  18351. If the listener isn't on the list, this won't have any effect.
  18352. */
  18353. void removeChangeListener (ChangeListener* const listener) throw();
  18354. /** Removes all listeners from the list. */
  18355. void removeAllChangeListeners() throw();
  18356. /** Broadcasts a change message to all the registered listeners.
  18357. The message will be delivered asynchronously by the event thread, so this
  18358. method will not directly call any of the listeners. For a synchronous
  18359. message, use sendSynchronousChangeMessage().
  18360. @see ChangeListenerList::sendActionMessage
  18361. */
  18362. void sendChangeMessage (void* objectThatHasChanged) throw();
  18363. /** Sends a synchronous change message to all the registered listeners.
  18364. @see ChangeListenerList::sendSynchronousChangeMessage
  18365. */
  18366. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18367. /** If a change message has been sent but not yet dispatched, this will
  18368. use sendSynchronousChangeMessage() to make the callback immediately.
  18369. */
  18370. void dispatchPendingMessages();
  18371. private:
  18372. ChangeListenerList changeListenerList;
  18373. ChangeBroadcaster (const ChangeBroadcaster&);
  18374. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18375. };
  18376. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18377. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18378. /** Wrapper on a file that stores a list of key/value data pairs.
  18379. Useful for storing application settings, etc. See the PropertySet class for
  18380. the interfaces that read and write values.
  18381. Not designed for very large amounts of data, as it keeps all the values in
  18382. memory and writes them out to disk lazily when they are changed.
  18383. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18384. with it, and these will be signalled when a value changes.
  18385. @see PropertySet
  18386. */
  18387. class JUCE_API PropertiesFile : public PropertySet,
  18388. public ChangeBroadcaster,
  18389. private Timer
  18390. {
  18391. public:
  18392. enum FileFormatOptions
  18393. {
  18394. ignoreCaseOfKeyNames = 1,
  18395. storeAsBinary = 2,
  18396. storeAsCompressedBinary = 4,
  18397. storeAsXML = 8
  18398. };
  18399. /**
  18400. Creates a PropertiesFile object.
  18401. @param file the file to use
  18402. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18403. is changed, the object will wait for this amount
  18404. of time and then save the file. If zero, the file
  18405. will be written to disk immediately on being changed
  18406. (which might be slow, as it'll re-write synchronously
  18407. each time a value-change method is called). If it is
  18408. less than zero, the file won't be saved until
  18409. save() or saveIfNeeded() are explicitly called.
  18410. @param options a combination of the flags in the FileFormatOptions
  18411. enum, which specify the type of file to save, and other
  18412. options.
  18413. */
  18414. PropertiesFile (const File& file,
  18415. const int millisecondsBeforeSaving,
  18416. const int options) throw();
  18417. /** Destructor.
  18418. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18419. */
  18420. ~PropertiesFile();
  18421. /** This will flush all the values to disk if they've changed since the last
  18422. time they were saved.
  18423. Returns false if it fails to write to the file for some reason (maybe because
  18424. it's read-only or the directory doesn't exist or something).
  18425. @see save
  18426. */
  18427. bool saveIfNeeded();
  18428. /** This will force a write-to-disk of the current values, regardless of whether
  18429. anything has changed since the last save.
  18430. Returns false if it fails to write to the file for some reason (maybe because
  18431. it's read-only or the directory doesn't exist or something).
  18432. @see saveIfNeeded
  18433. */
  18434. bool save();
  18435. /** Returns true if the properties have been altered since the last time they were
  18436. saved.
  18437. */
  18438. bool needsToBeSaved() const throw();
  18439. /** Returns the file that's being used. */
  18440. const File getFile() const throw();
  18441. /** Handy utility to create a properties file in whatever the standard OS-specific
  18442. location is for these things.
  18443. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18444. creates a PropertiesFile object with the specified properties. See
  18445. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18446. what the parameters do.
  18447. @see getDefaultAppSettingsFile
  18448. */
  18449. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18450. const String& fileNameSuffix,
  18451. const String& folderName,
  18452. const bool commonToAllUsers,
  18453. const int millisecondsBeforeSaving,
  18454. const int propertiesFileOptions);
  18455. /** Handy utility to choose a file in the standard OS-dependent location for application
  18456. settings files.
  18457. So on a Mac, this will return a file called:
  18458. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18459. On Windows it'll return something like:
  18460. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18461. On Linux it'll return
  18462. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18463. If you pass an empty string as the folder name, it'll use the app name for this (or
  18464. omit the folder name on the Mac).
  18465. If commonToAllUsers is true, then this will return the same file for all users of the
  18466. computer, regardless of the current user. If it is false, the file will be specific to
  18467. only the current user. Use this to choose whether you're saving settings that are common
  18468. or user-specific.
  18469. */
  18470. static const File getDefaultAppSettingsFile (const String& applicationName,
  18471. const String& fileNameSuffix,
  18472. const String& folderName,
  18473. const bool commonToAllUsers);
  18474. juce_UseDebuggingNewOperator
  18475. protected:
  18476. virtual void propertyChanged();
  18477. private:
  18478. File file;
  18479. int timerInterval;
  18480. const int options;
  18481. bool needsWriting;
  18482. void timerCallback();
  18483. PropertiesFile (const PropertiesFile&);
  18484. const PropertiesFile& operator= (const PropertiesFile&);
  18485. };
  18486. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18487. /********* End of inlined file: juce_PropertiesFile.h *********/
  18488. /**
  18489. Manages a collection of properties.
  18490. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18491. as a singleton.
  18492. It holds two different PropertiesFile objects internally, one for user-specific
  18493. settings (stored in your user directory), and one for settings that are common to
  18494. all users (stored in a folder accessible to all users).
  18495. The class manages the creation of these files on-demand, allowing access via the
  18496. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18497. methods like testWriteAccess() to check that the files can be saved.
  18498. If you're using one of these as a singleton, then your app's start-up code should
  18499. first of all call setStorageParameters() to tell it the parameters to use to create
  18500. the properties files.
  18501. @see PropertiesFile
  18502. */
  18503. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18504. {
  18505. public:
  18506. /**
  18507. Creates an ApplicationProperties object.
  18508. Before using it, you must call setStorageParameters() to give it the info
  18509. it needs to create the property files.
  18510. */
  18511. ApplicationProperties() throw();
  18512. /** Destructor.
  18513. */
  18514. ~ApplicationProperties();
  18515. juce_DeclareSingleton (ApplicationProperties, false)
  18516. /** Gives the object the information it needs to create the appropriate properties files.
  18517. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18518. info about how these parameters are used.
  18519. */
  18520. void setStorageParameters (const String& applicationName,
  18521. const String& fileNameSuffix,
  18522. const String& folderName,
  18523. const int millisecondsBeforeSaving,
  18524. const int propertiesFileOptions) throw();
  18525. /** Tests whether the files can be successfully written to, and can show
  18526. an error message if not.
  18527. Returns true if none of the tests fail.
  18528. @param testUserSettings if true, the user settings file will be tested
  18529. @param testCommonSettings if true, the common settings file will be tested
  18530. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18531. message box if either of the tests fail
  18532. */
  18533. bool testWriteAccess (const bool testUserSettings,
  18534. const bool testCommonSettings,
  18535. const bool showWarningDialogOnFailure);
  18536. /** Returns the user settings file.
  18537. The first time this is called, it will create and load the properties file.
  18538. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18539. the common settings are used as a second-chance place to look. This is done via the
  18540. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18541. to the fallback for the user settings.
  18542. @see getCommonSettings
  18543. */
  18544. PropertiesFile* getUserSettings() throw();
  18545. /** Returns the common settings file.
  18546. The first time this is called, it will create and load the properties file.
  18547. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18548. read-only (e.g. because the user doesn't have permission to write
  18549. to shared files), then this will return the user settings instead,
  18550. (like getUserSettings() would do). This is handy if you'd like to
  18551. write a value to the common settings, but if that's no possible,
  18552. then you'd rather write to the user settings than none at all.
  18553. If returnUserPropsIfReadOnly is false, this method will always return
  18554. the common settings, even if any changes to them can't be saved.
  18555. @see getUserSettings
  18556. */
  18557. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18558. /** Saves both files if they need to be saved.
  18559. @see PropertiesFile::saveIfNeeded
  18560. */
  18561. bool saveIfNeeded();
  18562. /** Flushes and closes both files if they are open.
  18563. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18564. and closes both files. They will then be re-opened the next time getUserSettings()
  18565. or getCommonSettings() is called.
  18566. */
  18567. void closeFiles();
  18568. juce_UseDebuggingNewOperator
  18569. private:
  18570. PropertiesFile* userProps;
  18571. PropertiesFile* commonProps;
  18572. String appName, fileSuffix, folderName;
  18573. int msBeforeSaving, options;
  18574. int commonSettingsAreReadOnly;
  18575. ApplicationProperties (const ApplicationProperties&);
  18576. const ApplicationProperties& operator= (const ApplicationProperties&);
  18577. void openFiles() throw();
  18578. };
  18579. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18580. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18581. #endif
  18582. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18583. #endif
  18584. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18585. #endif
  18586. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18587. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18588. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18589. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18590. /**
  18591. Handles reading/writing to the system's clipboard.
  18592. */
  18593. class JUCE_API SystemClipboard
  18594. {
  18595. public:
  18596. /** Copies a string of text onto the clipboard */
  18597. static void copyTextToClipboard (const String& text) throw();
  18598. /** Gets the current clipboard's contents.
  18599. Obviously this might have come from another app, so could contain
  18600. anything..
  18601. */
  18602. static const String getTextFromClipboard() throw();
  18603. };
  18604. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18605. /********* End of inlined file: juce_SystemClipboard.h *********/
  18606. #endif
  18607. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18608. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18609. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18610. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18611. /********* Start of inlined file: juce_MidiMessage.h *********/
  18612. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18613. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18614. /**
  18615. Encapsulates a MIDI message.
  18616. @see MidiMessageSequence, MidiOutput, MidiInput
  18617. */
  18618. class JUCE_API MidiMessage
  18619. {
  18620. public:
  18621. /** Creates a 3-byte short midi message.
  18622. @param byte1 message byte 1
  18623. @param byte2 message byte 2
  18624. @param byte3 message byte 3
  18625. @param timeStamp the time to give the midi message - this value doesn't
  18626. use any particular units, so will be application-specific
  18627. */
  18628. MidiMessage (const int byte1,
  18629. const int byte2,
  18630. const int byte3,
  18631. const double timeStamp = 0) throw();
  18632. /** Creates a 2-byte short midi message.
  18633. @param byte1 message byte 1
  18634. @param byte2 message byte 2
  18635. @param timeStamp the time to give the midi message - this value doesn't
  18636. use any particular units, so will be application-specific
  18637. */
  18638. MidiMessage (const int byte1,
  18639. const int byte2,
  18640. const double timeStamp = 0) throw();
  18641. /** Creates a 1-byte short midi message.
  18642. @param byte1 message byte 1
  18643. @param timeStamp the time to give the midi message - this value doesn't
  18644. use any particular units, so will be application-specific
  18645. */
  18646. MidiMessage (const int byte1,
  18647. const double timeStamp = 0) throw();
  18648. /** Creates a midi message from a block of data. */
  18649. MidiMessage (const uint8* const data,
  18650. const int dataSize,
  18651. const double timeStamp = 0) throw();
  18652. /** Reads the next midi message from some data.
  18653. This will read as many bytes from a data stream as it needs to make a
  18654. complete message, and will return the number of bytes it used. This lets
  18655. you read a sequence of midi messages from a file or stream.
  18656. @param data the data to read from
  18657. @param size the maximum number of bytes it's allowed to read
  18658. @param numBytesUsed returns the number of bytes that were actually needed
  18659. @param lastStatusByte in a sequence of midi messages, the initial byte
  18660. can be dropped from a message if it's the same as the
  18661. first byte of the previous message, so this lets you
  18662. supply the byte to use if the first byte of the message
  18663. has in fact been dropped.
  18664. @param timeStamp the time to give the midi message - this value doesn't
  18665. use any particular units, so will be application-specific
  18666. */
  18667. MidiMessage (const uint8* data,
  18668. int size,
  18669. int& numBytesUsed,
  18670. uint8 lastStatusByte,
  18671. double timeStamp = 0) throw();
  18672. /** Creates a copy of another midi message. */
  18673. MidiMessage (const MidiMessage& other) throw();
  18674. /** Creates a copy of another midi message, with a different timestamp. */
  18675. MidiMessage (const MidiMessage& other,
  18676. const double newTimeStamp) throw();
  18677. /** Destructor. */
  18678. ~MidiMessage() throw();
  18679. /** Copies this message from another one. */
  18680. const MidiMessage& operator= (const MidiMessage& other) throw();
  18681. /** Returns a pointer to the raw midi data.
  18682. @see getRawDataSize
  18683. */
  18684. uint8* getRawData() const throw() { return data; }
  18685. /** Returns the number of bytes of data in the message.
  18686. @see getRawData
  18687. */
  18688. int getRawDataSize() const throw() { return size; }
  18689. /** Returns the timestamp associated with this message.
  18690. The units for the timestamp will be application-specific.
  18691. @see setTimeStamp, addToTimeStamp
  18692. */
  18693. double getTimeStamp() const throw() { return timeStamp; }
  18694. /** Changes the message's associated timestamp.
  18695. The units for the timestamp will be application-specific.
  18696. @see addToTimeStamp, getTimeStamp
  18697. */
  18698. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18699. /** Adds a value to the message's timestamp.
  18700. The units for the timestamp will be application-specific.
  18701. */
  18702. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18703. /** Returns the midi channel associated with the message.
  18704. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18705. if it's a sysex)
  18706. @see isForChannel, setChannel
  18707. */
  18708. int getChannel() const throw();
  18709. /** Returns true if the message applies to the given midi channel.
  18710. @param channelNumber the channel number to look for, in the range 1 to 16
  18711. @see getChannel, setChannel
  18712. */
  18713. bool isForChannel (const int channelNumber) const throw();
  18714. /** Changes the message's midi channel.
  18715. This won't do anything for non-channel messages like sysexes.
  18716. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18717. */
  18718. void setChannel (const int newChannelNumber) throw();
  18719. /** Returns true if this is a system-exclusive message.
  18720. */
  18721. bool isSysEx() const throw();
  18722. /** Returns a pointer to the sysex data inside the message.
  18723. If this event isn't a sysex event, it'll return 0.
  18724. @see getSysExDataSize
  18725. */
  18726. const uint8* getSysExData() const throw();
  18727. /** Returns the size of the sysex data.
  18728. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18729. @see getSysExData
  18730. */
  18731. int getSysExDataSize() const throw();
  18732. /** Returns true if this message is a 'key-down' event.
  18733. This will return false for a note-on event with a velocity of 0.
  18734. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18735. */
  18736. bool isNoteOn() const throw();
  18737. /** Creates a key-down message (using a floating-point velocity).
  18738. @param channel the midi channel, in the range 1 to 16
  18739. @param noteNumber the key number, 0 to 127
  18740. @param velocity in the range 0 to 1.0
  18741. @see isNoteOn
  18742. */
  18743. static const MidiMessage noteOn (const int channel,
  18744. const int noteNumber,
  18745. const float velocity) throw();
  18746. /** Creates a key-down message (using an integer velocity).
  18747. @param channel the midi channel, in the range 1 to 16
  18748. @param noteNumber the key number, 0 to 127
  18749. @param velocity in the range 0 to 127
  18750. @see isNoteOn
  18751. */
  18752. static const MidiMessage noteOn (const int channel,
  18753. const int noteNumber,
  18754. const uint8 velocity) throw();
  18755. /** Returns true if this message is a 'key-up' event.
  18756. This will also return true for a note-on event with a velocity of 0.
  18757. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18758. */
  18759. bool isNoteOff() const throw();
  18760. /** Creates a key-up message.
  18761. @param channel the midi channel, in the range 1 to 16
  18762. @param noteNumber the key number, 0 to 127
  18763. @see isNoteOff
  18764. */
  18765. static const MidiMessage noteOff (const int channel,
  18766. const int noteNumber) throw();
  18767. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18768. @see isNoteOn, isNoteOff
  18769. */
  18770. bool isNoteOnOrOff() const throw();
  18771. /** Returns the midi note number for note-on and note-off messages.
  18772. If the message isn't a note-on or off, the value returned will be
  18773. meaningless.
  18774. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18775. */
  18776. int getNoteNumber() const throw();
  18777. /** Changes the midi note number of a note-on or note-off message.
  18778. If the message isn't a note on or off, this will do nothing.
  18779. */
  18780. void setNoteNumber (const int newNoteNumber) throw();
  18781. /** Returns the velocity of a note-on or note-off message.
  18782. The value returned will be in the range 0 to 127.
  18783. If the message isn't a note-on or off event, it will return 0.
  18784. @see getFloatVelocity
  18785. */
  18786. uint8 getVelocity() const throw();
  18787. /** Returns the velocity of a note-on or note-off message.
  18788. The value returned will be in the range 0 to 1.0
  18789. If the message isn't a note-on or off event, it will return 0.
  18790. @see getVelocity, setVelocity
  18791. */
  18792. float getFloatVelocity() const throw();
  18793. /** Changes the velocity of a note-on or note-off message.
  18794. If the message isn't a note on or off, this will do nothing.
  18795. @param newVelocity the new velocity, in the range 0 to 1.0
  18796. @see getFloatVelocity, multiplyVelocity
  18797. */
  18798. void setVelocity (const float newVelocity) throw();
  18799. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18800. If the message isn't a note on or off, this will do nothing.
  18801. @param scaleFactor the value by which to multiply the velocity
  18802. @see setVelocity
  18803. */
  18804. void multiplyVelocity (const float scaleFactor) throw();
  18805. /** Returns true if the message is a program (patch) change message.
  18806. @see getProgramChangeNumber, getGMInstrumentName
  18807. */
  18808. bool isProgramChange() const throw();
  18809. /** Returns the new program number of a program change message.
  18810. If the message isn't a program change, the value returned will be
  18811. nonsense.
  18812. @see isProgramChange, getGMInstrumentName
  18813. */
  18814. int getProgramChangeNumber() const throw();
  18815. /** Creates a program-change message.
  18816. @param channel the midi channel, in the range 1 to 16
  18817. @param programNumber the midi program number, 0 to 127
  18818. @see isProgramChange, getGMInstrumentName
  18819. */
  18820. static const MidiMessage programChange (const int channel,
  18821. const int programNumber) throw();
  18822. /** Returns true if the message is a pitch-wheel move.
  18823. @see getPitchWheelValue, pitchWheel
  18824. */
  18825. bool isPitchWheel() const throw();
  18826. /** Returns the pitch wheel position from a pitch-wheel move message.
  18827. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18828. If called for messages which aren't pitch wheel events, the number returned will be
  18829. nonsense.
  18830. @see isPitchWheel
  18831. */
  18832. int getPitchWheelValue() const throw();
  18833. /** Creates a pitch-wheel move message.
  18834. @param channel the midi channel, in the range 1 to 16
  18835. @param position the wheel position, in the range 0 to 16383
  18836. @see isPitchWheel
  18837. */
  18838. static const MidiMessage pitchWheel (const int channel,
  18839. const int position) throw();
  18840. /** Returns true if the message is an aftertouch event.
  18841. For aftertouch events, use the getNoteNumber() method to find out the key
  18842. that it applies to, and getAftertouchValue() to find out the amount. Use
  18843. getChannel() to find out the channel.
  18844. @see getAftertouchValue, getNoteNumber
  18845. */
  18846. bool isAftertouch() const throw();
  18847. /** Returns the amount of aftertouch from an aftertouch messages.
  18848. The value returned is in the range 0 to 127, and will be nonsense for messages
  18849. other than aftertouch messages.
  18850. @see isAftertouch
  18851. */
  18852. int getAfterTouchValue() const throw();
  18853. /** Creates an aftertouch message.
  18854. @param channel the midi channel, in the range 1 to 16
  18855. @param noteNumber the key number, 0 to 127
  18856. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18857. @see isAftertouch
  18858. */
  18859. static const MidiMessage aftertouchChange (const int channel,
  18860. const int noteNumber,
  18861. const int aftertouchAmount) throw();
  18862. /** Returns true if the message is a channel-pressure change event.
  18863. This is like aftertouch, but common to the whole channel rather than a specific
  18864. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18865. to find out the channel.
  18866. @see channelPressureChange
  18867. */
  18868. bool isChannelPressure() const throw();
  18869. /** Returns the pressure from a channel pressure change message.
  18870. @returns the pressure, in the range 0 to 127
  18871. @see isChannelPressure, channelPressureChange
  18872. */
  18873. int getChannelPressureValue() const throw();
  18874. /** Creates a channel-pressure change event.
  18875. @param channel the midi channel: 1 to 16
  18876. @param pressure the pressure, 0 to 127
  18877. @see isChannelPressure
  18878. */
  18879. static const MidiMessage channelPressureChange (const int channel,
  18880. const int pressure) throw();
  18881. /** Returns true if this is a midi controller message.
  18882. @see getControllerNumber, getControllerValue, controllerEvent
  18883. */
  18884. bool isController() const throw();
  18885. /** Returns the controller number of a controller message.
  18886. The name of the controller can be looked up using the getControllerName() method.
  18887. Note that the value returned is invalid for messages that aren't controller changes.
  18888. @see isController, getControllerName, getControllerValue
  18889. */
  18890. int getControllerNumber() const throw();
  18891. /** Returns the controller value from a controller message.
  18892. A value 0 to 127 is returned to indicate the new controller position.
  18893. Note that the value returned is invalid for messages that aren't controller changes.
  18894. @see isController, getControllerNumber
  18895. */
  18896. int getControllerValue() const throw();
  18897. /** Creates a controller message.
  18898. @param channel the midi channel, in the range 1 to 16
  18899. @param controllerType the type of controller
  18900. @param value the controller value
  18901. @see isController
  18902. */
  18903. static const MidiMessage controllerEvent (const int channel,
  18904. const int controllerType,
  18905. const int value) throw();
  18906. /** Checks whether this message is an all-notes-off message.
  18907. @see allNotesOff
  18908. */
  18909. bool isAllNotesOff() const throw();
  18910. /** Checks whether this message is an all-sound-off message.
  18911. @see allSoundOff
  18912. */
  18913. bool isAllSoundOff() const throw();
  18914. /** Creates an all-notes-off message.
  18915. @param channel the midi channel, in the range 1 to 16
  18916. @see isAllNotesOff
  18917. */
  18918. static const MidiMessage allNotesOff (const int channel) throw();
  18919. /** Creates an all-sound-off message.
  18920. @param channel the midi channel, in the range 1 to 16
  18921. @see isAllSoundOff
  18922. */
  18923. static const MidiMessage allSoundOff (const int channel) throw();
  18924. /** Creates an all-controllers-off message.
  18925. @param channel the midi channel, in the range 1 to 16
  18926. */
  18927. static const MidiMessage allControllersOff (const int channel) throw();
  18928. /** Returns true if this event is a meta-event.
  18929. Meta-events are things like tempo changes, track names, etc.
  18930. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18931. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18932. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18933. */
  18934. bool isMetaEvent() const throw();
  18935. /** Returns a meta-event's type number.
  18936. If the message isn't a meta-event, this will return -1.
  18937. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18938. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18939. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18940. */
  18941. int getMetaEventType() const throw();
  18942. /** Returns a pointer to the data in a meta-event.
  18943. @see isMetaEvent, getMetaEventLength
  18944. */
  18945. const uint8* getMetaEventData() const throw();
  18946. /** Returns the length of the data for a meta-event.
  18947. @see isMetaEvent, getMetaEventData
  18948. */
  18949. int getMetaEventLength() const throw();
  18950. /** Returns true if this is a 'track' meta-event. */
  18951. bool isTrackMetaEvent() const throw();
  18952. /** Returns true if this is an 'end-of-track' meta-event. */
  18953. bool isEndOfTrackMetaEvent() const throw();
  18954. /** Creates an end-of-track meta-event.
  18955. @see isEndOfTrackMetaEvent
  18956. */
  18957. static const MidiMessage endOfTrack() throw();
  18958. /** Returns true if this is an 'track name' meta-event.
  18959. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18960. */
  18961. bool isTrackNameEvent() const throw();
  18962. /** Returns true if this is a 'text' meta-event.
  18963. @see getTextFromTextMetaEvent
  18964. */
  18965. bool isTextMetaEvent() const throw();
  18966. /** Returns the text from a text meta-event.
  18967. @see isTextMetaEvent
  18968. */
  18969. const String getTextFromTextMetaEvent() const throw();
  18970. /** Returns true if this is a 'tempo' meta-event.
  18971. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18972. */
  18973. bool isTempoMetaEvent() const throw();
  18974. /** Returns the tick length from a tempo meta-event.
  18975. @param timeFormat the 16-bit time format value from the midi file's header.
  18976. @returns the tick length (in seconds).
  18977. @see isTempoMetaEvent
  18978. */
  18979. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18980. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18981. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18982. */
  18983. double getTempoSecondsPerQuarterNote() const throw();
  18984. /** Creates a tempo meta-event.
  18985. @see isTempoMetaEvent
  18986. */
  18987. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18988. /** Returns true if this is a 'time-signature' meta-event.
  18989. @see getTimeSignatureInfo
  18990. */
  18991. bool isTimeSignatureMetaEvent() const throw();
  18992. /** Returns the time-signature values from a time-signature meta-event.
  18993. @see isTimeSignatureMetaEvent
  18994. */
  18995. void getTimeSignatureInfo (int& numerator,
  18996. int& denominator) const throw();
  18997. /** Creates a time-signature meta-event.
  18998. @see isTimeSignatureMetaEvent
  18999. */
  19000. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  19001. const int denominator) throw();
  19002. /** Returns true if this is a 'key-signature' meta-event.
  19003. @see getKeySignatureNumberOfSharpsOrFlats
  19004. */
  19005. bool isKeySignatureMetaEvent() const throw();
  19006. /** Returns the key from a key-signature meta-event.
  19007. @see isKeySignatureMetaEvent
  19008. */
  19009. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  19010. /** Returns true if this is a 'channel' meta-event.
  19011. A channel meta-event specifies the midi channel that should be used
  19012. for subsequent meta-events.
  19013. @see getMidiChannelMetaEventChannel
  19014. */
  19015. bool isMidiChannelMetaEvent() const throw();
  19016. /** Returns the channel number from a channel meta-event.
  19017. @returns the channel, in the range 1 to 16.
  19018. @see isMidiChannelMetaEvent
  19019. */
  19020. int getMidiChannelMetaEventChannel() const throw();
  19021. /** Creates a midi channel meta-event.
  19022. @param channel the midi channel, in the range 1 to 16
  19023. @see isMidiChannelMetaEvent
  19024. */
  19025. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  19026. /** Returns true if this is an active-sense message. */
  19027. bool isActiveSense() const throw();
  19028. /** Returns true if this is a midi start event.
  19029. @see midiStart
  19030. */
  19031. bool isMidiStart() const throw();
  19032. /** Creates a midi start event. */
  19033. static const MidiMessage midiStart() throw();
  19034. /** Returns true if this is a midi continue event.
  19035. @see midiContinue
  19036. */
  19037. bool isMidiContinue() const throw();
  19038. /** Creates a midi continue event. */
  19039. static const MidiMessage midiContinue() throw();
  19040. /** Returns true if this is a midi stop event.
  19041. @see midiStop
  19042. */
  19043. bool isMidiStop() const throw();
  19044. /** Creates a midi stop event. */
  19045. static const MidiMessage midiStop() throw();
  19046. /** Returns true if this is a midi clock event.
  19047. @see midiClock, songPositionPointer
  19048. */
  19049. bool isMidiClock() const throw();
  19050. /** Creates a midi clock event. */
  19051. static const MidiMessage midiClock() throw();
  19052. /** Returns true if this is a song-position-pointer message.
  19053. @see getSongPositionPointerMidiBeat, songPositionPointer
  19054. */
  19055. bool isSongPositionPointer() const throw();
  19056. /** Returns the midi beat-number of a song-position-pointer message.
  19057. @see isSongPositionPointer, songPositionPointer
  19058. */
  19059. int getSongPositionPointerMidiBeat() const throw();
  19060. /** Creates a song-position-pointer message.
  19061. The position is a number of midi beats from the start of the song, where 1 midi
  19062. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  19063. are 4 midi beats in a quarter-note.
  19064. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  19065. */
  19066. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  19067. /** Returns true if this is a quarter-frame midi timecode message.
  19068. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  19069. */
  19070. bool isQuarterFrame() const throw();
  19071. /** Returns the sequence number of a quarter-frame midi timecode message.
  19072. This will be a value between 0 and 7.
  19073. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  19074. */
  19075. int getQuarterFrameSequenceNumber() const throw();
  19076. /** Returns the value from a quarter-frame message.
  19077. This will be the lower nybble of the message's data-byte, a value
  19078. between 0 and 15
  19079. */
  19080. int getQuarterFrameValue() const throw();
  19081. /** Creates a quarter-frame MTC message.
  19082. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  19083. @param value a value 0 to 15 for the lower nybble of the message's data byte
  19084. */
  19085. static const MidiMessage quarterFrame (const int sequenceNumber,
  19086. const int value) throw();
  19087. /** SMPTE timecode types.
  19088. Used by the getFullFrameParameters() and fullFrame() methods.
  19089. */
  19090. enum SmpteTimecodeType
  19091. {
  19092. fps24 = 0,
  19093. fps25 = 1,
  19094. fps30drop = 2,
  19095. fps30 = 3
  19096. };
  19097. /** Returns true if this is a full-frame midi timecode message.
  19098. */
  19099. bool isFullFrame() const throw();
  19100. /** Extracts the timecode information from a full-frame midi timecode message.
  19101. You should only call this on messages where you've used isFullFrame() to
  19102. check that they're the right kind.
  19103. */
  19104. void getFullFrameParameters (int& hours,
  19105. int& minutes,
  19106. int& seconds,
  19107. int& frames,
  19108. SmpteTimecodeType& timecodeType) const throw();
  19109. /** Creates a full-frame MTC message.
  19110. */
  19111. static const MidiMessage fullFrame (const int hours,
  19112. const int minutes,
  19113. const int seconds,
  19114. const int frames,
  19115. SmpteTimecodeType timecodeType);
  19116. /** Types of MMC command.
  19117. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  19118. */
  19119. enum MidiMachineControlCommand
  19120. {
  19121. mmc_stop = 1,
  19122. mmc_play = 2,
  19123. mmc_deferredplay = 3,
  19124. mmc_fastforward = 4,
  19125. mmc_rewind = 5,
  19126. mmc_recordStart = 6,
  19127. mmc_recordStop = 7,
  19128. mmc_pause = 9
  19129. };
  19130. /** Checks whether this is an MMC message.
  19131. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  19132. */
  19133. bool isMidiMachineControlMessage() const throw();
  19134. /** For an MMC message, this returns its type.
  19135. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  19136. calling this method.
  19137. */
  19138. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  19139. /** Creates an MMC message.
  19140. */
  19141. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  19142. /** Checks whether this is an MMC "goto" message.
  19143. If it is, the parameters passed-in are set to the time that the message contains.
  19144. @see midiMachineControlGoto
  19145. */
  19146. bool isMidiMachineControlGoto (int& hours,
  19147. int& minutes,
  19148. int& seconds,
  19149. int& frames) const throw();
  19150. /** Creates an MMC "goto" message.
  19151. This messages tells the device to go to a specific frame.
  19152. @see isMidiMachineControlGoto
  19153. */
  19154. static const MidiMessage midiMachineControlGoto (int hours,
  19155. int minutes,
  19156. int seconds,
  19157. int frames);
  19158. /** Creates a master-volume change message.
  19159. @param volume the volume, 0 to 1.0
  19160. */
  19161. static const MidiMessage masterVolume (const float volume) throw();
  19162. /** Creates a system-exclusive message.
  19163. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19164. */
  19165. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19166. const int dataSize) throw();
  19167. /** Reads a midi variable-length integer.
  19168. @param data the data to read the number from
  19169. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19170. */
  19171. static int readVariableLengthVal (const uint8* data,
  19172. int& numBytesUsed) throw();
  19173. /** Based on the first byte of a short midi message, this uses a lookup table
  19174. to return the message length (either 1, 2, or 3 bytes).
  19175. The value passed in must be 0x80 or higher.
  19176. */
  19177. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19178. /** Returns the name of a midi note number.
  19179. E.g "C", "D#", etc.
  19180. @param noteNumber the midi note number, 0 to 127
  19181. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19182. they'll be flattened, e.g. "Db"
  19183. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19184. e.g. "C#4"
  19185. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19186. number that will be used for middle C's octave
  19187. @see getMidiNoteInHertz
  19188. */
  19189. static const String getMidiNoteName (int noteNumber,
  19190. bool useSharps,
  19191. bool includeOctaveNumber,
  19192. int octaveNumForMiddleC) throw();
  19193. /** Returns the frequency of a midi note number.
  19194. @see getMidiNoteName
  19195. */
  19196. static const double getMidiNoteInHertz (int noteNumber) throw();
  19197. /** Returns the standard name of a GM instrument.
  19198. @param midiInstrumentNumber the program number 0 to 127
  19199. @see getProgramChangeNumber
  19200. */
  19201. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19202. /** Returns the name of a bank of GM instruments.
  19203. @param midiBankNumber the bank, 0 to 15
  19204. */
  19205. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19206. /** Returns the standard name of a channel 10 percussion sound.
  19207. @param midiNoteNumber the key number, 35 to 81
  19208. */
  19209. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19210. /** Returns the name of a controller type number.
  19211. @see getControllerNumber
  19212. */
  19213. static const String getControllerName (int controllerNumber) throw();
  19214. juce_UseDebuggingNewOperator
  19215. private:
  19216. double timeStamp;
  19217. uint8* data;
  19218. int message, size;
  19219. };
  19220. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19221. /********* End of inlined file: juce_MidiMessage.h *********/
  19222. /**
  19223. Holds a sequence of time-stamped midi events.
  19224. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19225. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19226. @see MidiMessage
  19227. */
  19228. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19229. {
  19230. public:
  19231. /** Creates an empty MidiBuffer. */
  19232. MidiBuffer() throw();
  19233. /** Creates a copy of another MidiBuffer. */
  19234. MidiBuffer (const MidiBuffer& other) throw();
  19235. /** Makes a copy of another MidiBuffer. */
  19236. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19237. /** Destructor */
  19238. ~MidiBuffer() throw();
  19239. /** Removes all events from the buffer. */
  19240. void clear() throw();
  19241. /** Removes all events between two times from the buffer.
  19242. All events for which (start <= event position < start + numSamples) will
  19243. be removed.
  19244. */
  19245. void clear (const int start,
  19246. const int numSamples) throw();
  19247. /** Returns true if the buffer is empty.
  19248. To actually retrieve the events, use a MidiBuffer::Iterator object
  19249. */
  19250. bool isEmpty() const throw();
  19251. /** Counts the number of events in the buffer.
  19252. This is actually quite a slow operation, as it has to iterate through all
  19253. the events, so you might prefer to call isEmpty() if that's all you need
  19254. to know.
  19255. */
  19256. int getNumEvents() const throw();
  19257. /** Adds an event to the buffer.
  19258. The sample number will be used to determine the position of the event in
  19259. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19260. ignored.
  19261. If an event is added whose sample position is the same as one or more events
  19262. already in the buffer, the new event will be placed after the existing ones.
  19263. To retrieve events, use a MidiBuffer::Iterator object
  19264. */
  19265. void addEvent (const MidiMessage& midiMessage,
  19266. const int sampleNumber) throw();
  19267. /** Adds an event to the buffer from raw midi data.
  19268. The sample number will be used to determine the position of the event in
  19269. the buffer, which is always kept sorted.
  19270. If an event is added whose sample position is the same as one or more events
  19271. already in the buffer, the new event will be placed after the existing ones.
  19272. The event data will be inspected to calculate the number of bytes in length that
  19273. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19274. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19275. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19276. add an event at all.
  19277. To retrieve events, use a MidiBuffer::Iterator object
  19278. */
  19279. void addEvent (const uint8* const rawMidiData,
  19280. const int maxBytesOfMidiData,
  19281. const int sampleNumber) throw();
  19282. /** Adds some events from another buffer to this one.
  19283. @param otherBuffer the buffer containing the events you want to add
  19284. @param startSample the lowest sample number in the source buffer for which
  19285. events should be added. Any source events whose timestamp is
  19286. less than this will be ignored
  19287. @param numSamples the valid range of samples from the source buffer for which
  19288. events should be added - i.e. events in the source buffer whose
  19289. timestamp is greater than or equal to (startSample + numSamples)
  19290. will be ignored. If this value is less than 0, all events after
  19291. startSample will be taken.
  19292. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19293. that are added to this buffer
  19294. */
  19295. void addEvents (const MidiBuffer& otherBuffer,
  19296. const int startSample,
  19297. const int numSamples,
  19298. const int sampleDeltaToAdd) throw();
  19299. /** Returns the sample number of the first event in the buffer.
  19300. If the buffer's empty, this will just return 0.
  19301. */
  19302. int getFirstEventTime() const throw();
  19303. /** Returns the sample number of the last event in the buffer.
  19304. If the buffer's empty, this will just return 0.
  19305. */
  19306. int getLastEventTime() const throw();
  19307. /**
  19308. Used to iterate through the events in a MidiBuffer.
  19309. Note that altering the buffer while an iterator is using it isn't a
  19310. safe operation.
  19311. @see MidiBuffer
  19312. */
  19313. class Iterator
  19314. {
  19315. public:
  19316. /** Creates an Iterator for this MidiBuffer. */
  19317. Iterator (const MidiBuffer& buffer) throw();
  19318. /** Destructor. */
  19319. ~Iterator() throw();
  19320. /** Repositions the iterator so that the next event retrieved will be the first
  19321. one whose sample position is at greater than or equal to the given position.
  19322. */
  19323. void setNextSamplePosition (const int samplePosition) throw();
  19324. /** Retrieves a copy of the next event from the buffer.
  19325. @param result on return, this will be the message (the MidiMessage's timestamp
  19326. is not set)
  19327. @param samplePosition on return, this will be the position of the event
  19328. @returns true if an event was found, or false if the iterator has reached
  19329. the end of the buffer
  19330. */
  19331. bool getNextEvent (MidiMessage& result,
  19332. int& samplePosition) throw();
  19333. /** Retrieves the next event from the buffer.
  19334. @param midiData on return, this pointer will be set to a block of data containing
  19335. the midi message. Note that to make it fast, this is a pointer
  19336. directly into the MidiBuffer's internal data, so is only valid
  19337. temporarily until the MidiBuffer is altered.
  19338. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19339. midi message
  19340. @param samplePosition on return, this will be the position of the event
  19341. @returns true if an event was found, or false if the iterator has reached
  19342. the end of the buffer
  19343. */
  19344. bool getNextEvent (const uint8* &midiData,
  19345. int& numBytesOfMidiData,
  19346. int& samplePosition) throw();
  19347. juce_UseDebuggingNewOperator
  19348. private:
  19349. const MidiBuffer& buffer;
  19350. const uint8* data;
  19351. Iterator (const Iterator&);
  19352. const Iterator& operator= (const Iterator&);
  19353. };
  19354. juce_UseDebuggingNewOperator
  19355. private:
  19356. friend class MidiBuffer::Iterator;
  19357. int bytesUsed;
  19358. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19359. };
  19360. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19361. /********* End of inlined file: juce_MidiBuffer.h *********/
  19362. #endif
  19363. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19364. /********* Start of inlined file: juce_MidiFile.h *********/
  19365. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19366. #define __JUCE_MIDIFILE_JUCEHEADER__
  19367. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19368. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19369. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19370. /**
  19371. A sequence of timestamped midi messages.
  19372. This allows the sequence to be manipulated, and also to be read from and
  19373. written to a standard midi file.
  19374. @see MidiMessage, MidiFile
  19375. */
  19376. class JUCE_API MidiMessageSequence
  19377. {
  19378. public:
  19379. /** Creates an empty midi sequence object. */
  19380. MidiMessageSequence();
  19381. /** Creates a copy of another sequence. */
  19382. MidiMessageSequence (const MidiMessageSequence& other);
  19383. /** Replaces this sequence with another one. */
  19384. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19385. /** Destructor. */
  19386. ~MidiMessageSequence();
  19387. /** Structure used to hold midi events in the sequence.
  19388. These structures act as 'handles' on the events as they are moved about in
  19389. the list, and make it quick to find the matching note-offs for note-on events.
  19390. @see MidiMessageSequence::getEventPointer
  19391. */
  19392. class MidiEventHolder
  19393. {
  19394. public:
  19395. /** Destructor. */
  19396. ~MidiEventHolder();
  19397. /** The message itself, whose timestamp is used to specify the event's time.
  19398. */
  19399. MidiMessage message;
  19400. /** The matching note-off event (if this is a note-on event).
  19401. If this isn't a note-on, this pointer will be null.
  19402. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19403. note-offs up-to-date after events have been moved around in the sequence
  19404. or deleted.
  19405. */
  19406. MidiEventHolder* noteOffObject;
  19407. juce_UseDebuggingNewOperator
  19408. private:
  19409. friend class MidiMessageSequence;
  19410. MidiEventHolder (const MidiMessage& message);
  19411. };
  19412. /** Clears the sequence. */
  19413. void clear();
  19414. /** Returns the number of events in the sequence. */
  19415. int getNumEvents() const;
  19416. /** Returns a pointer to one of the events. */
  19417. MidiEventHolder* getEventPointer (const int index) const;
  19418. /** Returns the time of the note-up that matches the note-on at this index.
  19419. If the event at this index isn't a note-on, it'll just return 0.
  19420. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19421. */
  19422. double getTimeOfMatchingKeyUp (const int index) const;
  19423. /** Returns the index of the note-up that matches the note-on at this index.
  19424. If the event at this index isn't a note-on, it'll just return -1.
  19425. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19426. */
  19427. int getIndexOfMatchingKeyUp (const int index) const;
  19428. /** Returns the index of an event. */
  19429. int getIndexOf (MidiEventHolder* const event) const;
  19430. /** Returns the index of the first event on or after the given timestamp.
  19431. If the time is beyond the end of the sequence, this will return the
  19432. number of events.
  19433. */
  19434. int getNextIndexAtTime (const double timeStamp) const;
  19435. /** Returns the timestamp of the first event in the sequence.
  19436. @see getEndTime
  19437. */
  19438. double getStartTime() const;
  19439. /** Returns the timestamp of the last event in the sequence.
  19440. @see getStartTime
  19441. */
  19442. double getEndTime() const;
  19443. /** Returns the timestamp of the event at a given index.
  19444. If the index is out-of-range, this will return 0.0
  19445. */
  19446. double getEventTime (const int index) const;
  19447. /** Inserts a midi message into the sequence.
  19448. The index at which the new message gets inserted will depend on its timestamp,
  19449. because the sequence is kept sorted.
  19450. Remember to call updateMatchedPairs() after adding note-on events.
  19451. @param newMessage the new message to add (an internal copy will be made)
  19452. @param timeAdjustment an optional value to add to the timestamp of the message
  19453. that will be inserted
  19454. @see updateMatchedPairs
  19455. */
  19456. void addEvent (const MidiMessage& newMessage,
  19457. double timeAdjustment = 0);
  19458. /** Deletes one of the events in the sequence.
  19459. Remember to call updateMatchedPairs() after removing events.
  19460. @param index the index of the event to delete
  19461. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19462. if the event you're removing is a note-on
  19463. */
  19464. void deleteEvent (const int index,
  19465. const bool deleteMatchingNoteUp);
  19466. /** Merges another sequence into this one.
  19467. Remember to call updateMatchedPairs() after using this method.
  19468. @param other the sequence to add from
  19469. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19470. as they are read from the other sequence
  19471. @param firstAllowableDestTime events will not be added if their time is earlier
  19472. than this time. (This is after their time has been adjusted
  19473. by the timeAdjustmentDelta)
  19474. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19475. or greater than this time. (This is after their time has
  19476. been adjusted by the timeAdjustmentDelta)
  19477. */
  19478. void addSequence (const MidiMessageSequence& other,
  19479. double timeAdjustmentDelta,
  19480. double firstAllowableDestTime,
  19481. double endOfAllowableDestTimes);
  19482. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19483. Call this after moving messages about or deleting/adding messages, and it
  19484. will scan the list and make sure all the note-offs in the MidiEventHolder
  19485. structures are pointing at the correct ones.
  19486. */
  19487. void updateMatchedPairs();
  19488. /** Copies all the messages for a particular midi channel to another sequence.
  19489. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19490. @param destSequence the sequence that the chosen events should be copied to
  19491. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19492. channel) will also be copied across.
  19493. @see extractSysExMessages
  19494. */
  19495. void extractMidiChannelMessages (const int channelNumberToExtract,
  19496. MidiMessageSequence& destSequence,
  19497. const bool alsoIncludeMetaEvents) const;
  19498. /** Copies all midi sys-ex messages to another sequence.
  19499. @param destSequence this is the sequence to which any sys-exes in this sequence
  19500. will be added
  19501. @see extractMidiChannelMessages
  19502. */
  19503. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19504. /** Removes any messages in this sequence that have a specific midi channel.
  19505. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19506. */
  19507. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19508. /** Removes any sys-ex messages from this sequence.
  19509. */
  19510. void deleteSysExMessages();
  19511. /** Adds an offset to the timestamps of all events in the sequence.
  19512. @param deltaTime the amount to add to each timestamp.
  19513. */
  19514. void addTimeToMessages (const double deltaTime);
  19515. /** Scans through the sequence to determine the state of any midi controllers at
  19516. a given time.
  19517. This will create a sequence of midi controller changes that can be
  19518. used to set all midi controllers to the state they would be in at the
  19519. specified time within this sequence.
  19520. As well as controllers, it will also recreate the midi program number
  19521. and pitch bend position.
  19522. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19523. for other channels will be ignored.
  19524. @param time the time at which you want to find out the state - there are
  19525. no explicit units for this time measurement, it's the same units
  19526. as used for the timestamps of the messages
  19527. @param resultMessages an array to which midi controller-change messages will be added. This
  19528. will be the minimum number of controller changes to recreate the
  19529. state at the required time.
  19530. */
  19531. void createControllerUpdatesForTime (const int channelNumber,
  19532. const double time,
  19533. OwnedArray<MidiMessage>& resultMessages);
  19534. juce_UseDebuggingNewOperator
  19535. /** @internal */
  19536. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19537. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19538. private:
  19539. friend class MidiComparator;
  19540. friend class MidiFile;
  19541. OwnedArray <MidiEventHolder> list;
  19542. void sort();
  19543. };
  19544. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19545. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19546. /**
  19547. Reads/writes standard midi format files.
  19548. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19549. can then get the individual midi tracks from it using the getTrack() method.
  19550. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19551. to it using the addTrack() method, and then call its writeTo() method to stream
  19552. it out.
  19553. @see MidiMessageSequence
  19554. */
  19555. class JUCE_API MidiFile
  19556. {
  19557. public:
  19558. /** Creates an empty MidiFile object.
  19559. */
  19560. MidiFile() throw();
  19561. /** Destructor. */
  19562. ~MidiFile() throw();
  19563. /** Returns the number of tracks in the file.
  19564. @see getTrack, addTrack
  19565. */
  19566. int getNumTracks() const throw();
  19567. /** Returns a pointer to one of the tracks in the file.
  19568. @returns a pointer to the track, or 0 if the index is out-of-range
  19569. @see getNumTracks, addTrack
  19570. */
  19571. const MidiMessageSequence* getTrack (const int index) const throw();
  19572. /** Adds a midi track to the file.
  19573. This will make its own internal copy of the sequence that is passed-in.
  19574. @see getNumTracks, getTrack
  19575. */
  19576. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19577. /** Removes all midi tracks from the file.
  19578. @see getNumTracks
  19579. */
  19580. void clear() throw();
  19581. /** Returns the raw time format code that will be written to a stream.
  19582. After reading a midi file, this method will return the time-format that
  19583. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19584. or setSmpteTimeFormat() methods.
  19585. If the value returned is positive, it indicates the number of midi ticks
  19586. per quarter-note - see setTicksPerQuarterNote().
  19587. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19588. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19589. */
  19590. short getTimeFormat() const throw();
  19591. /** Sets the time format to use when this file is written to a stream.
  19592. If this is called, the file will be written as bars/beats using the
  19593. specified resolution, rather than SMPTE absolute times, as would be
  19594. used if setSmpteTimeFormat() had been called instead.
  19595. @param ticksPerQuarterNote e.g. 96, 960
  19596. @see setSmpteTimeFormat
  19597. */
  19598. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19599. /** Sets the time format to use when this file is written to a stream.
  19600. If this is called, the file will be written using absolute times, rather
  19601. than bars/beats as would be the case if setTicksPerBeat() had been called
  19602. instead.
  19603. @param framesPerSecond must be 24, 25, 29 or 30
  19604. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19605. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19606. timing, setSmpteTimeFormat (25, 40)
  19607. @see setTicksPerBeat
  19608. */
  19609. void setSmpteTimeFormat (const int framesPerSecond,
  19610. const int subframeResolution) throw();
  19611. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19612. Useful for finding the positions of all the tempo changes in a file.
  19613. @param tempoChangeEvents a list to which all the events will be added
  19614. */
  19615. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19616. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19617. Useful for finding the positions of all the tempo changes in a file.
  19618. @param timeSigEvents a list to which all the events will be added
  19619. */
  19620. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19621. /** Returns the latest timestamp in any of the tracks.
  19622. (Useful for finding the length of the file).
  19623. */
  19624. double getLastTimestamp() const;
  19625. /** Reads a midi file format stream.
  19626. After calling this, you can get the tracks that were read from the file by using the
  19627. getNumTracks() and getTrack() methods.
  19628. The timestamps of the midi events in the tracks will represent their positions in
  19629. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19630. method.
  19631. @returns true if the stream was read successfully
  19632. */
  19633. bool readFrom (InputStream& sourceStream);
  19634. /** Writes the midi tracks as a standard midi file.
  19635. @returns true if the operation succeeded.
  19636. */
  19637. bool writeTo (OutputStream& destStream);
  19638. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19639. This will use the midi time format and tempo/time signature info in the
  19640. tracks to convert all the timestamps to absolute values in seconds.
  19641. */
  19642. void convertTimestampTicksToSeconds();
  19643. juce_UseDebuggingNewOperator
  19644. /** @internal */
  19645. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19646. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19647. private:
  19648. MidiMessageSequence* tracks [128];
  19649. short numTracks, timeFormat;
  19650. MidiFile (const MidiFile&);
  19651. const MidiFile& operator= (const MidiFile&);
  19652. void readNextTrack (const char* data, int size);
  19653. void writeTrack (OutputStream& mainOut, const int trackNum);
  19654. };
  19655. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19656. /********* End of inlined file: juce_MidiFile.h *********/
  19657. #endif
  19658. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19659. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19660. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19661. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19662. class MidiKeyboardState;
  19663. /**
  19664. Receives events from a MidiKeyboardState object.
  19665. @see MidiKeyboardState
  19666. */
  19667. class JUCE_API MidiKeyboardStateListener
  19668. {
  19669. public:
  19670. MidiKeyboardStateListener() throw() {}
  19671. virtual ~MidiKeyboardStateListener() {}
  19672. /** Called when one of the MidiKeyboardState's keys is pressed.
  19673. This will be called synchronously when the state is either processing a
  19674. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19675. when a note is being played with its MidiKeyboardState::noteOn() method.
  19676. Note that this callback could happen from an audio callback thread, so be
  19677. careful not to block, and avoid any UI activity in the callback.
  19678. */
  19679. virtual void handleNoteOn (MidiKeyboardState* source,
  19680. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19681. /** Called when one of the MidiKeyboardState's keys is released.
  19682. This will be called synchronously when the state is either processing a
  19683. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19684. when a note is being played with its MidiKeyboardState::noteOff() method.
  19685. Note that this callback could happen from an audio callback thread, so be
  19686. careful not to block, and avoid any UI activity in the callback.
  19687. */
  19688. virtual void handleNoteOff (MidiKeyboardState* source,
  19689. int midiChannel, int midiNoteNumber) = 0;
  19690. };
  19691. /**
  19692. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19693. This object can parse a stream of midi events, using them to update its idea
  19694. of which keys are pressed for each individiual midi channel.
  19695. When keys go up or down, it can broadcast these events to listener objects.
  19696. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19697. methods, and midi messages for these events will be merged into the
  19698. midi stream that gets processed by processNextMidiBuffer().
  19699. */
  19700. class JUCE_API MidiKeyboardState
  19701. {
  19702. public:
  19703. MidiKeyboardState();
  19704. ~MidiKeyboardState();
  19705. /** Resets the state of the object.
  19706. All internal data for all the channels is reset, but no events are sent as a
  19707. result.
  19708. If you want to release any keys that are currently down, and to send out note-up
  19709. midi messages for this, use the allNotesOff() method instead.
  19710. */
  19711. void reset();
  19712. /** Returns true if the given midi key is currently held down for the given midi channel.
  19713. The channel number must be between 1 and 16. If you want to see if any notes are
  19714. on for a range of channels, use the isNoteOnForChannels() method.
  19715. */
  19716. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19717. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19718. The channel mask has a bit set for each midi channel you want to test for - bit
  19719. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19720. If a note is on for at least one of the specified channels, this returns true.
  19721. */
  19722. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19723. /** Turns a specified note on.
  19724. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19725. next call to processNextMidiBuffer().
  19726. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19727. gone down.
  19728. */
  19729. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19730. /** Turns a specified note off.
  19731. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19732. next call to processNextMidiBuffer().
  19733. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19734. gone up.
  19735. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19736. */
  19737. void noteOff (const int midiChannel, const int midiNoteNumber);
  19738. /** This will turn off any currently-down notes for the given midi channel.
  19739. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19740. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19741. and events being added to the midi stream.
  19742. */
  19743. void allNotesOff (const int midiChannel);
  19744. /** Looks at a key-up/down event and uses it to update the state of this object.
  19745. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19746. instead.
  19747. */
  19748. void processNextMidiEvent (const MidiMessage& message);
  19749. /** Scans a midi stream for up/down events and adds its own events to it.
  19750. This will look for any up/down events and use them to update the internal state,
  19751. synchronously making suitable callbacks to the listeners.
  19752. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19753. and noteOff() calls will be added into the buffer.
  19754. Only the section of the buffer whose timestamps are between startSample and
  19755. (startSample + numSamples) will be affected, and any events added will be placed
  19756. between these times.
  19757. If you're going to use this method, you'll need to keep calling it regularly for
  19758. it to work satisfactorily.
  19759. To process a single midi event at a time, use the processNextMidiEvent() method
  19760. instead.
  19761. */
  19762. void processNextMidiBuffer (MidiBuffer& buffer,
  19763. const int startSample,
  19764. const int numSamples,
  19765. const bool injectIndirectEvents);
  19766. /** Registers a listener for callbacks when keys go up or down.
  19767. @see removeListener
  19768. */
  19769. void addListener (MidiKeyboardStateListener* const listener) throw();
  19770. /** Deregisters a listener.
  19771. @see addListener
  19772. */
  19773. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19774. juce_UseDebuggingNewOperator
  19775. private:
  19776. CriticalSection lock;
  19777. uint16 noteStates [128];
  19778. MidiBuffer eventsToAdd;
  19779. VoidArray listeners;
  19780. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19781. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19782. MidiKeyboardState (const MidiKeyboardState&);
  19783. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19784. };
  19785. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19786. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19787. #endif
  19788. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19789. #endif
  19790. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19791. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19792. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19793. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19794. /********* Start of inlined file: juce_MidiInput.h *********/
  19795. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19796. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19797. class MidiInput;
  19798. /**
  19799. Receives midi messages from a midi input device.
  19800. This class is overridden to handle incoming midi messages. See the MidiInput
  19801. class for more details.
  19802. @see MidiInput
  19803. */
  19804. class JUCE_API MidiInputCallback
  19805. {
  19806. public:
  19807. /** Destructor. */
  19808. virtual ~MidiInputCallback() {}
  19809. /** Receives an incoming message.
  19810. A MidiInput object will call this method when a midi event arrives. It'll be
  19811. called on a high-priority system thread, so avoid doing anything time-consuming
  19812. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19813. for queueing incoming messages for use later.
  19814. @param source the MidiInput object that generated the message
  19815. @param message the incoming message. The message's timestamp is set to a value
  19816. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19817. time when the message arrived.
  19818. */
  19819. virtual void handleIncomingMidiMessage (MidiInput* source,
  19820. const MidiMessage& message) = 0;
  19821. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19822. If a long sysex message is broken up into multiple packets, this callback is made
  19823. for each packet that arrives until the message is finished, at which point
  19824. the normal handleIncomingMidiMessage() callback will be made with the entire
  19825. message.
  19826. The message passed in will contain the start of a sysex, but won't be finished
  19827. with the terminating 0xf7 byte.
  19828. */
  19829. virtual void handlePartialSysexMessage (MidiInput* source,
  19830. const uint8* messageData,
  19831. const int numBytesSoFar,
  19832. const double timestamp)
  19833. {
  19834. // (this bit is just to avoid compiler warnings about unused variables)
  19835. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19836. }
  19837. };
  19838. /**
  19839. Represents a midi input device.
  19840. To create one of these, use the static getDevices() method to find out what inputs are
  19841. available, and then use the openDevice() method to try to open one.
  19842. @see MidiOutput
  19843. */
  19844. class JUCE_API MidiInput
  19845. {
  19846. public:
  19847. /** Returns a list of the available midi input devices.
  19848. You can open one of the devices by passing its index into the
  19849. openDevice() method.
  19850. @see getDefaultDeviceIndex, openDevice
  19851. */
  19852. static const StringArray getDevices();
  19853. /** Returns the index of the default midi input device to use.
  19854. This refers to the index in the list returned by getDevices().
  19855. */
  19856. static int getDefaultDeviceIndex();
  19857. /** Tries to open one of the midi input devices.
  19858. This will return a MidiInput object if it manages to open it. You can then
  19859. call start() and stop() on this device, and delete it when no longer needed.
  19860. If the device can't be opened, this will return a null pointer.
  19861. @param deviceIndex the index of a device from the list returned by getDevices()
  19862. @param callback the object that will receive the midi messages from this device.
  19863. @see MidiInputCallback, getDevices
  19864. */
  19865. static MidiInput* openDevice (int deviceIndex,
  19866. MidiInputCallback* callback);
  19867. #if JUCE_LINUX || DOXYGEN
  19868. /** LINUX ONLY - This will try to create a new midi input device.
  19869. This will attempt to create a new midi input device with the specified name,
  19870. for other apps to connect to.
  19871. Returns 0 if a device can't be created.
  19872. @param deviceName the name to use for the new device
  19873. @param callback the object that will receive the midi messages from this device.
  19874. */
  19875. static MidiInput* createNewDevice (const String& deviceName,
  19876. MidiInputCallback* callback);
  19877. #endif
  19878. /** Destructor. */
  19879. virtual ~MidiInput();
  19880. /** Returns the name of this device.
  19881. */
  19882. virtual const String getName() const throw() { return name; }
  19883. /** Allows you to set a custom name for the device, in case you don't like the name
  19884. it was given when created.
  19885. */
  19886. virtual void setName (const String& newName) throw() { name = newName; }
  19887. /** Starts the device running.
  19888. After calling this, the device will start sending midi messages to the
  19889. MidiInputCallback object that was specified when the openDevice() method
  19890. was called.
  19891. @see stop
  19892. */
  19893. virtual void start();
  19894. /** Stops the device running.
  19895. @see start
  19896. */
  19897. virtual void stop();
  19898. juce_UseDebuggingNewOperator
  19899. protected:
  19900. String name;
  19901. void* internal;
  19902. MidiInput (const String& name);
  19903. MidiInput (const MidiInput&);
  19904. };
  19905. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19906. /********* End of inlined file: juce_MidiInput.h *********/
  19907. /**
  19908. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19909. processing by a block-based audio callback.
  19910. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19911. so it can easily use a midi input or keyboard component as its source.
  19912. @see MidiMessage, MidiInput
  19913. */
  19914. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19915. public MidiInputCallback
  19916. {
  19917. public:
  19918. /** Creates a MidiMessageCollector. */
  19919. MidiMessageCollector();
  19920. /** Destructor. */
  19921. ~MidiMessageCollector();
  19922. /** Clears any messages from the queue.
  19923. You need to call this method before starting to use the collector, so that
  19924. it knows the correct sample rate to use.
  19925. */
  19926. void reset (const double sampleRate);
  19927. /** Takes an incoming real-time message and adds it to the queue.
  19928. The message's timestamp is taken, and it will be ready for retrieval as part
  19929. of the block returned by the next call to removeNextBlockOfMessages().
  19930. This method is fully thread-safe when overlapping calls are made with
  19931. removeNextBlockOfMessages().
  19932. */
  19933. void addMessageToQueue (const MidiMessage& message);
  19934. /** Removes all the pending messages from the queue as a buffer.
  19935. This will also correct the messages' timestamps to make sure they're in
  19936. the range 0 to numSamples - 1.
  19937. This call should be made regularly by something like an audio processing
  19938. callback, because the time that it happens is used in calculating the
  19939. midi event positions.
  19940. This method is fully thread-safe when overlapping calls are made with
  19941. addMessageToQueue().
  19942. */
  19943. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19944. const int numSamples);
  19945. /** @internal */
  19946. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19947. /** @internal */
  19948. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19949. /** @internal */
  19950. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19951. juce_UseDebuggingNewOperator
  19952. private:
  19953. double lastCallbackTime;
  19954. CriticalSection midiCallbackLock;
  19955. MidiBuffer incomingMessages;
  19956. double sampleRate;
  19957. MidiMessageCollector (const MidiMessageCollector&);
  19958. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19959. };
  19960. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19961. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19962. #endif
  19963. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19964. #endif
  19965. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19966. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19967. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19968. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19969. /**
  19970. A set of routines to convert buffers of 32-bit floating point data to and from
  19971. various integer formats.
  19972. */
  19973. class JUCE_API AudioDataConverters
  19974. {
  19975. public:
  19976. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19977. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19978. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19979. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19980. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19981. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19982. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19983. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19984. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19985. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19986. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19987. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19988. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19989. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19990. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19991. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19992. enum DataFormat
  19993. {
  19994. int16LE,
  19995. int16BE,
  19996. int24LE,
  19997. int24BE,
  19998. int32LE,
  19999. int32BE,
  20000. float32LE,
  20001. float32BE,
  20002. };
  20003. static void convertFloatToFormat (const DataFormat destFormat,
  20004. const float* source, void* dest, int numSamples);
  20005. static void convertFormatToFloat (const DataFormat sourceFormat,
  20006. const void* source, float* dest, int numSamples);
  20007. static void interleaveSamples (const float** source, float* dest,
  20008. const int numSamples, const int numChannels);
  20009. static void deinterleaveSamples (const float* source, float** dest,
  20010. const int numSamples, const int numChannels);
  20011. };
  20012. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20013. /********* End of inlined file: juce_AudioDataConverters.h *********/
  20014. #endif
  20015. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20016. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20017. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20018. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20019. class AudioFormatReader;
  20020. class AudioFormatWriter;
  20021. /**
  20022. A multi-channel buffer of 32-bit floating point audio samples.
  20023. */
  20024. class JUCE_API AudioSampleBuffer
  20025. {
  20026. public:
  20027. /** Creates a buffer with a specified number of channels and samples.
  20028. The contents of the buffer will initially be undefined, so use clear() to
  20029. set all the samples to zero.
  20030. The buffer will allocate its memory internally, and this will be released
  20031. when the buffer is deleted.
  20032. */
  20033. AudioSampleBuffer (const int numChannels,
  20034. const int numSamples) throw();
  20035. /** Creates a buffer using a pre-allocated block of memory.
  20036. Note that if the buffer is resized or its number of channels is changed, it
  20037. will re-allocate memory internally and copy the existing data to this new area,
  20038. so it will then stop directly addressing this memory.
  20039. @param dataToReferTo a pre-allocated array containing pointers to the data
  20040. for each channel that should be used by this buffer. The
  20041. buffer will only refer to this memory, it won't try to delete
  20042. it when the buffer is deleted or resized.
  20043. @param numChannels the number of channels to use - this must correspond to the
  20044. number of elements in the array passed in
  20045. @param numSamples the number of samples to use - this must correspond to the
  20046. size of the arrays passed in
  20047. */
  20048. AudioSampleBuffer (float** dataToReferTo,
  20049. const int numChannels,
  20050. const int numSamples) throw();
  20051. /** Copies another buffer.
  20052. This buffer will make its own copy of the other's data, unless the buffer was created
  20053. using an external data buffer, in which case boths buffers will just point to the same
  20054. shared block of data.
  20055. */
  20056. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20057. /** Copies another buffer onto this one.
  20058. This buffer's size will be changed to that of the other buffer.
  20059. */
  20060. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20061. /** Destructor.
  20062. This will free any memory allocated by the buffer.
  20063. */
  20064. virtual ~AudioSampleBuffer() throw();
  20065. /** Returns the number of channels of audio data that this buffer contains.
  20066. @see getSampleData
  20067. */
  20068. int getNumChannels() const throw() { return numChannels; }
  20069. /** Returns the number of samples allocated in each of the buffer's channels.
  20070. @see getSampleData
  20071. */
  20072. int getNumSamples() const throw() { return size; }
  20073. /** Returns a pointer to a sample in one of the buffer's channels.
  20074. For speed, this doesn't check whether the channel and sample number
  20075. are legal, so be careful when using it!
  20076. */
  20077. float* getSampleData (const int channelNumber,
  20078. const int sampleOffset = 0) const throw();
  20079. /** Chages the buffer's size or number of channels.
  20080. This can expand or contract the buffer's length, and add or remove channels.
  20081. If keepExistingContent is true, it will try to preserve as much of the
  20082. old data as it can in the new buffer.
  20083. If clearExtraSpace is true, then any extra channels or space that is
  20084. allocated will be also be cleared. If false, then this space is left
  20085. uninitialised.
  20086. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20087. amount of memory that is currently allocated (but it will still increase it if
  20088. the new size is bigger than the amount it currently has). If this is false, then
  20089. a new allocation will be done so that the buffer uses takes up the minimum amount
  20090. of memory that it needs.
  20091. */
  20092. void setSize (const int newNumChannels,
  20093. const int newNumSamples,
  20094. const bool keepExistingContent = false,
  20095. const bool clearExtraSpace = false,
  20096. const bool avoidReallocating = false) throw();
  20097. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20098. There's also a constructor that lets you specify arrays like this, but this
  20099. lets you change the channels dynamically.
  20100. Note that if the buffer is resized or its number of channels is changed, it
  20101. will re-allocate memory internally and copy the existing data to this new area,
  20102. so it will then stop directly addressing this memory.
  20103. @param dataToReferTo a pre-allocated array containing pointers to the data
  20104. for each channel that should be used by this buffer. The
  20105. buffer will only refer to this memory, it won't try to delete
  20106. it when the buffer is deleted or resized.
  20107. @param numChannels the number of channels to use - this must correspond to the
  20108. number of elements in the array passed in
  20109. @param numSamples the number of samples to use - this must correspond to the
  20110. size of the arrays passed in
  20111. */
  20112. void setDataToReferTo (float** dataToReferTo,
  20113. const int numChannels,
  20114. const int numSamples) throw();
  20115. /** Clears all the samples in all channels. */
  20116. void clear() throw();
  20117. /** Clears a specified region of all the channels.
  20118. For speed, this doesn't check whether the channel and sample number
  20119. are in-range, so be careful!
  20120. */
  20121. void clear (const int startSample,
  20122. const int numSamples) throw();
  20123. /** Clears a specified region of just one channel.
  20124. For speed, this doesn't check whether the channel and sample number
  20125. are in-range, so be careful!
  20126. */
  20127. void clear (const int channel,
  20128. const int startSample,
  20129. const int numSamples) throw();
  20130. /** Applies a gain multiple to a region of one channel.
  20131. For speed, this doesn't check whether the channel and sample number
  20132. are in-range, so be careful!
  20133. */
  20134. void applyGain (const int channel,
  20135. const int startSample,
  20136. int numSamples,
  20137. const float gain) throw();
  20138. /** Applies a gain multiple to a region of all the channels.
  20139. For speed, this doesn't check whether the sample numbers
  20140. are in-range, so be careful!
  20141. */
  20142. void applyGain (const int startSample,
  20143. const int numSamples,
  20144. const float gain) throw();
  20145. /** Applies a range of gains to a region of a channel.
  20146. The gain that is applied to each sample will vary from
  20147. startGain on the first sample to endGain on the last Sample,
  20148. so it can be used to do basic fades.
  20149. For speed, this doesn't check whether the sample numbers
  20150. are in-range, so be careful!
  20151. */
  20152. void applyGainRamp (const int channel,
  20153. const int startSample,
  20154. int numSamples,
  20155. float startGain,
  20156. float endGain) throw();
  20157. /** Adds samples from another buffer to this one.
  20158. @param destChannel the channel within this buffer to add the samples to
  20159. @param destStartSample the start sample within this buffer's channel
  20160. @param source the source buffer to add from
  20161. @param sourceChannel the channel within the source buffer to read from
  20162. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20163. @param numSamples the number of samples to process
  20164. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20165. added to this buffer's samples
  20166. @see copyFrom
  20167. */
  20168. void addFrom (const int destChannel,
  20169. const int destStartSample,
  20170. const AudioSampleBuffer& source,
  20171. const int sourceChannel,
  20172. const int sourceStartSample,
  20173. int numSamples,
  20174. const float gainToApplyToSource = 1.0f) throw();
  20175. /** Adds samples from an array of floats to one of the channels.
  20176. @param destChannel the channel within this buffer to add the samples to
  20177. @param destStartSample the start sample within this buffer's channel
  20178. @param source the source data to use
  20179. @param numSamples the number of samples to process
  20180. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20181. added to this buffer's samples
  20182. @see copyFrom
  20183. */
  20184. void addFrom (const int destChannel,
  20185. const int destStartSample,
  20186. const float* source,
  20187. int numSamples,
  20188. const float gainToApplyToSource = 1.0f) throw();
  20189. /** Adds samples from an array of floats, applying a gain ramp to them.
  20190. @param destChannel the channel within this buffer to add the samples to
  20191. @param destStartSample the start sample within this buffer's channel
  20192. @param source the source data to use
  20193. @param numSamples the number of samples to process
  20194. @param startGain the gain to apply to the first sample (this is multiplied with
  20195. the source samples before they are added to this buffer)
  20196. @param endGain the gain to apply to the final sample. The gain is linearly
  20197. interpolated between the first and last samples.
  20198. */
  20199. void addFromWithRamp (const int destChannel,
  20200. const int destStartSample,
  20201. const float* source,
  20202. int numSamples,
  20203. float startGain,
  20204. float endGain) throw();
  20205. /** Copies samples from another buffer to this one.
  20206. @param destChannel the channel within this buffer to copy the samples to
  20207. @param destStartSample the start sample within this buffer's channel
  20208. @param source the source buffer to read from
  20209. @param sourceChannel the channel within the source buffer to read from
  20210. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20211. @param numSamples the number of samples to process
  20212. @see addFrom
  20213. */
  20214. void copyFrom (const int destChannel,
  20215. const int destStartSample,
  20216. const AudioSampleBuffer& source,
  20217. const int sourceChannel,
  20218. const int sourceStartSample,
  20219. int numSamples) throw();
  20220. /** Copies samples from an array of floats into one of the channels.
  20221. @param destChannel the channel within this buffer to copy the samples to
  20222. @param destStartSample the start sample within this buffer's channel
  20223. @param source the source buffer to read from
  20224. @param numSamples the number of samples to process
  20225. @see addFrom
  20226. */
  20227. void copyFrom (const int destChannel,
  20228. const int destStartSample,
  20229. const float* source,
  20230. int numSamples) throw();
  20231. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20232. @param destChannel the channel within this buffer to copy the samples to
  20233. @param destStartSample the start sample within this buffer's channel
  20234. @param source the source buffer to read from
  20235. @param numSamples the number of samples to process
  20236. @param gain the gain to apply
  20237. @see addFrom
  20238. */
  20239. void copyFrom (const int destChannel,
  20240. const int destStartSample,
  20241. const float* source,
  20242. int numSamples,
  20243. const float gain) throw();
  20244. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20245. @param destChannel the channel within this buffer to copy the samples to
  20246. @param destStartSample the start sample within this buffer's channel
  20247. @param source the source buffer to read from
  20248. @param numSamples the number of samples to process
  20249. @param startGain the gain to apply to the first sample (this is multiplied with
  20250. the source samples before they are copied to this buffer)
  20251. @param endGain the gain to apply to the final sample. The gain is linearly
  20252. interpolated between the first and last samples.
  20253. @see addFrom
  20254. */
  20255. void copyFromWithRamp (const int destChannel,
  20256. const int destStartSample,
  20257. const float* source,
  20258. int numSamples,
  20259. float startGain,
  20260. float endGain) throw();
  20261. /** Finds the highest and lowest sample values in a given range.
  20262. @param channel the channel to read from
  20263. @param startSample the start sample within the channel
  20264. @param numSamples the number of samples to check
  20265. @param minVal on return, the lowest value that was found
  20266. @param maxVal on return, the highest value that was found
  20267. */
  20268. void findMinMax (const int channel,
  20269. const int startSample,
  20270. int numSamples,
  20271. float& minVal,
  20272. float& maxVal) const throw();
  20273. /** Finds the highest absolute sample value within a region of a channel.
  20274. */
  20275. float getMagnitude (const int channel,
  20276. const int startSample,
  20277. const int numSamples) const throw();
  20278. /** Finds the highest absolute sample value within a region on all channels.
  20279. */
  20280. float getMagnitude (const int startSample,
  20281. const int numSamples) const throw();
  20282. /** Returns the root mean squared level for a region of a channel.
  20283. */
  20284. float getRMSLevel (const int channel,
  20285. const int startSample,
  20286. const int numSamples) const throw();
  20287. /** Fills a section of the buffer using an AudioReader as its source.
  20288. This will convert the reader's fixed- or floating-point data to
  20289. the buffer's floating-point format, and will try to intelligently
  20290. cope with mismatches between the number of channels in the reader
  20291. and the buffer.
  20292. @see writeToAudioWriter
  20293. */
  20294. void readFromAudioReader (AudioFormatReader* reader,
  20295. const int startSample,
  20296. const int numSamples,
  20297. const int readerStartSample,
  20298. const bool useReaderLeftChan,
  20299. const bool useReaderRightChan) throw();
  20300. /** Writes a section of this buffer to an audio writer.
  20301. This saves you having to mess about with channels or floating/fixed
  20302. point conversion.
  20303. @see readFromAudioReader
  20304. */
  20305. void writeToAudioWriter (AudioFormatWriter* writer,
  20306. const int startSample,
  20307. const int numSamples) const throw();
  20308. juce_UseDebuggingNewOperator
  20309. private:
  20310. int numChannels, size, allocatedBytes;
  20311. float** channels;
  20312. float* allocatedData;
  20313. };
  20314. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20315. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20316. #endif
  20317. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20318. /********* Start of inlined file: juce_IIRFilter.h *********/
  20319. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20320. #define __JUCE_IIRFILTER_JUCEHEADER__
  20321. /**
  20322. An IIR filter that can perform low, high, or band-pass filtering on an
  20323. audio signal.
  20324. @see IIRFilterAudioSource
  20325. */
  20326. class JUCE_API IIRFilter
  20327. {
  20328. public:
  20329. /** Creates a filter.
  20330. Initially the filter is inactive, so will have no effect on samples that
  20331. you process with it. Use the appropriate method to turn it into the type
  20332. of filter needed.
  20333. */
  20334. IIRFilter() throw();
  20335. /** Creates a copy of another filter. */
  20336. IIRFilter (const IIRFilter& other) throw();
  20337. /** Destructor. */
  20338. ~IIRFilter() throw();
  20339. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20340. Note that this clears the processing state, but the type of filter and
  20341. its coefficients aren't changed. To put a filter into an inactive state, use
  20342. the makeInactive() method.
  20343. */
  20344. void reset() throw();
  20345. /** Performs the filter operation on the given set of samples.
  20346. */
  20347. void processSamples (float* const samples,
  20348. const int numSamples) throw();
  20349. /** Processes a single sample, without any locking or checking.
  20350. Use this if you need fast processing of a single value, but be aware that
  20351. this isn't thread-safe in the way that processSamples() is.
  20352. */
  20353. float processSingleSampleRaw (const float sample) throw();
  20354. /** Sets the filter up to act as a low-pass filter.
  20355. */
  20356. void makeLowPass (const double sampleRate,
  20357. const double frequency) throw();
  20358. /** Sets the filter up to act as a high-pass filter.
  20359. */
  20360. void makeHighPass (const double sampleRate,
  20361. const double frequency) throw();
  20362. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20363. The gain is a scale factor that the low frequencies are multiplied by, so values
  20364. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20365. attenuate them.
  20366. */
  20367. void makeLowShelf (const double sampleRate,
  20368. const double cutOffFrequency,
  20369. const double Q,
  20370. const float gainFactor) throw();
  20371. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20372. The gain is a scale factor that the high frequencies are multiplied by, so values
  20373. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20374. attenuate them.
  20375. */
  20376. void makeHighShelf (const double sampleRate,
  20377. const double cutOffFrequency,
  20378. const double Q,
  20379. const float gainFactor) throw();
  20380. /** Sets the filter up to act as a band pass filter centred around a
  20381. frequency, with a variable Q and gain.
  20382. The gain is a scale factor that the centre frequencies are multiplied by, so
  20383. values greater than 1.0 will boost the centre frequencies, values less than
  20384. 1.0 will attenuate them.
  20385. */
  20386. void makeBandPass (const double sampleRate,
  20387. const double centreFrequency,
  20388. const double Q,
  20389. const float gainFactor) throw();
  20390. /** Clears the filter's coefficients so that it becomes inactive.
  20391. */
  20392. void makeInactive() throw();
  20393. /** Makes this filter duplicate the set-up of another one.
  20394. */
  20395. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20396. juce_UseDebuggingNewOperator
  20397. protected:
  20398. CriticalSection processLock;
  20399. void setCoefficients (double c1, double c2, double c3,
  20400. double c4, double c5, double c6) throw();
  20401. bool active;
  20402. float coefficients[6];
  20403. float x1, x2, y1, y2;
  20404. // (use the copyCoefficientsFrom() method instead of this operator)
  20405. const IIRFilter& operator= (const IIRFilter&);
  20406. };
  20407. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20408. /********* End of inlined file: juce_IIRFilter.h *********/
  20409. #endif
  20410. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20411. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20412. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20413. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20414. /**
  20415. A subclass of AudioPlayHead can supply information about the position and
  20416. status of a moving play head during audio playback.
  20417. One of these can be supplied to an AudioProcessor object so that it can find
  20418. out about the position of the audio that it is rendering.
  20419. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20420. */
  20421. class JUCE_API AudioPlayHead
  20422. {
  20423. protected:
  20424. AudioPlayHead() {}
  20425. public:
  20426. virtual ~AudioPlayHead() {}
  20427. /** Frame rate types. */
  20428. enum FrameRateType
  20429. {
  20430. fps24 = 0,
  20431. fps25 = 1,
  20432. fps2997 = 2,
  20433. fps30 = 3,
  20434. fps2997drop = 4,
  20435. fps30drop = 5,
  20436. fpsUnknown = 99
  20437. };
  20438. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20439. */
  20440. struct CurrentPositionInfo
  20441. {
  20442. /** The tempo in BPM */
  20443. double bpm;
  20444. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20445. int timeSigNumerator;
  20446. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20447. int timeSigDenominator;
  20448. /** The current play position, in seconds from the start of the edit. */
  20449. double timeInSeconds;
  20450. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20451. double editOriginTime;
  20452. /** The current play position in pulses-per-quarter-note.
  20453. This is the number of quarter notes since the edit start.
  20454. */
  20455. double ppqPosition;
  20456. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20457. This is the number of quarter notes from the start of the edit to the
  20458. start of the current bar.
  20459. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20460. it's not available, the value will be 0.
  20461. */
  20462. double ppqPositionOfLastBarStart;
  20463. /** The video frame rate, if applicable. */
  20464. FrameRateType frameRate;
  20465. /** True if the transport is currently playing. */
  20466. bool isPlaying;
  20467. /** True if the transport is currently recording.
  20468. (When isRecording is true, then isPlaying will also be true).
  20469. */
  20470. bool isRecording;
  20471. };
  20472. /** Fills-in the given structure with details about the transport's
  20473. position at the start of the current processing block.
  20474. */
  20475. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20476. };
  20477. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20478. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20479. #endif
  20480. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20481. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20482. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20483. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20484. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20485. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20486. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20487. class AudioProcessor;
  20488. /**
  20489. Base class for the component that acts as the GUI for an AudioProcessor.
  20490. Derive your editor component from this class, and create an instance of it
  20491. by overriding the AudioProcessor::createEditor() method.
  20492. @see AudioProcessor, GenericAudioProcessorEditor
  20493. */
  20494. class JUCE_API AudioProcessorEditor : public Component
  20495. {
  20496. protected:
  20497. /** Creates an editor for the specified processor.
  20498. */
  20499. AudioProcessorEditor (AudioProcessor* const owner);
  20500. public:
  20501. /** Destructor. */
  20502. ~AudioProcessorEditor();
  20503. /** Returns a pointer to the processor that this editor represents. */
  20504. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20505. private:
  20506. AudioProcessor* const owner;
  20507. };
  20508. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20509. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20510. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20511. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20512. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20513. class AudioProcessor;
  20514. /**
  20515. Base class for listeners that want to know about changes to an AudioProcessor.
  20516. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20517. @see AudioProcessor
  20518. */
  20519. class JUCE_API AudioProcessorListener
  20520. {
  20521. public:
  20522. /** Destructor. */
  20523. virtual ~AudioProcessorListener() {}
  20524. /** Receives a callback when a parameter is changed.
  20525. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20526. many audio processors will change their parameter during their audio callback.
  20527. This means that not only has your handler code got to be completely thread-safe,
  20528. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20529. this event on your message thread, use this callback to trigger an AsyncUpdater
  20530. or ChangeBroadcaster which you can respond to on the message thread.
  20531. */
  20532. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20533. int parameterIndex,
  20534. float newValue) = 0;
  20535. /** Called to indicate that something else in the plugin has changed, like its
  20536. program, number of parameters, etc.
  20537. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20538. call it during their audio callback. This means that not only has your handler code
  20539. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20540. blocking. If you need to handle this event on your message thread, use this callback
  20541. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20542. message thread.
  20543. */
  20544. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20545. /** Indicates that a parameter change gesture has started.
  20546. E.g. if the user is dragging a slider, this would be called when they first
  20547. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20548. called when they release it.
  20549. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20550. call it during their audio callback. This means that not only has your handler code
  20551. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20552. blocking. If you need to handle this event on your message thread, use this callback
  20553. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20554. message thread.
  20555. @see audioProcessorParameterChangeGestureEnd
  20556. */
  20557. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20558. int parameterIndex);
  20559. /** Indicates that a parameter change gesture has finished.
  20560. E.g. if the user is dragging a slider, this would be called when they release
  20561. the mouse button.
  20562. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20563. call it during their audio callback. This means that not only has your handler code
  20564. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20565. blocking. If you need to handle this event on your message thread, use this callback
  20566. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20567. message thread.
  20568. @see audioPluginParameterChangeGestureStart
  20569. */
  20570. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20571. int parameterIndex);
  20572. };
  20573. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20574. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20575. /**
  20576. Base class for audio processing filters or plugins.
  20577. This is intended to act as a base class of audio filter that is general enough to
  20578. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20579. It is also used by the plugin hosting code as the wrapper around an instance
  20580. of a loaded plugin.
  20581. Derive your filter class from this base class, and if you're building a plugin,
  20582. you should implement a global function called createPluginFilter() which creates
  20583. and returns a new instance of your subclass.
  20584. */
  20585. class JUCE_API AudioProcessor
  20586. {
  20587. protected:
  20588. /** Constructor.
  20589. You can also do your initialisation tasks in the initialiseFilterInfo()
  20590. call, which will be made after this object has been created.
  20591. */
  20592. AudioProcessor();
  20593. public:
  20594. /** Destructor. */
  20595. virtual ~AudioProcessor();
  20596. /** Returns the name of this processor.
  20597. */
  20598. virtual const String getName() const = 0;
  20599. /** Called before playback starts, to let the filter prepare itself.
  20600. The sample rate is the target sample rate, and will remain constant until
  20601. playback stops.
  20602. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20603. samples that will be processed for each callback, but isn't any kind
  20604. of guarantee. The actual block sizes that the host uses may be different
  20605. each time the callback happens, and may be more or less than this value.
  20606. */
  20607. virtual void prepareToPlay (double sampleRate,
  20608. int estimatedSamplesPerBlock) = 0;
  20609. /** Called after playback has stopped, to let the filter free up any resources it
  20610. no longer needs.
  20611. */
  20612. virtual void releaseResources() = 0;
  20613. /** Renders the next block.
  20614. When this method is called, the buffer contains a number of channels which is
  20615. at least as great as the maximum number of input and output channels that
  20616. this filter is using. It will be filled with the filter's input data and
  20617. should be replaced with the filter's output.
  20618. So for example if your filter has 2 input channels and 4 output channels, then
  20619. the buffer will contain 4 channels, the first two being filled with the
  20620. input data. Your filter should read these, do its processing, and replace
  20621. the contents of all 4 channels with its output.
  20622. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20623. all filled with data, and your filter should overwrite the first 2 of these
  20624. with its output. But be VERY careful not to write anything to the last 3
  20625. channels, as these might be mapped to memory that the host assumes is read-only!
  20626. Note that if you have more outputs than inputs, then only those channels that
  20627. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20628. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20629. but the last two channels may contain garbage, so you should be careful not to
  20630. let this pass through without being overwritten or cleared.
  20631. Also note that the buffer may have more channels than are strictly necessary,
  20632. but your should only read/write from the ones that your filter is supposed to
  20633. be using.
  20634. The number of samples in these buffers is NOT guaranteed to be the same for every
  20635. callback, and may be more or less than the estimated value given to prepareToPlay().
  20636. Your code must be able to cope with variable-sized blocks, or you're going to get
  20637. clicks and crashes!
  20638. If the filter is receiving a midi input, then the midiMessages array will be filled
  20639. with the midi messages for this block. Each message's timestamp will indicate the
  20640. message's time, as a number of samples from the start of the block.
  20641. Any messages left in the midi buffer when this method has finished are assumed to
  20642. be the filter's midi output. This means that your filter should be careful to
  20643. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20644. Be very careful about what you do in this callback - it's going to be called by
  20645. the audio thread, so any kind of interaction with the UI is absolutely
  20646. out of the question. If you change a parameter in here and need to tell your UI to
  20647. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20648. the UI components register as listeners, and then call sendChangeMessage() inside the
  20649. processBlock() method to send out an asynchronous message. You could also use
  20650. the AsyncUpdater class in a similar way.
  20651. */
  20652. virtual void processBlock (AudioSampleBuffer& buffer,
  20653. MidiBuffer& midiMessages) = 0;
  20654. /** Returns the current AudioPlayHead object that should be used to find
  20655. out the state and position of the playhead.
  20656. You can call this from your processBlock() method, and use the AudioPlayHead
  20657. object to get the details about the time of the start of the block currently
  20658. being processed.
  20659. If the host hasn't supplied a playhead object, this will return 0.
  20660. */
  20661. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20662. /** Returns the current sample rate.
  20663. This can be called from your processBlock() method - it's not guaranteed
  20664. to be valid at any other time, and may return 0 if it's unknown.
  20665. */
  20666. double getSampleRate() const throw() { return sampleRate; }
  20667. /** Returns the current typical block size that is being used.
  20668. This can be called from your processBlock() method - it's not guaranteed
  20669. to be valid at any other time.
  20670. Remember it's not the ONLY block size that may be used when calling
  20671. processBlock, it's just the normal one. The actual block sizes used may be
  20672. larger or smaller than this, and will vary between successive calls.
  20673. */
  20674. int getBlockSize() const throw() { return blockSize; }
  20675. /** Returns the number of input channels that the host will be sending the filter.
  20676. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20677. number of channels that your filter would prefer to have, and this method lets
  20678. you know how many the host is actually using.
  20679. Note that this method is only valid during or after the prepareToPlay()
  20680. method call. Until that point, the number of channels will be unknown.
  20681. */
  20682. int getNumInputChannels() const throw() { return numInputChannels; }
  20683. /** Returns the number of output channels that the host will be sending the filter.
  20684. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20685. number of channels that your filter would prefer to have, and this method lets
  20686. you know how many the host is actually using.
  20687. Note that this method is only valid during or after the prepareToPlay()
  20688. method call. Until that point, the number of channels will be unknown.
  20689. */
  20690. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20691. /** Returns the name of one of the input channels, as returned by the host.
  20692. The host might not supply very useful names for channels, and this might be
  20693. something like "1", "2", "left", "right", etc.
  20694. */
  20695. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20696. /** Returns the name of one of the output channels, as returned by the host.
  20697. The host might not supply very useful names for channels, and this might be
  20698. something like "1", "2", "left", "right", etc.
  20699. */
  20700. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20701. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20702. virtual bool isInputChannelStereoPair (int index) const = 0;
  20703. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20704. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20705. /** This returns the number of samples delay that the filter imposes on the audio
  20706. passing through it.
  20707. The host will call this to find the latency - the filter itself should set this value
  20708. by calling setLatencySamples() as soon as it can during its initialisation.
  20709. */
  20710. int getLatencySamples() const throw() { return latencySamples; }
  20711. /** The filter should call this to set the number of samples delay that it introduces.
  20712. The filter should call this as soon as it can during initialisation, and can call it
  20713. later if the value changes.
  20714. */
  20715. void setLatencySamples (const int newLatency);
  20716. /** Returns true if the processor wants midi messages. */
  20717. virtual bool acceptsMidi() const = 0;
  20718. /** Returns true if the processor produces midi messages. */
  20719. virtual bool producesMidi() const = 0;
  20720. /** This returns a critical section that will automatically be locked while the host
  20721. is calling the processBlock() method.
  20722. Use it from your UI or other threads to lock access to variables that are used
  20723. by the process callback, but obviously be careful not to keep it locked for
  20724. too long, because that could cause stuttering playback. If you need to do something
  20725. that'll take a long time and need the processing to stop while it happens, use the
  20726. suspendProcessing() method instead.
  20727. @see suspendProcessing
  20728. */
  20729. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20730. /** Enables and disables the processing callback.
  20731. If you need to do something time-consuming on a thread and would like to make sure
  20732. the audio processing callback doesn't happen until you've finished, use this
  20733. to disable the callback and re-enable it again afterwards.
  20734. E.g.
  20735. @code
  20736. void loadNewPatch()
  20737. {
  20738. suspendProcessing (true);
  20739. ..do something that takes ages..
  20740. suspendProcessing (false);
  20741. }
  20742. @endcode
  20743. If the host tries to make an audio callback while processing is suspended, the
  20744. filter will return an empty buffer, but won't block the audio thread like it would
  20745. do if you use the getCallbackLock() critical section to synchronise access.
  20746. If you're going to use this, your processBlock() method must call isSuspended() and
  20747. check whether it's suspended or not. If it is, then it should skip doing any real
  20748. processing, either emitting silence or passing the input through unchanged.
  20749. @see getCallbackLock
  20750. */
  20751. void suspendProcessing (const bool shouldBeSuspended);
  20752. /** Returns true if processing is currently suspended.
  20753. @see suspendProcessing
  20754. */
  20755. bool isSuspended() const throw() { return suspended; }
  20756. /** A plugin can override this to be told when it should reset any playing voices.
  20757. The default implementation does nothing, but a host may call this to tell the
  20758. plugin that it should stop any tails or sounds that have been left running.
  20759. */
  20760. virtual void reset();
  20761. /** Returns true if the processor is being run in an offline mode for rendering.
  20762. If the processor is being run live on realtime signals, this returns false.
  20763. If the mode is unknown, this will assume it's realtime and return false.
  20764. This value may be unreliable until the prepareToPlay() method has been called,
  20765. and could change each time prepareToPlay() is called.
  20766. @see setNonRealtime()
  20767. */
  20768. bool isNonRealtime() const throw() { return nonRealtime; }
  20769. /** Called by the host to tell this processor whether it's being used in a non-realime
  20770. capacity for offline rendering or bouncing.
  20771. Whatever value is passed-in will be
  20772. */
  20773. void setNonRealtime (const bool isNonRealtime) throw();
  20774. /** Creates the filter's UI.
  20775. This can return 0 if you want a UI-less filter, in which case the host may create
  20776. a generic UI that lets the user twiddle the parameters directly.
  20777. If you do want to pass back a component, the component should be created and set to
  20778. the correct size before returning it.
  20779. Remember not to do anything silly like allowing your filter to keep a pointer to
  20780. the component that gets created - it could be deleted later without any warning, which
  20781. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20782. The correct way to handle the connection between an editor component and its
  20783. filter is to use something like a ChangeBroadcaster so that the editor can
  20784. register itself as a listener, and be told when a change occurs. This lets them
  20785. safely unregister themselves when they are deleted.
  20786. Here are a few things to bear in mind when writing an editor:
  20787. - Initially there won't be an editor, until the user opens one, or they might
  20788. not open one at all. Your filter mustn't rely on it being there.
  20789. - An editor object may be deleted and a replacement one created again at any time.
  20790. - It's safe to assume that an editor will be deleted before its filter.
  20791. */
  20792. virtual AudioProcessorEditor* createEditor() = 0;
  20793. /** Returns the active editor, if there is one.
  20794. Bear in mind this can return 0, even if an editor has previously been
  20795. opened.
  20796. */
  20797. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20798. /** Returns the active editor, or if there isn't one, it will create one.
  20799. This may call createEditor() internally to create the component.
  20800. */
  20801. AudioProcessorEditor* createEditorIfNeeded();
  20802. /** This must return the correct value immediately after the object has been
  20803. created, and mustn't change the number of parameters later.
  20804. */
  20805. virtual int getNumParameters() = 0;
  20806. /** Returns the name of a particular parameter. */
  20807. virtual const String getParameterName (int parameterIndex) = 0;
  20808. /** Called by the host to find out the value of one of the filter's parameters.
  20809. The host will expect the value returned to be between 0 and 1.0.
  20810. This could be called quite frequently, so try to make your code efficient.
  20811. It's also likely to be called by non-UI threads, so the code in here should
  20812. be thread-aware.
  20813. */
  20814. virtual float getParameter (int parameterIndex) = 0;
  20815. /** Returns the value of a parameter as a text string. */
  20816. virtual const String getParameterText (int parameterIndex) = 0;
  20817. /** The host will call this method to change the value of one of the filter's parameters.
  20818. The host may call this at any time, including during the audio processing
  20819. callback, so the filter has to process this very fast and avoid blocking.
  20820. If you want to set the value of a parameter internally, e.g. from your
  20821. editor component, then don't call this directly - instead, use the
  20822. setParameterNotifyingHost() method, which will also send a message to
  20823. the host telling it about the change. If the message isn't sent, the host
  20824. won't be able to automate your parameters properly.
  20825. The value passed will be between 0 and 1.0.
  20826. */
  20827. virtual void setParameter (int parameterIndex,
  20828. float newValue) = 0;
  20829. /** Your filter can call this when it needs to change one of its parameters.
  20830. This could happen when the editor or some other internal operation changes
  20831. a parameter. This method will call the setParameter() method to change the
  20832. value, and will then send a message to the host telling it about the change.
  20833. Note that to make sure the host correctly handles automation, you should call
  20834. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20835. tell the host when the user has started and stopped changing the parameter.
  20836. */
  20837. void setParameterNotifyingHost (int parameterIndex,
  20838. float newValue);
  20839. /** Returns true if the host can automate this parameter.
  20840. By default, this returns true for all parameters.
  20841. */
  20842. virtual bool isParameterAutomatable (int parameterIndex) const;
  20843. /** Should return true if this parameter is a "meta" parameter.
  20844. A meta-parameter is a parameter that changes other params. It is used
  20845. by some hosts (e.g. AudioUnit hosts).
  20846. By default this returns false.
  20847. */
  20848. virtual bool isMetaParameter (int parameterIndex) const;
  20849. /** Sends a signal to the host to tell it that the user is about to start changing this
  20850. parameter.
  20851. This allows the host to know when a parameter is actively being held by the user, and
  20852. it may use this information to help it record automation.
  20853. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20854. */
  20855. void beginParameterChangeGesture (int parameterIndex);
  20856. /** Tells the host that the user has finished changing this parameter.
  20857. This allows the host to know when a parameter is actively being held by the user, and
  20858. it may use this information to help it record automation.
  20859. A call to this method must follow a call to beginParameterChangeGesture().
  20860. */
  20861. void endParameterChangeGesture (int parameterIndex);
  20862. /** The filter can call this when something (apart from a parameter value) has changed.
  20863. It sends a hint to the host that something like the program, number of parameters,
  20864. etc, has changed, and that it should update itself.
  20865. */
  20866. void updateHostDisplay();
  20867. /** Returns the number of preset programs the filter supports.
  20868. The value returned must be valid as soon as this object is created, and
  20869. must not change over its lifetime.
  20870. This value shouldn't be less than 1.
  20871. */
  20872. virtual int getNumPrograms() = 0;
  20873. /** Returns the number of the currently active program.
  20874. */
  20875. virtual int getCurrentProgram() = 0;
  20876. /** Called by the host to change the current program.
  20877. */
  20878. virtual void setCurrentProgram (int index) = 0;
  20879. /** Must return the name of a given program. */
  20880. virtual const String getProgramName (int index) = 0;
  20881. /** Called by the host to rename a program.
  20882. */
  20883. virtual void changeProgramName (int index, const String& newName) = 0;
  20884. /** The host will call this method when it wants to save the filter's internal state.
  20885. This must copy any info about the filter's state into the block of memory provided,
  20886. so that the host can store this and later restore it using setStateInformation().
  20887. Note that there's also a getCurrentProgramStateInformation() method, which only
  20888. stores the current program, not the state of the entire filter.
  20889. See also the helper function copyXmlToBinary() for storing settings as XML.
  20890. @see getCurrentProgramStateInformation
  20891. */
  20892. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20893. /** The host will call this method if it wants to save the state of just the filter's
  20894. current program.
  20895. Unlike getStateInformation, this should only return the current program's state.
  20896. Not all hosts support this, and if you don't implement it, the base class
  20897. method just calls getStateInformation() instead. If you do implement it, be
  20898. sure to also implement getCurrentProgramStateInformation.
  20899. @see getStateInformation, setCurrentProgramStateInformation
  20900. */
  20901. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20902. /** This must restore the filter's state from a block of data previously created
  20903. using getStateInformation().
  20904. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20905. to restore just the current program, not the state of the entire filter.
  20906. See also the helper function getXmlFromBinary() for loading settings as XML.
  20907. @see setCurrentProgramStateInformation
  20908. */
  20909. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20910. /** The host will call this method if it wants to restore the state of just the filter's
  20911. current program.
  20912. Not all hosts support this, and if you don't implement it, the base class
  20913. method just calls setStateInformation() instead. If you do implement it, be
  20914. sure to also implement getCurrentProgramStateInformation.
  20915. @see setStateInformation, getCurrentProgramStateInformation
  20916. */
  20917. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20918. /** Adds a listener that will be called when an aspect of this processor changes. */
  20919. void addListener (AudioProcessorListener* const newListener) throw();
  20920. /** Removes a previously added listener. */
  20921. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20922. /** Not for public use - this is called before deleting an editor component. */
  20923. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20924. /** Not for public use - this is called to initialise the processor. */
  20925. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20926. /** Not for public use - this is called to initialise the processor before playing. */
  20927. void setPlayConfigDetails (const int numIns, const int numOuts,
  20928. const double sampleRate,
  20929. const int blockSize) throw();
  20930. juce_UseDebuggingNewOperator
  20931. protected:
  20932. /** Helper function that just converts an xml element into a binary blob.
  20933. Use this in your filter's getStateInformation() method if you want to
  20934. store its state as xml.
  20935. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20936. from a binary blob.
  20937. */
  20938. static void copyXmlToBinary (const XmlElement& xml,
  20939. JUCE_NAMESPACE::MemoryBlock& destData);
  20940. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20941. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20942. an XmlElement object that the caller must delete when no longer needed.
  20943. */
  20944. static XmlElement* getXmlFromBinary (const void* data,
  20945. const int sizeInBytes);
  20946. /** @internal */
  20947. AudioPlayHead* playHead;
  20948. /** @internal */
  20949. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20950. private:
  20951. VoidArray listeners;
  20952. AudioProcessorEditor* activeEditor;
  20953. double sampleRate;
  20954. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20955. bool suspended, nonRealtime;
  20956. CriticalSection callbackLock, listenerLock;
  20957. #ifdef JUCE_DEBUG
  20958. BitArray changingParams;
  20959. #endif
  20960. AudioProcessor (const AudioProcessor&);
  20961. const AudioProcessor& operator= (const AudioProcessor&);
  20962. };
  20963. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20964. /********* End of inlined file: juce_AudioProcessor.h *********/
  20965. #endif
  20966. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20967. #endif
  20968. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20969. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20970. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20971. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20972. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20973. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20974. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20975. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20976. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20977. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20978. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20979. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20980. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20981. /********* Start of inlined file: juce_PluginDescription.h *********/
  20982. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20983. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20984. /**
  20985. A small class to represent some facts about a particular type of plugin.
  20986. This class is for storing and managing the details about a plugin without
  20987. actually having to load an instance of it.
  20988. A KnownPluginList contains a list of PluginDescription objects.
  20989. @see KnownPluginList
  20990. */
  20991. class JUCE_API PluginDescription
  20992. {
  20993. public:
  20994. PluginDescription() throw();
  20995. PluginDescription (const PluginDescription& other) throw();
  20996. const PluginDescription& operator= (const PluginDescription& other) throw();
  20997. ~PluginDescription() throw();
  20998. /** The name of the plugin. */
  20999. String name;
  21000. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  21001. */
  21002. String pluginFormatName;
  21003. /** A category, such as "Dynamics", "Reverbs", etc.
  21004. */
  21005. String category;
  21006. /** The manufacturer. */
  21007. String manufacturerName;
  21008. /** The version. This string doesn't have any particular format. */
  21009. String version;
  21010. /** Either the file containing the plugin module, or some other unique way
  21011. of identifying it.
  21012. E.g. for an AU, this would be an ID string that the component manager
  21013. could use to retrieve the plugin. For a VST, it's the file path.
  21014. */
  21015. String fileOrIdentifier;
  21016. /** The last time the plugin file was changed.
  21017. This is handy when scanning for new or changed plugins.
  21018. */
  21019. Time lastFileModTime;
  21020. /** A unique ID for the plugin.
  21021. Note that this might not be unique between formats, e.g. a VST and some
  21022. other format might actually have the same id.
  21023. @see createIdentifierString
  21024. */
  21025. int uid;
  21026. /** True if the plugin identifies itself as a synthesiser. */
  21027. bool isInstrument;
  21028. /** The number of inputs. */
  21029. int numInputChannels;
  21030. /** The number of outputs. */
  21031. int numOutputChannels;
  21032. /** Returns true if the two descriptions refer the the same plugin.
  21033. This isn't quite as simple as them just having the same file (because of
  21034. shell plugins).
  21035. */
  21036. bool isDuplicateOf (const PluginDescription& other) const;
  21037. /** Returns a string that can be saved and used to uniquely identify the
  21038. plugin again.
  21039. This contains less info than the XML encoding, and is independent of the
  21040. plugin's file location, so can be used to store a plugin ID for use
  21041. across different machines.
  21042. */
  21043. const String createIdentifierString() const throw();
  21044. /** Creates an XML object containing these details.
  21045. @see loadFromXml
  21046. */
  21047. XmlElement* createXml() const;
  21048. /** Reloads the info in this structure from an XML record that was previously
  21049. saved with createXML().
  21050. Returns true if the XML was a valid plugin description.
  21051. */
  21052. bool loadFromXml (const XmlElement& xml);
  21053. juce_UseDebuggingNewOperator
  21054. };
  21055. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21056. /********* End of inlined file: juce_PluginDescription.h *********/
  21057. /**
  21058. Base class for an active instance of a plugin.
  21059. This derives from the AudioProcessor class, and adds some extra functionality
  21060. that helps when wrapping dynamically loaded plugins.
  21061. @see AudioProcessor, AudioPluginFormat
  21062. */
  21063. class JUCE_API AudioPluginInstance : public AudioProcessor
  21064. {
  21065. public:
  21066. /** Destructor.
  21067. Make sure that you delete any UI components that belong to this plugin before
  21068. deleting the plugin.
  21069. */
  21070. virtual ~AudioPluginInstance();
  21071. /** Fills-in the appropriate parts of this plugin description object.
  21072. */
  21073. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  21074. juce_UseDebuggingNewOperator
  21075. protected:
  21076. AudioPluginInstance();
  21077. AudioPluginInstance (const AudioPluginInstance&);
  21078. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  21079. };
  21080. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21081. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  21082. class PluginDescription;
  21083. /**
  21084. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  21085. Use the static getNumFormats() and getFormat() calls to find the types
  21086. of format that are available.
  21087. */
  21088. class JUCE_API AudioPluginFormat
  21089. {
  21090. public:
  21091. /** Destructor. */
  21092. virtual ~AudioPluginFormat();
  21093. /** Returns the format name.
  21094. E.g. "VST", "AudioUnit", etc.
  21095. */
  21096. virtual const String getName() const = 0;
  21097. /** This tries to create descriptions for all the plugin types available in
  21098. a binary module file.
  21099. The file will be some kind of DLL or bundle.
  21100. Normally there will only be one type returned, but some plugins
  21101. (e.g. VST shells) can use a single DLL to create a set of different plugin
  21102. subtypes, so in that case, each subtype is returned as a separate object.
  21103. */
  21104. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  21105. const String& fileOrIdentifier) = 0;
  21106. /** Tries to recreate a type from a previously generated PluginDescription.
  21107. @see PluginDescription::createInstance
  21108. */
  21109. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  21110. /** Should do a quick check to see if this file or directory might be a plugin of
  21111. this format.
  21112. This is for searching for potential files, so it shouldn't actually try to
  21113. load the plugin or do anything time-consuming.
  21114. */
  21115. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  21116. /** Returns a readable version of the name of the plugin that this identifier refers to.
  21117. */
  21118. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  21119. /** Checks whether this plugin could possibly be loaded.
  21120. It doesn't actually need to load it, just to check whether the file or component
  21121. still exists.
  21122. */
  21123. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  21124. /** Searches a suggested set of directories for any plugins in this format.
  21125. The path might be ignored, e.g. by AUs, which are found by the OS rather
  21126. than manually.
  21127. */
  21128. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  21129. const bool recursive) = 0;
  21130. /** Returns the typical places to look for this kind of plugin.
  21131. Note that if this returns no paths, it means that the format can't be scanned-for
  21132. (i.e. it's an internal format that doesn't live in files)
  21133. */
  21134. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  21135. juce_UseDebuggingNewOperator
  21136. protected:
  21137. AudioPluginFormat() throw();
  21138. AudioPluginFormat (const AudioPluginFormat&);
  21139. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  21140. };
  21141. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21142. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  21143. /**
  21144. This maintains a list of known AudioPluginFormats.
  21145. @see AudioPluginFormat
  21146. */
  21147. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  21148. {
  21149. public:
  21150. AudioPluginFormatManager() throw();
  21151. /** Destructor. */
  21152. ~AudioPluginFormatManager() throw();
  21153. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  21154. /** Adds any formats that it knows about, e.g. VST.
  21155. */
  21156. void addDefaultFormats();
  21157. /** Returns the number of types of format that are available.
  21158. Use getFormat() to get one of them.
  21159. */
  21160. int getNumFormats() throw();
  21161. /** Returns one of the available formats.
  21162. @see getNumFormats
  21163. */
  21164. AudioPluginFormat* getFormat (const int index) throw();
  21165. /** Adds a format to the list.
  21166. The object passed in will be owned and deleted by the manager.
  21167. */
  21168. void addFormat (AudioPluginFormat* const format) throw();
  21169. /** Tries to load the type for this description, by trying all the formats
  21170. that this manager knows about.
  21171. The caller is responsible for deleting the object that is returned.
  21172. If it can't load the plugin, it returns 0 and leaves a message in the
  21173. errorMessage string.
  21174. */
  21175. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  21176. String& errorMessage) const;
  21177. /** Checks that the file or component for this plugin actually still exists.
  21178. (This won't try to load the plugin)
  21179. */
  21180. bool doesPluginStillExist (const PluginDescription& description) const;
  21181. juce_UseDebuggingNewOperator
  21182. private:
  21183. OwnedArray <AudioPluginFormat> formats;
  21184. AudioPluginFormatManager (const AudioPluginFormatManager&);
  21185. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  21186. };
  21187. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21188. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21189. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21190. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21191. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21192. /********* Start of inlined file: juce_PopupMenu.h *********/
  21193. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21194. #define __JUCE_POPUPMENU_JUCEHEADER__
  21195. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21196. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21197. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21198. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21199. @see PopupMenu::addCustomItem
  21200. */
  21201. class JUCE_API PopupMenuCustomComponent : public Component
  21202. {
  21203. public:
  21204. /** Destructor. */
  21205. ~PopupMenuCustomComponent();
  21206. /** Chooses the size that this component would like to have.
  21207. Note that the size which this method returns isn't necessarily the one that
  21208. the menu will give it, as it will be stretched to fit the other items in
  21209. the menu.
  21210. */
  21211. virtual void getIdealSize (int& idealWidth,
  21212. int& idealHeight) = 0;
  21213. /** Dismisses the menu indicating that this item has been chosen.
  21214. This will cause the menu to exit from its modal state, returning
  21215. this item's id as the result.
  21216. */
  21217. void triggerMenuItem();
  21218. /** Returns true if this item should be highlighted because the mouse is
  21219. over it.
  21220. You can call this method in your paint() method to find out whether
  21221. to draw a highlight.
  21222. */
  21223. bool isItemHighlighted() const throw() { return isHighlighted; }
  21224. protected:
  21225. /** Constructor.
  21226. If isTriggeredAutomatically is true, then the menu will automatically detect
  21227. a click on this component and use that to trigger it. If it's false, then it's
  21228. up to your class to manually trigger the item if it wants to.
  21229. */
  21230. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21231. private:
  21232. friend class MenuItemInfo;
  21233. friend class MenuItemComponent;
  21234. friend class PopupMenuWindow;
  21235. int refCount_;
  21236. bool isHighlighted, isTriggeredAutomatically;
  21237. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21238. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21239. };
  21240. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21241. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21242. /** Creates and displays a popup-menu.
  21243. To show a popup-menu, you create one of these, add some items to it, then
  21244. call its show() method, which returns the id of the item the user selects.
  21245. E.g. @code
  21246. void MyWidget::mouseDown (const MouseEvent& e)
  21247. {
  21248. PopupMenu m;
  21249. m.addItem (1, "item 1");
  21250. m.addItem (2, "item 2");
  21251. const int result = m.show();
  21252. if (result == 0)
  21253. {
  21254. // user dismissed the menu without picking anything
  21255. }
  21256. else if (result == 1)
  21257. {
  21258. // user picked item 1
  21259. }
  21260. else if (result == 2)
  21261. {
  21262. // user picked item 2
  21263. }
  21264. }
  21265. @endcode
  21266. Submenus are easy too: @code
  21267. void MyWidget::mouseDown (const MouseEvent& e)
  21268. {
  21269. PopupMenu subMenu;
  21270. subMenu.addItem (1, "item 1");
  21271. subMenu.addItem (2, "item 2");
  21272. PopupMenu mainMenu;
  21273. mainMenu.addItem (3, "item 3");
  21274. mainMenu.addSubMenu ("other choices", subMenu);
  21275. const int result = m.show();
  21276. ...etc
  21277. }
  21278. @endcode
  21279. */
  21280. class JUCE_API PopupMenu
  21281. {
  21282. public:
  21283. /** Creates an empty popup menu. */
  21284. PopupMenu() throw();
  21285. /** Creates a copy of another menu. */
  21286. PopupMenu (const PopupMenu& other) throw();
  21287. /** Destructor. */
  21288. ~PopupMenu() throw();
  21289. /** Copies this menu from another one. */
  21290. const PopupMenu& operator= (const PopupMenu& other) throw();
  21291. /** Resets the menu, removing all its items. */
  21292. void clear() throw();
  21293. /** Appends a new text item for this menu to show.
  21294. @param itemResultId the number that will be returned from the show() method
  21295. if the user picks this item. The value should never be
  21296. zero, because that's used to indicate that the user didn't
  21297. select anything.
  21298. @param itemText the text to show.
  21299. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21300. picked
  21301. @param isTicked if true, the item will be shown with a tick next to it
  21302. @param iconToUse if this is non-zero, it should be an image that will be
  21303. displayed to the left of the item. This method will take its
  21304. own copy of the image passed-in, so there's no need to keep
  21305. it hanging around.
  21306. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21307. */
  21308. void addItem (const int itemResultId,
  21309. const String& itemText,
  21310. const bool isActive = true,
  21311. const bool isTicked = false,
  21312. const Image* const iconToUse = 0) throw();
  21313. /** Adds an item that represents one of the commands in a command manager object.
  21314. @param commandManager the manager to use to trigger the command and get information
  21315. about it
  21316. @param commandID the ID of the command
  21317. @param displayName if this is non-empty, then this string will be used instead of
  21318. the command's registered name
  21319. */
  21320. void addCommandItem (ApplicationCommandManager* commandManager,
  21321. const int commandID,
  21322. const String& displayName = String::empty) throw();
  21323. /** Appends a text item with a special colour.
  21324. This is the same as addItem(), but specifies a colour to use for the
  21325. text, which will override the default colours that are used by the
  21326. current look-and-feel. See addItem() for a description of the parameters.
  21327. */
  21328. void addColouredItem (const int itemResultId,
  21329. const String& itemText,
  21330. const Colour& itemTextColour,
  21331. const bool isActive = true,
  21332. const bool isTicked = false,
  21333. const Image* const iconToUse = 0) throw();
  21334. /** Appends a custom menu item.
  21335. This will add a user-defined component to use as a menu item. The component
  21336. passed in will be deleted by this menu when it's no longer needed.
  21337. @see PopupMenuCustomComponent
  21338. */
  21339. void addCustomItem (const int itemResultId,
  21340. PopupMenuCustomComponent* const customComponent) throw();
  21341. /** Appends a custom menu item that can't be used to trigger a result.
  21342. This will add a user-defined component to use as a menu item. Unlike the
  21343. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21344. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21345. delete the component when it's finished, so it's the caller's responsibility
  21346. to manage the component that is passed-in.
  21347. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21348. detection of a mouse-click on your component, and use that to trigger the
  21349. menu ID specified in itemResultId. If this is false, the menu item can't
  21350. be triggered, so itemResultId is not used.
  21351. @see PopupMenuCustomComponent
  21352. */
  21353. void addCustomItem (const int itemResultId,
  21354. Component* customComponent,
  21355. int idealWidth, int idealHeight,
  21356. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21357. /** Appends a sub-menu.
  21358. If the menu that's passed in is empty, it will appear as an inactive item.
  21359. */
  21360. void addSubMenu (const String& subMenuName,
  21361. const PopupMenu& subMenu,
  21362. const bool isActive = true,
  21363. Image* const iconToUse = 0,
  21364. const bool isTicked = false) throw();
  21365. /** Appends a separator to the menu, to help break it up into sections.
  21366. The menu class is smart enough not to display separators at the top or bottom
  21367. of the menu, and it will replace mutliple adjacent separators with a single
  21368. one, so your code can be quite free and easy about adding these, and it'll
  21369. always look ok.
  21370. */
  21371. void addSeparator() throw();
  21372. /** Adds a non-clickable text item to the menu.
  21373. This is a bold-font items which can be used as a header to separate the items
  21374. into named groups.
  21375. */
  21376. void addSectionHeader (const String& title) throw();
  21377. /** Returns the number of items that the menu currently contains.
  21378. (This doesn't count separators).
  21379. */
  21380. int getNumItems() const throw();
  21381. /** Returns true if the menu contains a command item that triggers the given command. */
  21382. bool containsCommandItem (const int commandID) const throw();
  21383. /** Returns true if the menu contains any items that can be used. */
  21384. bool containsAnyActiveItems() const throw();
  21385. /** Displays the menu and waits for the user to pick something.
  21386. This will display the menu modally, and return the ID of the item that the
  21387. user picks. If they click somewhere off the menu to get rid of it without
  21388. choosing anything, this will return 0.
  21389. The current location of the mouse will be used as the position to show the
  21390. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21391. on where this point is on the screen, the menu will appear above, below or
  21392. to the side of the point.
  21393. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21394. then when the menu first appears, it will make sure
  21395. that this item is visible. So if the menu has too many
  21396. items to fit on the screen, it will be scrolled to a
  21397. position where this item is visible.
  21398. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21399. than this if some items are too long to fit.
  21400. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21401. vertical column, the menu may be laid out as a series of
  21402. columns - this is the maximum number allowed. To use the
  21403. default value for this (probably about 7), you can pass
  21404. in zero.
  21405. @param standardItemHeight if this is non-zero, it will be used as the standard
  21406. height for menu items (apart from custom items)
  21407. @see showAt
  21408. */
  21409. int show (const int itemIdThatMustBeVisible = 0,
  21410. const int minimumWidth = 0,
  21411. const int maximumNumColumns = 0,
  21412. const int standardItemHeight = 0);
  21413. /** Displays the menu at a specific location.
  21414. This is the same as show(), but uses a specific location (in global screen
  21415. co-ordinates) rather than the current mouse position.
  21416. Note that the co-ordinates don't specify the top-left of the menu - they
  21417. indicate a point of interest, and the menu will position itself nearby to
  21418. this point, trying to keep it fully on-screen.
  21419. @see show()
  21420. */
  21421. int showAt (const int screenX,
  21422. const int screenY,
  21423. const int itemIdThatMustBeVisible = 0,
  21424. const int minimumWidth = 0,
  21425. const int maximumNumColumns = 0,
  21426. const int standardItemHeight = 0);
  21427. /** Displays the menu as if it's attached to a component such as a button.
  21428. This is similar to showAt(), but will position it next to the given component, e.g.
  21429. so that the menu's edge is aligned with that of the component. This is intended for
  21430. things like buttons that trigger a pop-up menu.
  21431. */
  21432. int showAt (Component* componentToAttachTo,
  21433. const int itemIdThatMustBeVisible = 0,
  21434. const int minimumWidth = 0,
  21435. const int maximumNumColumns = 0,
  21436. const int standardItemHeight = 0);
  21437. /** Closes any menus that are currently open.
  21438. This might be useful if you have a situation where your window is being closed
  21439. by some means other than a user action, and you'd like to make sure that menus
  21440. aren't left hanging around.
  21441. */
  21442. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21443. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21444. This can be called before show() if you need a customised menu. Be careful
  21445. not to delete the LookAndFeel object before the menu has been deleted.
  21446. */
  21447. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21448. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21449. These constants can be used either via the LookAndFeel::setColour()
  21450. method for the look and feel that is set for this menu with setLookAndFeel()
  21451. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21452. */
  21453. enum ColourIds
  21454. {
  21455. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21456. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21457. colour is specified when the item is added). */
  21458. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21459. addSectionHeader() method). */
  21460. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21461. highlighted menu item. */
  21462. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21463. highlighted item. */
  21464. };
  21465. /**
  21466. Allows you to iterate through the items in a pop-up menu, and examine
  21467. their properties.
  21468. To use this, just create one and repeatedly call its next() method. When this
  21469. returns true, all the member variables of the iterator are filled-out with
  21470. information describing the menu item. When it returns false, the end of the
  21471. list has been reached.
  21472. */
  21473. class JUCE_API MenuItemIterator
  21474. {
  21475. public:
  21476. /** Creates an iterator that will scan through the items in the specified
  21477. menu.
  21478. Be careful not to add any items to a menu while it is being iterated,
  21479. or things could get out of step.
  21480. */
  21481. MenuItemIterator (const PopupMenu& menu) throw();
  21482. /** Destructor. */
  21483. ~MenuItemIterator() throw();
  21484. /** Returns true if there is another item, and sets up all this object's
  21485. member variables to reflect that item's properties.
  21486. */
  21487. bool next() throw();
  21488. String itemName;
  21489. const PopupMenu* subMenu;
  21490. int itemId;
  21491. bool isSeparator;
  21492. bool isTicked;
  21493. bool isEnabled;
  21494. bool isCustomComponent;
  21495. bool isSectionHeader;
  21496. const Colour* customColour;
  21497. const Image* customImage;
  21498. ApplicationCommandManager* commandManager;
  21499. juce_UseDebuggingNewOperator
  21500. private:
  21501. const PopupMenu& menu;
  21502. int index;
  21503. MenuItemIterator (const MenuItemIterator&);
  21504. const MenuItemIterator& operator= (const MenuItemIterator&);
  21505. };
  21506. juce_UseDebuggingNewOperator
  21507. private:
  21508. friend class PopupMenuWindow;
  21509. friend class MenuItemIterator;
  21510. VoidArray items;
  21511. LookAndFeel* lookAndFeel;
  21512. bool separatorPending;
  21513. void addSeparatorIfPending();
  21514. int showMenu (const int x, const int y, const int w, const int h,
  21515. const int itemIdThatMustBeVisible,
  21516. const int minimumWidth,
  21517. const int maximumNumColumns,
  21518. const int standardItemHeight,
  21519. const bool alignToRectangle,
  21520. Component* const componentAttachedTo) throw();
  21521. friend class MenuBarComponent;
  21522. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21523. const int itemIdThatMustBeVisible,
  21524. const int minimumWidth,
  21525. const int maximumNumColumns,
  21526. const int standardItemHeight,
  21527. const bool alignToRectangle,
  21528. Component* menuBarComponent,
  21529. ApplicationCommandManager** managerOfChosenCommand,
  21530. Component* const componentAttachedTo) throw();
  21531. };
  21532. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21533. /********* End of inlined file: juce_PopupMenu.h *********/
  21534. /**
  21535. Manages a list of plugin types.
  21536. This can be easily edited, saved and loaded, and used to create instances of
  21537. the plugin types in it.
  21538. @see PluginListComponent
  21539. */
  21540. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21541. {
  21542. public:
  21543. /** Creates an empty list.
  21544. */
  21545. KnownPluginList();
  21546. /** Destructor. */
  21547. ~KnownPluginList();
  21548. /** Clears the list. */
  21549. void clear();
  21550. /** Returns the number of types currently in the list.
  21551. @see getType
  21552. */
  21553. int getNumTypes() const throw() { return types.size(); }
  21554. /** Returns one of the types.
  21555. @see getNumTypes
  21556. */
  21557. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21558. /** Looks for a type in the list which comes from this file.
  21559. */
  21560. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21561. /** Looks for a type in the list which matches a plugin type ID.
  21562. The identifierString parameter must have been created by
  21563. PluginDescription::createIdentifierString().
  21564. */
  21565. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21566. /** Adds a type manually from its description. */
  21567. bool addType (const PluginDescription& type);
  21568. /** Removes a type. */
  21569. void removeType (const int index) throw();
  21570. /** Looks for all types that can be loaded from a given file, and adds them
  21571. to the list.
  21572. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21573. re-tested if it's not already in the list, or if the file's modification
  21574. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21575. false, the file will always be reloaded and tested.
  21576. Returns true if any new types were added, and all the types found in this
  21577. file (even if it was already known and hasn't been re-scanned) get returned
  21578. in the array.
  21579. */
  21580. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21581. const bool dontRescanIfAlreadyInList,
  21582. OwnedArray <PluginDescription>& typesFound,
  21583. AudioPluginFormat& formatToUse);
  21584. /** Returns true if the specified file is already known about and if it
  21585. hasn't been modified since our entry was created.
  21586. */
  21587. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21588. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21589. If any types are found in the files, their descriptions are returned in the array.
  21590. */
  21591. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21592. OwnedArray <PluginDescription>& typesFound);
  21593. /** Sort methods used to change the order of the plugins in the list.
  21594. */
  21595. enum SortMethod
  21596. {
  21597. defaultOrder = 0,
  21598. sortAlphabetically,
  21599. sortByCategory,
  21600. sortByManufacturer,
  21601. sortByFileSystemLocation
  21602. };
  21603. /** Adds all the plugin types to a popup menu so that the user can select one.
  21604. Depending on the sort method, it may add sub-menus for categories,
  21605. manufacturers, etc.
  21606. Use getIndexChosenByMenu() to find out the type that was chosen.
  21607. */
  21608. void addToMenu (PopupMenu& menu,
  21609. const SortMethod sortMethod) const;
  21610. /** Converts a menu item index that has been chosen into its index in this list.
  21611. Returns -1 if it's not an ID that was used.
  21612. @see addToMenu
  21613. */
  21614. int getIndexChosenByMenu (const int menuResultCode) const;
  21615. /** Sorts the list. */
  21616. void sort (const SortMethod method);
  21617. /** Creates some XML that can be used to store the state of this list.
  21618. */
  21619. XmlElement* createXml() const;
  21620. /** Recreates the state of this list from its stored XML format.
  21621. */
  21622. void recreateFromXml (const XmlElement& xml);
  21623. juce_UseDebuggingNewOperator
  21624. private:
  21625. OwnedArray <PluginDescription> types;
  21626. KnownPluginList (const KnownPluginList&);
  21627. const KnownPluginList& operator= (const KnownPluginList&);
  21628. };
  21629. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21630. /********* End of inlined file: juce_KnownPluginList.h *********/
  21631. /**
  21632. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21633. Use one of these objects if you want to wire-up a set of AudioProcessors
  21634. and play back the result.
  21635. Processors can be added to the graph as "nodes" using addNode(), and once
  21636. added, you can connect any of their input or output channels to other
  21637. nodes using addConnection().
  21638. To play back a graph through an audio device, you might want to use an
  21639. AudioProcessorPlayer object.
  21640. */
  21641. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21642. public AsyncUpdater
  21643. {
  21644. public:
  21645. /** Creates an empty graph.
  21646. */
  21647. AudioProcessorGraph();
  21648. /** Destructor.
  21649. Any processor objects that have been added to the graph will also be deleted.
  21650. */
  21651. ~AudioProcessorGraph();
  21652. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21653. To create a node, call AudioProcessorGraph::addNode().
  21654. */
  21655. class Node : public ReferenceCountedObject
  21656. {
  21657. public:
  21658. /** Destructor.
  21659. */
  21660. ~Node();
  21661. /** The ID number assigned to this node.
  21662. This is assigned by the graph that owns it, and can't be changed.
  21663. */
  21664. const uint32 id;
  21665. /** The actual processor object that this node represents.
  21666. */
  21667. AudioProcessor* const processor;
  21668. /** A set of user-definable properties that are associated with this node.
  21669. This can be used to attach values to the node for whatever purpose seems
  21670. useful. For example, you might store an x and y position if your application
  21671. is displaying the nodes on-screen.
  21672. */
  21673. PropertySet properties;
  21674. /** A convenient typedef for referring to a pointer to a node object.
  21675. */
  21676. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21677. juce_UseDebuggingNewOperator
  21678. private:
  21679. friend class AudioProcessorGraph;
  21680. bool isPrepared;
  21681. Node (const uint32 id, AudioProcessor* const processor) throw();
  21682. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21683. void unprepare();
  21684. Node (const Node&);
  21685. const Node& operator= (const Node&);
  21686. };
  21687. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21688. To create a connection, use AudioProcessorGraph::addConnection().
  21689. */
  21690. struct Connection
  21691. {
  21692. public:
  21693. /** The ID number of the node which is the input source for this connection.
  21694. @see AudioProcessorGraph::getNodeForId
  21695. */
  21696. uint32 sourceNodeId;
  21697. /** The index of the output channel of the source node from which this
  21698. connection takes its data.
  21699. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21700. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21701. index of an audio output channel in the source node.
  21702. */
  21703. int sourceChannelIndex;
  21704. /** The ID number of the node which is the destination for this connection.
  21705. @see AudioProcessorGraph::getNodeForId
  21706. */
  21707. uint32 destNodeId;
  21708. /** The index of the input channel of the destination node to which this
  21709. connection delivers its data.
  21710. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21711. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21712. index of an audio input channel in the destination node.
  21713. */
  21714. int destChannelIndex;
  21715. juce_UseDebuggingNewOperator
  21716. private:
  21717. };
  21718. /** Deletes all nodes and connections from this graph.
  21719. Any processor objects in the graph will be deleted.
  21720. */
  21721. void clear();
  21722. /** Returns the number of nodes in the graph. */
  21723. int getNumNodes() const throw() { return nodes.size(); }
  21724. /** Returns a pointer to one of the nodes in the graph.
  21725. This will return 0 if the index is out of range.
  21726. @see getNodeForId
  21727. */
  21728. Node* getNode (const int index) const throw() { return nodes [index]; }
  21729. /** Searches the graph for a node with the given ID number and returns it.
  21730. If no such node was found, this returns 0.
  21731. @see getNode
  21732. */
  21733. Node* getNodeForId (const uint32 nodeId) const throw();
  21734. /** Adds a node to the graph.
  21735. This creates a new node in the graph, for the specified processor. Once you have
  21736. added a processor to the graph, the graph owns it and will delete it later when
  21737. it is no longer needed.
  21738. The optional nodeId parameter lets you specify an ID to use for the node, but
  21739. if the value is already in use, this new node will overwrite the old one.
  21740. If this succeeds, it returns a pointer to the newly-created node.
  21741. */
  21742. Node* addNode (AudioProcessor* const newProcessor,
  21743. uint32 nodeId = 0);
  21744. /** Deletes a node within the graph which has the specified ID.
  21745. This will also delete any connections that are attached to this node.
  21746. */
  21747. bool removeNode (const uint32 nodeId);
  21748. /** Returns the number of connections in the graph. */
  21749. int getNumConnections() const throw() { return connections.size(); }
  21750. /** Returns a pointer to one of the connections in the graph. */
  21751. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21752. /** Searches for a connection between some specified channels.
  21753. If no such connection is found, this returns 0.
  21754. */
  21755. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21756. const int sourceChannelIndex,
  21757. const uint32 destNodeId,
  21758. const int destChannelIndex) const throw();
  21759. /** Returns true if there is a connection between any of the channels of
  21760. two specified nodes.
  21761. */
  21762. bool isConnected (const uint32 possibleSourceNodeId,
  21763. const uint32 possibleDestNodeId) const throw();
  21764. /** Returns true if it would be legal to connect the specified points.
  21765. */
  21766. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21767. const uint32 destNodeId, const int destChannelIndex) const throw();
  21768. /** Attempts to connect two specified channels of two nodes.
  21769. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21770. to an audio one or other such nonsense), then it'll return false.
  21771. */
  21772. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21773. const uint32 destNodeId, const int destChannelIndex);
  21774. /** Deletes the connection with the specified index.
  21775. Returns true if a connection was actually deleted.
  21776. */
  21777. void removeConnection (const int index);
  21778. /** Deletes any connection between two specified points.
  21779. Returns true if a connection was actually deleted.
  21780. */
  21781. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21782. const uint32 destNodeId, const int destChannelIndex);
  21783. /** Removes all connections from the specified node.
  21784. */
  21785. bool disconnectNode (const uint32 nodeId);
  21786. /** Performs a sanity checks of all the connections.
  21787. This might be useful if some of the processors are doing things like changing
  21788. their channel counts, which could render some connections obsolete.
  21789. */
  21790. bool removeIllegalConnections();
  21791. /** A special number that represents the midi channel of a node.
  21792. This is used as a channel index value if you want to refer to the midi input
  21793. or output instead of an audio channel.
  21794. */
  21795. static const int midiChannelIndex;
  21796. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21797. in order to use the audio that comes into and out of the graph itself.
  21798. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21799. node in the graph which delivers the audio that is coming into the parent
  21800. graph. This allows you to stream the data to other nodes and process the
  21801. incoming audio.
  21802. Likewise, one of these in "output" mode can be sent data which it will add to
  21803. the sum of data being sent to the graph's output.
  21804. @see AudioProcessorGraph
  21805. */
  21806. class AudioGraphIOProcessor : public AudioPluginInstance
  21807. {
  21808. public:
  21809. /** Specifies the mode in which this processor will operate.
  21810. */
  21811. enum IODeviceType
  21812. {
  21813. audioInputNode, /**< In this mode, the processor has output channels
  21814. representing all the audio input channels that are
  21815. coming into its parent audio graph. */
  21816. audioOutputNode, /**< In this mode, the processor has input channels
  21817. representing all the audio output channels that are
  21818. going out of its parent audio graph. */
  21819. midiInputNode, /**< In this mode, the processor has a midi output which
  21820. delivers the same midi data that is arriving at its
  21821. parent graph. */
  21822. midiOutputNode /**< In this mode, the processor has a midi input and
  21823. any data sent to it will be passed out of the parent
  21824. graph. */
  21825. };
  21826. /** Returns the mode of this processor. */
  21827. IODeviceType getType() const throw() { return type; }
  21828. /** Returns the parent graph to which this processor belongs, or 0 if it
  21829. hasn't yet been added to one. */
  21830. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21831. /** True if this is an audio or midi input. */
  21832. bool isInput() const throw();
  21833. /** True if this is an audio or midi output. */
  21834. bool isOutput() const throw();
  21835. AudioGraphIOProcessor (const IODeviceType type);
  21836. ~AudioGraphIOProcessor();
  21837. const String getName() const;
  21838. void fillInPluginDescription (PluginDescription& d) const;
  21839. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21840. void releaseResources();
  21841. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21842. const String getInputChannelName (const int channelIndex) const;
  21843. const String getOutputChannelName (const int channelIndex) const;
  21844. bool isInputChannelStereoPair (int index) const;
  21845. bool isOutputChannelStereoPair (int index) const;
  21846. bool acceptsMidi() const;
  21847. bool producesMidi() const;
  21848. AudioProcessorEditor* createEditor();
  21849. int getNumParameters();
  21850. const String getParameterName (int);
  21851. float getParameter (int);
  21852. const String getParameterText (int);
  21853. void setParameter (int, float);
  21854. int getNumPrograms();
  21855. int getCurrentProgram();
  21856. void setCurrentProgram (int);
  21857. const String getProgramName (int);
  21858. void changeProgramName (int, const String&);
  21859. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21860. void setStateInformation (const void* data, int sizeInBytes);
  21861. /** @internal */
  21862. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21863. juce_UseDebuggingNewOperator
  21864. private:
  21865. const IODeviceType type;
  21866. AudioProcessorGraph* graph;
  21867. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21868. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21869. };
  21870. // AudioProcessor methods:
  21871. const String getName() const;
  21872. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21873. void releaseResources();
  21874. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21875. const String getInputChannelName (const int channelIndex) const;
  21876. const String getOutputChannelName (const int channelIndex) const;
  21877. bool isInputChannelStereoPair (int index) const;
  21878. bool isOutputChannelStereoPair (int index) const;
  21879. bool acceptsMidi() const;
  21880. bool producesMidi() const;
  21881. AudioProcessorEditor* createEditor() { return 0; }
  21882. int getNumParameters() { return 0; }
  21883. const String getParameterName (int) { return String::empty; }
  21884. float getParameter (int) { return 0; }
  21885. const String getParameterText (int) { return String::empty; }
  21886. void setParameter (int, float) { }
  21887. int getNumPrograms() { return 0; }
  21888. int getCurrentProgram() { return 0; }
  21889. void setCurrentProgram (int) { }
  21890. const String getProgramName (int) { return String::empty; }
  21891. void changeProgramName (int, const String&) { }
  21892. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21893. void setStateInformation (const void* data, int sizeInBytes);
  21894. /** @internal */
  21895. void handleAsyncUpdate();
  21896. juce_UseDebuggingNewOperator
  21897. private:
  21898. ReferenceCountedArray <Node> nodes;
  21899. OwnedArray <Connection> connections;
  21900. int lastNodeId;
  21901. AudioSampleBuffer renderingBuffers;
  21902. OwnedArray <MidiBuffer> midiBuffers;
  21903. CriticalSection renderLock;
  21904. VoidArray renderingOps;
  21905. friend class AudioGraphIOProcessor;
  21906. AudioSampleBuffer* currentAudioInputBuffer;
  21907. AudioSampleBuffer currentAudioOutputBuffer;
  21908. MidiBuffer* currentMidiInputBuffer;
  21909. MidiBuffer currentMidiOutputBuffer;
  21910. void clearRenderingSequence();
  21911. void buildRenderingSequence();
  21912. bool isAnInputTo (const uint32 possibleInputId,
  21913. const uint32 possibleDestinationId,
  21914. const int recursionCheck) const throw();
  21915. AudioProcessorGraph (const AudioProcessorGraph&);
  21916. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21917. };
  21918. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21919. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21920. #endif
  21921. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21922. #endif
  21923. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21924. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21925. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21926. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21927. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21928. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21929. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21930. class AudioIODevice;
  21931. /**
  21932. One of these is passed to an AudioIODevice object to stream the audio data
  21933. in and out.
  21934. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21935. method on its own high-priority audio thread, when it needs to send or receive
  21936. the next block of data.
  21937. @see AudioIODevice, AudioDeviceManager
  21938. */
  21939. class JUCE_API AudioIODeviceCallback
  21940. {
  21941. public:
  21942. /** Destructor. */
  21943. virtual ~AudioIODeviceCallback() {}
  21944. /** Processes a block of incoming and outgoing audio data.
  21945. The subclass's implementation should use the incoming audio for whatever
  21946. purposes it needs to, and must fill all the output channels with the next
  21947. block of output data before returning.
  21948. The channel data is arranged with the same array indices as the channel name
  21949. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21950. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21951. associated channel, so remember to check for this.
  21952. @param inputChannelData a set of arrays containing the audio data for each
  21953. incoming channel - this data is valid until the function
  21954. returns. There will be one channel of data for each input
  21955. channel that was enabled when the audio device was opened
  21956. (see AudioIODevice::open())
  21957. @param numInputChannels the number of pointers to channel data in the
  21958. inputChannelData array.
  21959. @param outputChannelData a set of arrays which need to be filled with the data
  21960. that should be sent to each outgoing channel of the device.
  21961. There will be one channel of data for each output channel
  21962. that was enabled when the audio device was opened (see
  21963. AudioIODevice::open())
  21964. The initial contents of the array is undefined, so the
  21965. callback function must fill all the channels with zeros if
  21966. its output is silence. Failing to do this could cause quite
  21967. an unpleasant noise!
  21968. @param numOutputChannels the number of pointers to channel data in the
  21969. outputChannelData array.
  21970. @param numSamples the number of samples in each channel of the input and
  21971. output arrays. The number of samples will depend on the
  21972. audio device's buffer size and will usually remain constant,
  21973. although this isn't guaranteed, so make sure your code can
  21974. cope with reasonable changes in the buffer size from one
  21975. callback to the next.
  21976. */
  21977. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21978. int numInputChannels,
  21979. float** outputChannelData,
  21980. int numOutputChannels,
  21981. int numSamples) = 0;
  21982. /** Called to indicate that the device is about to start calling back.
  21983. This will be called just before the audio callbacks begin, either when this
  21984. callback has just been added to an audio device, or after the device has been
  21985. restarted because of a sample-rate or block-size change.
  21986. You can use this opportunity to find out the sample rate and block size
  21987. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21988. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21989. @param device the audio IO device that will be used to drive the callback.
  21990. Note that if you're going to store this this pointer, it is
  21991. only valid until the next time that audioDeviceStopped is called.
  21992. */
  21993. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21994. /** Called to indicate that the device has stopped.
  21995. */
  21996. virtual void audioDeviceStopped() = 0;
  21997. };
  21998. /**
  21999. Base class for an audio device with synchronised input and output channels.
  22000. Subclasses of this are used to implement different protocols such as DirectSound,
  22001. ASIO, CoreAudio, etc.
  22002. To create one of these, you'll need to use the AudioIODeviceType class - see the
  22003. documentation for that class for more info.
  22004. For an easier way of managing audio devices and their settings, have a look at the
  22005. AudioDeviceManager class.
  22006. @see AudioIODeviceType, AudioDeviceManager
  22007. */
  22008. class JUCE_API AudioIODevice
  22009. {
  22010. public:
  22011. /** Destructor. */
  22012. virtual ~AudioIODevice();
  22013. /** Returns the device's name, (as set in the constructor). */
  22014. const String& getName() const throw() { return name; }
  22015. /** Returns the type of the device.
  22016. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  22017. */
  22018. const String& getTypeName() const throw() { return typeName; }
  22019. /** Returns the names of all the available output channels on this device.
  22020. To find out which of these are currently in use, call getActiveOutputChannels().
  22021. */
  22022. virtual const StringArray getOutputChannelNames() = 0;
  22023. /** Returns the names of all the available input channels on this device.
  22024. To find out which of these are currently in use, call getActiveInputChannels().
  22025. */
  22026. virtual const StringArray getInputChannelNames() = 0;
  22027. /** Returns the number of sample-rates this device supports.
  22028. To find out which rates are available on this device, use this method to
  22029. find out how many there are, and getSampleRate() to get the rates.
  22030. @see getSampleRate
  22031. */
  22032. virtual int getNumSampleRates() = 0;
  22033. /** Returns one of the sample-rates this device supports.
  22034. To find out which rates are available on this device, use getNumSampleRates() to
  22035. find out how many there are, and getSampleRate() to get the individual rates.
  22036. The sample rate is set by the open() method.
  22037. (Note that for DirectSound some rates might not work, depending on combinations
  22038. of i/o channels that are being opened).
  22039. @see getNumSampleRates
  22040. */
  22041. virtual double getSampleRate (int index) = 0;
  22042. /** Returns the number of sizes of buffer that are available.
  22043. @see getBufferSizeSamples, getDefaultBufferSize
  22044. */
  22045. virtual int getNumBufferSizesAvailable() = 0;
  22046. /** Returns one of the possible buffer-sizes.
  22047. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  22048. @returns a number of samples
  22049. @see getNumBufferSizesAvailable, getDefaultBufferSize
  22050. */
  22051. virtual int getBufferSizeSamples (int index) = 0;
  22052. /** Returns the default buffer-size to use.
  22053. @returns a number of samples
  22054. @see getNumBufferSizesAvailable, getBufferSizeSamples
  22055. */
  22056. virtual int getDefaultBufferSize() = 0;
  22057. /** Tries to open the device ready to play.
  22058. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  22059. input channel should be enabled
  22060. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  22061. output channel should be enabled
  22062. @param sampleRate the sample rate to try to use - to find out which rates are
  22063. available, see getNumSampleRates() and getSampleRate()
  22064. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  22065. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  22066. @returns an error description if there's a problem, or an empty string if it succeeds in
  22067. opening the device
  22068. @see close
  22069. */
  22070. virtual const String open (const BitArray& inputChannels,
  22071. const BitArray& outputChannels,
  22072. double sampleRate,
  22073. int bufferSizeSamples) = 0;
  22074. /** Closes and releases the device if it's open. */
  22075. virtual void close() = 0;
  22076. /** Returns true if the device is still open.
  22077. A device might spontaneously close itself if something goes wrong, so this checks if
  22078. it's still open.
  22079. */
  22080. virtual bool isOpen() = 0;
  22081. /** Starts the device actually playing.
  22082. This must be called after the device has been opened.
  22083. @param callback the callback to use for streaming the data.
  22084. @see AudioIODeviceCallback, open
  22085. */
  22086. virtual void start (AudioIODeviceCallback* callback) = 0;
  22087. /** Stops the device playing.
  22088. Once a device has been started, this will stop it. Any pending calls to the
  22089. callback class will be flushed before this method returns.
  22090. */
  22091. virtual void stop() = 0;
  22092. /** Returns true if the device is still calling back.
  22093. The device might mysteriously stop, so this checks whether it's
  22094. still playing.
  22095. */
  22096. virtual bool isPlaying() = 0;
  22097. /** Returns the last error that happened if anything went wrong. */
  22098. virtual const String getLastError() = 0;
  22099. /** Returns the buffer size that the device is currently using.
  22100. If the device isn't actually open, this value doesn't really mean much.
  22101. */
  22102. virtual int getCurrentBufferSizeSamples() = 0;
  22103. /** Returns the sample rate that the device is currently using.
  22104. If the device isn't actually open, this value doesn't really mean much.
  22105. */
  22106. virtual double getCurrentSampleRate() = 0;
  22107. /** Returns the device's current physical bit-depth.
  22108. If the device isn't actually open, this value doesn't really mean much.
  22109. */
  22110. virtual int getCurrentBitDepth() = 0;
  22111. /** Returns a mask showing which of the available output channels are currently
  22112. enabled.
  22113. @see getOutputChannelNames
  22114. */
  22115. virtual const BitArray getActiveOutputChannels() const = 0;
  22116. /** Returns a mask showing which of the available input channels are currently
  22117. enabled.
  22118. @see getInputChannelNames
  22119. */
  22120. virtual const BitArray getActiveInputChannels() const = 0;
  22121. /** Returns the device's output latency.
  22122. This is the delay in samples between a callback getting a block of data, and
  22123. that data actually getting played.
  22124. */
  22125. virtual int getOutputLatencyInSamples() = 0;
  22126. /** Returns the device's input latency.
  22127. This is the delay in samples between some audio actually arriving at the soundcard,
  22128. and the callback getting passed this block of data.
  22129. */
  22130. virtual int getInputLatencyInSamples() = 0;
  22131. /** True if this device can show a pop-up control panel for editing its settings.
  22132. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22133. to display it.
  22134. */
  22135. virtual bool hasControlPanel() const;
  22136. /** Shows a device-specific control panel if there is one.
  22137. This should only be called for devices which return true from hasControlPanel().
  22138. */
  22139. virtual bool showControlPanel();
  22140. protected:
  22141. /** Creates a device, setting its name and type member variables. */
  22142. AudioIODevice (const String& deviceName,
  22143. const String& typeName);
  22144. /** @internal */
  22145. String name, typeName;
  22146. };
  22147. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22148. /********* End of inlined file: juce_AudioIODevice.h *********/
  22149. /**
  22150. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  22151. To use one of these, just make it the callback used by your AudioIODevice, and
  22152. give it a processor to use by calling setProcessor().
  22153. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  22154. input to send both streams through the processor.
  22155. @see AudioProcessor, AudioProcessorGraph
  22156. */
  22157. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  22158. public MidiInputCallback
  22159. {
  22160. public:
  22161. /**
  22162. */
  22163. AudioProcessorPlayer();
  22164. /** Destructor. */
  22165. virtual ~AudioProcessorPlayer();
  22166. /** Sets the processor that should be played.
  22167. The processor that is passed in will not be deleted or owned by this object.
  22168. To stop anything playing, pass in 0 to this method.
  22169. */
  22170. void setProcessor (AudioProcessor* const processorToPlay);
  22171. /** Returns the current audio processor that is being played.
  22172. */
  22173. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  22174. /** Returns a midi message collector that you can pass midi messages to if you
  22175. want them to be injected into the midi stream that is being sent to the
  22176. processor.
  22177. */
  22178. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  22179. /** @internal */
  22180. void audioDeviceIOCallback (const float** inputChannelData,
  22181. int totalNumInputChannels,
  22182. float** outputChannelData,
  22183. int totalNumOutputChannels,
  22184. int numSamples);
  22185. /** @internal */
  22186. void audioDeviceAboutToStart (AudioIODevice* device);
  22187. /** @internal */
  22188. void audioDeviceStopped();
  22189. /** @internal */
  22190. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22191. juce_UseDebuggingNewOperator
  22192. private:
  22193. AudioProcessor* processor;
  22194. CriticalSection lock;
  22195. double sampleRate;
  22196. int blockSize;
  22197. bool isPrepared;
  22198. int numInputChans, numOutputChans;
  22199. float* channels [128];
  22200. AudioSampleBuffer tempBuffer;
  22201. MidiBuffer incomingMidi;
  22202. MidiMessageCollector messageCollector;
  22203. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22204. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22205. };
  22206. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22207. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22208. #endif
  22209. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22210. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22211. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22212. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22213. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22214. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22215. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22216. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22217. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22218. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22219. class EditableProperty;
  22220. /**
  22221. A base class for a component that goes in a PropertyPanel and displays one of
  22222. an item's properties.
  22223. Subclasses of this are used to display a property in various forms, e.g. a
  22224. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22225. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22226. A subclass must implement the refresh() method which will be called to tell the
  22227. component to update itself, and is also responsible for calling this it when the
  22228. item that it refers to is changed.
  22229. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22230. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22231. */
  22232. class JUCE_API PropertyComponent : public Component
  22233. {
  22234. public:
  22235. /** Creates a PropertyComponent.
  22236. @param propertyName the name is stored as this component's name, and is
  22237. used as the name displayed next to this component in
  22238. a property panel
  22239. @param preferredHeight the height that the component should be given - some
  22240. items may need to be larger than a normal row height.
  22241. This value can also be set if a subclass changes the
  22242. preferredHeight member variable.
  22243. */
  22244. PropertyComponent (const String& propertyName,
  22245. const int preferredHeight = 25);
  22246. /** Destructor. */
  22247. ~PropertyComponent();
  22248. /** Returns this item's preferred height.
  22249. This value is specified either in the constructor or by a subclass changing the
  22250. preferredHeight member variable.
  22251. */
  22252. int getPreferredHeight() const throw() { return preferredHeight; }
  22253. /** Updates the property component if the item it refers to has changed.
  22254. A subclass must implement this method, and other objects may call it to
  22255. force it to refresh itself.
  22256. The subclass should be economical in the amount of work is done, so for
  22257. example it should check whether it really needs to do a repaint rather than
  22258. just doing one every time this method is called, as it may be called when
  22259. the value being displayed hasn't actually changed.
  22260. */
  22261. virtual void refresh() = 0;
  22262. /** The default paint method fills the background and draws a label for the
  22263. item's name.
  22264. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22265. */
  22266. void paint (Graphics& g);
  22267. /** The default resize method positions any child component to the right of this
  22268. one, based on the look and feel's default label size.
  22269. */
  22270. void resized();
  22271. /** By default, this just repaints the component. */
  22272. void enablementChanged();
  22273. juce_UseDebuggingNewOperator
  22274. protected:
  22275. /** Used by the PropertyPanel to determine how high this component needs to be.
  22276. A subclass can update this value in its constructor but shouldn't alter it later
  22277. as changes won't necessarily be picked up.
  22278. */
  22279. int preferredHeight;
  22280. };
  22281. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22282. /********* End of inlined file: juce_PropertyComponent.h *********/
  22283. /********* Start of inlined file: juce_Viewport.h *********/
  22284. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22285. #define __JUCE_VIEWPORT_JUCEHEADER__
  22286. /********* Start of inlined file: juce_ScrollBar.h *********/
  22287. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22288. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22289. /********* Start of inlined file: juce_Button.h *********/
  22290. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22291. #define __JUCE_BUTTON_JUCEHEADER__
  22292. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22293. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22294. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22295. /********* Start of inlined file: juce_TooltipClient.h *********/
  22296. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22297. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22298. /**
  22299. Components that want to use pop-up tooltips should implement this interface.
  22300. A TooltipWindow will wait for the mouse to hover over a component that
  22301. implements the TooltipClient interface, and when it finds one, it will display
  22302. the tooltip returned by its getTooltip() method.
  22303. @see TooltipWindow, SettableTooltipClient
  22304. */
  22305. class JUCE_API TooltipClient
  22306. {
  22307. public:
  22308. /** Destructor. */
  22309. virtual ~TooltipClient() {}
  22310. /** Returns the string that this object wants to show as its tooltip. */
  22311. virtual const String getTooltip() = 0;
  22312. };
  22313. /**
  22314. An implementation of TooltipClient that stores the tooltip string and a method
  22315. for changing it.
  22316. This makes it easy to add a tooltip to a custom component, by simply adding this
  22317. as a base class and calling setTooltip().
  22318. Many of the Juce widgets already use this as a base class to implement their
  22319. tooltips.
  22320. @see TooltipClient, TooltipWindow
  22321. */
  22322. class JUCE_API SettableTooltipClient : public TooltipClient
  22323. {
  22324. public:
  22325. /** Destructor. */
  22326. virtual ~SettableTooltipClient() {}
  22327. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22328. virtual const String getTooltip() { return tooltipString; }
  22329. juce_UseDebuggingNewOperator
  22330. protected:
  22331. String tooltipString;
  22332. };
  22333. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22334. /********* End of inlined file: juce_TooltipClient.h *********/
  22335. /**
  22336. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22337. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22338. object.
  22339. The TooltipWindow object will then stay invisible, waiting until the mouse
  22340. hovers for the specified length of time - it will then see if it's currently
  22341. over a component which implements the TooltipClient interface, and if so,
  22342. it will make itself visible to show the tooltip in the appropriate place.
  22343. @see TooltipClient, SettableTooltipClient
  22344. */
  22345. class JUCE_API TooltipWindow : public Component,
  22346. private Timer
  22347. {
  22348. public:
  22349. /** Creates a tooltip window.
  22350. Make sure your app only creates one instance of this class, otherwise you'll
  22351. get multiple overlaid tooltips appearing. The window will initially be invisible
  22352. and will make itself visible when it needs to display a tip.
  22353. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22354. methods.
  22355. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22356. otherwise the tooltip will be added to the given parent
  22357. component.
  22358. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22359. before a tooltip will be shown
  22360. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22361. */
  22362. TooltipWindow (Component* parentComponent = 0,
  22363. const int millisecondsBeforeTipAppears = 700);
  22364. /** Destructor. */
  22365. ~TooltipWindow();
  22366. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22367. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22368. methods.
  22369. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22370. */
  22371. enum ColourIds
  22372. {
  22373. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22374. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22375. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22376. };
  22377. juce_UseDebuggingNewOperator
  22378. private:
  22379. const int millisecondsBeforeTipAppears;
  22380. int mouseX, mouseY, mouseClicks;
  22381. unsigned int lastMouseMoveTime, lastHideTime;
  22382. Component* lastComponentUnderMouse;
  22383. bool changedCompsSinceShown;
  22384. String tip;
  22385. void paint (Graphics& g);
  22386. void mouseEnter (const MouseEvent& e);
  22387. void timerCallback();
  22388. void showFor (Component* const c);
  22389. void hide();
  22390. TooltipWindow (const TooltipWindow&);
  22391. const TooltipWindow& operator= (const TooltipWindow&);
  22392. };
  22393. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22394. /********* End of inlined file: juce_TooltipWindow.h *********/
  22395. class Button;
  22396. /**
  22397. Used to receive callbacks when a button is clicked.
  22398. @see Button::addButtonListener, Button::removeButtonListener
  22399. */
  22400. class JUCE_API ButtonListener
  22401. {
  22402. public:
  22403. /** Destructor. */
  22404. virtual ~ButtonListener() {}
  22405. /** Called when the button is clicked. */
  22406. virtual void buttonClicked (Button* button) = 0;
  22407. /** Called when the button's state changes. */
  22408. virtual void buttonStateChanged (Button*) {}
  22409. };
  22410. /**
  22411. A base class for buttons.
  22412. This contains all the logic for button behaviours such as enabling/disabling,
  22413. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22414. and radio groups, etc.
  22415. @see TextButton, DrawableButton, ToggleButton
  22416. */
  22417. class JUCE_API Button : public Component,
  22418. public SettableTooltipClient,
  22419. public ApplicationCommandManagerListener,
  22420. private KeyListener
  22421. {
  22422. protected:
  22423. /** Creates a button.
  22424. @param buttonName the text to put in the button (the component's name is also
  22425. initially set to this string, but these can be changed later
  22426. using the setName() and setButtonText() methods)
  22427. */
  22428. Button (const String& buttonName);
  22429. public:
  22430. /** Destructor. */
  22431. virtual ~Button();
  22432. /** Changes the button's text.
  22433. @see getButtonText
  22434. */
  22435. void setButtonText (const String& newText) throw();
  22436. /** Returns the text displayed in the button.
  22437. @see setButtonText
  22438. */
  22439. const String getButtonText() const throw() { return text; }
  22440. /** Returns true if the button is currently being held down by the mouse.
  22441. @see isOver
  22442. */
  22443. bool isDown() const throw();
  22444. /** Returns true if the mouse is currently over the button.
  22445. This will be also be true if the mouse is being held down.
  22446. @see isDown
  22447. */
  22448. bool isOver() const throw();
  22449. /** A button has an on/off state associated with it, and this changes that.
  22450. By default buttons are 'off' and for simple buttons that you click to perform
  22451. an action you won't change this. Toggle buttons, however will want to
  22452. change their state when turned on or off.
  22453. @param shouldBeOn whether to set the button's toggle state to be on or
  22454. off. If it's a member of a button group, this will
  22455. always try to turn it on, and to turn off any other
  22456. buttons in the group
  22457. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22458. the button will be repainted but no notification will
  22459. be sent
  22460. @see getToggleState, setRadioGroupId
  22461. */
  22462. void setToggleState (const bool shouldBeOn,
  22463. const bool sendChangeNotification);
  22464. /** Returns true if the button in 'on'.
  22465. By default buttons are 'off' and for simple buttons that you click to perform
  22466. an action you won't change this. Toggle buttons, however will want to
  22467. change their state when turned on or off.
  22468. @see setToggleState
  22469. */
  22470. bool getToggleState() const throw() { return isOn; }
  22471. /** This tells the button to automatically flip the toggle state when
  22472. the button is clicked.
  22473. If set to true, then before the clicked() callback occurs, the toggle-state
  22474. of the button is flipped.
  22475. */
  22476. void setClickingTogglesState (const bool shouldToggle) throw();
  22477. /** Returns true if this button is set to be an automatic toggle-button.
  22478. This returns the last value that was passed to setClickingTogglesState().
  22479. */
  22480. bool getClickingTogglesState() const throw();
  22481. /** Enables the button to act as a member of a mutually-exclusive group
  22482. of 'radio buttons'.
  22483. If the group ID is set to a non-zero number, then this button will
  22484. act as part of a group of buttons with the same ID, only one of
  22485. which can be 'on' at the same time. Note that when it's part of
  22486. a group, clicking a toggle-button that's 'on' won't turn it off.
  22487. To find other buttons with the same ID, this button will search through
  22488. its sibling components for ToggleButtons, so all the buttons for a
  22489. particular group must be placed inside the same parent component.
  22490. Set the group ID back to zero if you want it to act as a normal toggle
  22491. button again.
  22492. @see getRadioGroupId
  22493. */
  22494. void setRadioGroupId (const int newGroupId);
  22495. /** Returns the ID of the group to which this button belongs.
  22496. (See setRadioGroupId() for an explanation of this).
  22497. */
  22498. int getRadioGroupId() const throw() { return radioGroupId; }
  22499. /** Registers a listener to receive events when this button's state changes.
  22500. If the listener is already registered, this will not register it again.
  22501. @see removeButtonListener
  22502. */
  22503. void addButtonListener (ButtonListener* const newListener) throw();
  22504. /** Removes a previously-registered button listener
  22505. @see addButtonListener
  22506. */
  22507. void removeButtonListener (ButtonListener* const listener) throw();
  22508. /** Causes the button to act as if it's been clicked.
  22509. This will asynchronously make the button draw itself going down and up, and
  22510. will then call back the clicked() method as if mouse was clicked on it.
  22511. @see clicked
  22512. */
  22513. virtual void triggerClick();
  22514. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22515. When the button is pressed, it will use the given manager to trigger the
  22516. command ID.
  22517. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22518. before this button is. To disable the command triggering, call this method and
  22519. pass 0 for the parameters.
  22520. If generateTooltip is true, then the button's tooltip will be automatically
  22521. generated based on the name of this command and its current shortcut key.
  22522. @see addShortcut, getCommandID
  22523. */
  22524. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22525. const int commandID,
  22526. const bool generateTooltip);
  22527. /** Returns the command ID that was set by setCommandToTrigger().
  22528. */
  22529. int getCommandID() const throw() { return commandID; }
  22530. /** Assigns a shortcut key to trigger the button.
  22531. The button registers itself with its top-level parent component for keypresses.
  22532. Note that a different way of linking buttons to keypresses is by using the
  22533. setKeyPressToTrigger() method to invoke a command - the difference being that
  22534. setting a shortcut allows the button to be temporarily linked to a keypress
  22535. only while it's on-screen.
  22536. @see clearShortcuts
  22537. */
  22538. void addShortcut (const KeyPress& key);
  22539. /** Removes all key shortcuts that had been set for this button.
  22540. @see addShortcut
  22541. */
  22542. void clearShortcuts();
  22543. /** Returns true if the given keypress is a shortcut for this button.
  22544. @see addShortcut
  22545. */
  22546. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22547. /** Sets an auto-repeat speed for the button when it is held down.
  22548. (Auto-repeat is disabled by default).
  22549. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22550. triggering the next click. If this is zero, auto-repeat
  22551. is disabled
  22552. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22553. triggered
  22554. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22555. get faster, the longer the button is held down, up to the
  22556. minimum interval specified here
  22557. */
  22558. void setRepeatSpeed (const int initialDelayInMillisecs,
  22559. const int repeatDelayInMillisecs,
  22560. const int minimumDelayInMillisecs = -1) throw();
  22561. /** Sets whether the button click should happen when the mouse is pressed or released.
  22562. By default the button is only considered to have been clicked when the mouse is
  22563. released, but setting this to true will make it call the clicked() method as soon
  22564. as the button is pressed.
  22565. This is useful if the button is being used to show a pop-up menu, as it allows
  22566. the click to be used as a drag onto the menu.
  22567. */
  22568. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22569. /** Returns the number of milliseconds since the last time the button
  22570. went into the 'down' state.
  22571. */
  22572. uint32 getMillisecondsSinceButtonDown() const throw();
  22573. /** (overridden from Component to do special stuff). */
  22574. void setVisible (bool shouldBeVisible);
  22575. /** Sets the tooltip for this button.
  22576. @see TooltipClient, TooltipWindow
  22577. */
  22578. void setTooltip (const String& newTooltip);
  22579. // (implementation of the TooltipClient method)
  22580. const String getTooltip();
  22581. /** A combination of these flags are used by setConnectedEdges().
  22582. */
  22583. enum ConnectedEdgeFlags
  22584. {
  22585. ConnectedOnLeft = 1,
  22586. ConnectedOnRight = 2,
  22587. ConnectedOnTop = 4,
  22588. ConnectedOnBottom = 8
  22589. };
  22590. /** Hints about which edges of the button might be connected to adjoining buttons.
  22591. The value passed in is a bitwise combination of any of the values in the
  22592. ConnectedEdgeFlags enum.
  22593. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22594. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22595. without rounded corners on the edges that connect. It's only a hint, so the
  22596. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22597. button.
  22598. */
  22599. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22600. /** Returns the set of flags passed into setConnectedEdges(). */
  22601. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22602. /** Indicates whether the button adjoins another one on its left edge.
  22603. @see setConnectedEdges
  22604. */
  22605. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22606. /** Indicates whether the button adjoins another one on its right edge.
  22607. @see setConnectedEdges
  22608. */
  22609. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22610. /** Indicates whether the button adjoins another one on its top edge.
  22611. @see setConnectedEdges
  22612. */
  22613. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22614. /** Indicates whether the button adjoins another one on its bottom edge.
  22615. @see setConnectedEdges
  22616. */
  22617. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22618. /** Used by setState(). */
  22619. enum ButtonState
  22620. {
  22621. buttonNormal,
  22622. buttonOver,
  22623. buttonDown
  22624. };
  22625. /** Can be used to force the button into a particular state.
  22626. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22627. from happening.
  22628. The state that you set here will only last until it is automatically changed when the mouse
  22629. enters or exits the button, or the mouse-button is pressed or released.
  22630. */
  22631. void setState (const ButtonState newState);
  22632. juce_UseDebuggingNewOperator
  22633. protected:
  22634. /** This method is called when the button has been clicked.
  22635. Subclasses can override this to perform whatever they actions they need
  22636. to do.
  22637. Alternatively, a ButtonListener can be added to the button, and these listeners
  22638. will be called when the click occurs.
  22639. @see triggerClick
  22640. */
  22641. virtual void clicked();
  22642. /** This method is called when the button has been clicked.
  22643. By default it just calls clicked(), but you might want to override it to handle
  22644. things like clicking when a modifier key is pressed, etc.
  22645. @see ModifierKeys
  22646. */
  22647. virtual void clicked (const ModifierKeys& modifiers);
  22648. /** Subclasses should override this to actually paint the button's contents.
  22649. It's better to use this than the paint method, because it gives you information
  22650. about the over/down state of the button.
  22651. @param g the graphics context to use
  22652. @param isMouseOverButton true if the button is either in the 'over' or
  22653. 'down' state
  22654. @param isButtonDown true if the button should be drawn in the 'down' position
  22655. */
  22656. virtual void paintButton (Graphics& g,
  22657. bool isMouseOverButton,
  22658. bool isButtonDown) = 0;
  22659. /** Called when the button's up/down/over state changes.
  22660. Subclasses can override this if they need to do something special when the button
  22661. goes up or down.
  22662. @see isDown, isOver
  22663. */
  22664. virtual void buttonStateChanged();
  22665. /** @internal */
  22666. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22667. /** @internal */
  22668. void handleCommandMessage (int commandId);
  22669. /** @internal */
  22670. void mouseEnter (const MouseEvent& e);
  22671. /** @internal */
  22672. void mouseExit (const MouseEvent& e);
  22673. /** @internal */
  22674. void mouseDown (const MouseEvent& e);
  22675. /** @internal */
  22676. void mouseDrag (const MouseEvent& e);
  22677. /** @internal */
  22678. void mouseUp (const MouseEvent& e);
  22679. /** @internal */
  22680. bool keyPressed (const KeyPress& key);
  22681. /** @internal */
  22682. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22683. /** @internal */
  22684. bool keyStateChanged (Component* originatingComponent);
  22685. /** @internal */
  22686. void paint (Graphics& g);
  22687. /** @internal */
  22688. void parentHierarchyChanged();
  22689. /** @internal */
  22690. void focusGained (FocusChangeType cause);
  22691. /** @internal */
  22692. void focusLost (FocusChangeType cause);
  22693. /** @internal */
  22694. void enablementChanged();
  22695. /** @internal */
  22696. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22697. /** @internal */
  22698. void applicationCommandListChanged();
  22699. private:
  22700. Array <KeyPress> shortcuts;
  22701. Component* keySource;
  22702. String text;
  22703. SortedSet <void*> buttonListeners;
  22704. friend class InternalButtonRepeatTimer;
  22705. Timer* repeatTimer;
  22706. uint32 buttonPressTime, lastTimeCallbackTime;
  22707. ApplicationCommandManager* commandManagerToUse;
  22708. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22709. int radioGroupId, commandID, connectedEdgeFlags;
  22710. ButtonState buttonState;
  22711. bool isOn : 1;
  22712. bool clickTogglesState : 1;
  22713. bool needsToRelease : 1;
  22714. bool needsRepainting : 1;
  22715. bool isKeyDown : 1;
  22716. bool triggerOnMouseDown : 1;
  22717. bool generateTooltip : 1;
  22718. void repeatTimerCallback() throw();
  22719. Timer& getRepeatTimer() throw();
  22720. ButtonState updateState (const MouseEvent* const e) throw();
  22721. bool isShortcutPressed() const throw();
  22722. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22723. void flashButtonState() throw();
  22724. void sendClickMessage (const ModifierKeys& modifiers);
  22725. void sendStateMessage();
  22726. Button (const Button&);
  22727. const Button& operator= (const Button&);
  22728. };
  22729. #endif // __JUCE_BUTTON_JUCEHEADER__
  22730. /********* End of inlined file: juce_Button.h *********/
  22731. class ScrollBar;
  22732. /**
  22733. A class for receiving events from a ScrollBar.
  22734. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22735. method, and it will be called when the bar's position changes.
  22736. @see ScrollBar::addListener, ScrollBar::removeListener
  22737. */
  22738. class JUCE_API ScrollBarListener
  22739. {
  22740. public:
  22741. /** Destructor. */
  22742. virtual ~ScrollBarListener() {}
  22743. /** Called when a ScrollBar is moved.
  22744. @param scrollBarThatHasMoved the bar that has moved
  22745. @param newRangeStart the new range start of this bar
  22746. */
  22747. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22748. const double newRangeStart) = 0;
  22749. };
  22750. /**
  22751. A scrollbar component.
  22752. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22753. sets the range of values it can represent. Then you can use setCurrentRange() to
  22754. change the position and size of the scrollbar's 'thumb'.
  22755. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22756. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22757. they moved it to.
  22758. The scrollbar will adjust its own visibility according to whether its thumb size
  22759. allows it to actually be scrolled.
  22760. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22761. instead of handling a scrollbar directly.
  22762. @see ScrollBarListener
  22763. */
  22764. class JUCE_API ScrollBar : public Component,
  22765. public AsyncUpdater,
  22766. private Timer
  22767. {
  22768. public:
  22769. /** Creates a Scrollbar.
  22770. @param isVertical whether it should be a vertical or horizontal bar
  22771. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22772. */
  22773. ScrollBar (const bool isVertical,
  22774. const bool buttonsAreVisible = true);
  22775. /** Destructor. */
  22776. ~ScrollBar();
  22777. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22778. bool isVertical() const throw() { return vertical; }
  22779. /** Changes the scrollbar's direction.
  22780. You'll also need to resize the bar appropriately - this just changes its internal
  22781. layout.
  22782. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22783. */
  22784. void setOrientation (const bool shouldBeVertical) throw();
  22785. /** Shows or hides the scrollbar's buttons. */
  22786. void setButtonVisibility (const bool buttonsAreVisible);
  22787. /** Tells the scrollbar whether to make itself invisible when not needed.
  22788. The default behaviour is for a scrollbar to become invisible when the thumb
  22789. fills the whole of its range (i.e. when it can't be moved). Setting this
  22790. value to false forces the bar to always be visible.
  22791. */
  22792. void setAutoHide (const bool shouldHideWhenFullRange);
  22793. /** Sets the minimum and maximum values that the bar will move between.
  22794. The bar's thumb will always be constrained so that the top of the thumb
  22795. will be >= minimum, and the bottom of the thumb <= maximum.
  22796. @see setCurrentRange
  22797. */
  22798. void setRangeLimits (const double minimum,
  22799. const double maximum) throw();
  22800. /** Returns the lower value that the thumb can be set to.
  22801. This is the value set by setRangeLimits().
  22802. */
  22803. double getMinimumRangeLimit() const throw() { return minimum; }
  22804. /** Returns the upper value that the thumb can be set to.
  22805. This is the value set by setRangeLimits().
  22806. */
  22807. double getMaximumRangeLimit() const throw() { return maximum; }
  22808. /** Changes the position of the scrollbar's 'thumb'.
  22809. This sets both the position and size of the thumb - to just set the position without
  22810. changing the size, you can use setCurrentRangeStart().
  22811. If this method call actually changes the scrollbar's position, it will trigger an
  22812. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22813. are registered.
  22814. @param newStart the top (or left) of the thumb, in the range
  22815. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22816. value is beyond these limits, it will be clipped.
  22817. @param newSize the size of the thumb, such that
  22818. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22819. size is beyond these limits, it will be clipped.
  22820. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22821. */
  22822. void setCurrentRange (double newStart,
  22823. double newSize) throw();
  22824. /** Moves the bar's thumb position.
  22825. This will move the thumb position without changing the thumb size. Note
  22826. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22827. If this method call actually changes the scrollbar's position, it will trigger an
  22828. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22829. are registered.
  22830. @see setCurrentRange
  22831. */
  22832. void setCurrentRangeStart (double newStart) throw();
  22833. /** Returns the position of the top of the thumb.
  22834. @see setCurrentRangeStart
  22835. */
  22836. double getCurrentRangeStart() const throw() { return rangeStart; }
  22837. /** Returns the current size of the thumb.
  22838. @see setCurrentRange
  22839. */
  22840. double getCurrentRangeSize() const throw() { return rangeSize; }
  22841. /** Sets the amount by which the up and down buttons will move the bar.
  22842. The value here is in terms of the total range, and is added or subtracted
  22843. from the thumb position when the user clicks an up/down (or left/right) button.
  22844. */
  22845. void setSingleStepSize (const double newSingleStepSize) throw();
  22846. /** Moves the scrollbar by a number of single-steps.
  22847. This will move the bar by a multiple of its single-step interval (as
  22848. specified using the setSingleStepSize() method).
  22849. A positive value here will move the bar down or to the right, a negative
  22850. value moves it up or to the left.
  22851. */
  22852. void moveScrollbarInSteps (const int howManySteps) throw();
  22853. /** Moves the scroll bar up or down in pages.
  22854. This will move the bar by a multiple of its current thumb size, effectively
  22855. doing a page-up or down.
  22856. A positive value here will move the bar down or to the right, a negative
  22857. value moves it up or to the left.
  22858. */
  22859. void moveScrollbarInPages (const int howManyPages) throw();
  22860. /** Scrolls to the top (or left).
  22861. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22862. */
  22863. void scrollToTop() throw();
  22864. /** Scrolls to the bottom (or right).
  22865. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22866. */
  22867. void scrollToBottom() throw();
  22868. /** Changes the delay before the up and down buttons autorepeat when they are held
  22869. down.
  22870. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22871. @see Button::setRepeatSpeed
  22872. */
  22873. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22874. const int repeatDelayInMillisecs,
  22875. const int minimumDelayInMillisecs = -1) throw();
  22876. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22877. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22878. methods.
  22879. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22880. */
  22881. enum ColourIds
  22882. {
  22883. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22884. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22885. 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. */
  22886. };
  22887. /** Registers a listener that will be called when the scrollbar is moved. */
  22888. void addListener (ScrollBarListener* const listener) throw();
  22889. /** Deregisters a previously-registered listener. */
  22890. void removeListener (ScrollBarListener* const listener) throw();
  22891. /** @internal */
  22892. bool keyPressed (const KeyPress& key);
  22893. /** @internal */
  22894. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22895. /** @internal */
  22896. void lookAndFeelChanged();
  22897. /** @internal */
  22898. void handleAsyncUpdate();
  22899. /** @internal */
  22900. void mouseDown (const MouseEvent& e);
  22901. /** @internal */
  22902. void mouseDrag (const MouseEvent& e);
  22903. /** @internal */
  22904. void mouseUp (const MouseEvent& e);
  22905. /** @internal */
  22906. void paint (Graphics& g);
  22907. /** @internal */
  22908. void resized();
  22909. juce_UseDebuggingNewOperator
  22910. private:
  22911. double minimum, maximum;
  22912. double rangeStart, rangeSize;
  22913. double singleStepSize, dragStartRange;
  22914. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22915. int dragStartMousePos, lastMousePos;
  22916. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22917. bool vertical, isDraggingThumb, alwaysVisible;
  22918. Button* upButton;
  22919. Button* downButton;
  22920. SortedSet <void*> listeners;
  22921. void updateThumbPosition() throw();
  22922. void timerCallback();
  22923. ScrollBar (const ScrollBar&);
  22924. const ScrollBar& operator= (const ScrollBar&);
  22925. };
  22926. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22927. /********* End of inlined file: juce_ScrollBar.h *********/
  22928. /**
  22929. A Viewport is used to contain a larger child component, and allows the child
  22930. to be automatically scrolled around.
  22931. To use a Viewport, just create one and set the component that goes inside it
  22932. using the setViewedComponent() method. When the child component changes size,
  22933. the Viewport will adjust its scrollbars accordingly.
  22934. A subclass of the viewport can be created which will receive calls to its
  22935. visibleAreaChanged() method when the subcomponent changes position or size.
  22936. */
  22937. class JUCE_API Viewport : public Component,
  22938. private ComponentListener,
  22939. private ScrollBarListener
  22940. {
  22941. public:
  22942. /** Creates a Viewport.
  22943. The viewport is initially empty - use the setViewedComponent() method to
  22944. add a child component for it to manage.
  22945. */
  22946. Viewport (const String& componentName = String::empty);
  22947. /** Destructor. */
  22948. ~Viewport();
  22949. /** Sets the component that this viewport will contain and scroll around.
  22950. This will add the given component to this Viewport and position it at
  22951. (0, 0).
  22952. (Don't add or remove any child components directly using the normal
  22953. Component::addChildComponent() methods).
  22954. @param newViewedComponent the component to add to this viewport (this pointer
  22955. may be null). The component passed in will be deleted
  22956. by the Viewport when it's no longer needed
  22957. @see getViewedComponent
  22958. */
  22959. void setViewedComponent (Component* const newViewedComponent);
  22960. /** Returns the component that's currently being used inside the Viewport.
  22961. @see setViewedComponent
  22962. */
  22963. Component* getViewedComponent() const throw() { return contentComp; }
  22964. /** Changes the position of the viewed component.
  22965. The inner component will be moved so that the pixel at the top left of
  22966. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22967. within the inner component.
  22968. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22969. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22970. */
  22971. void setViewPosition (const int xPixelsOffset,
  22972. const int yPixelsOffset);
  22973. /** Changes the view position as a proportion of the distance it can move.
  22974. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22975. visible area in the top-left, and (1, 1) would put it as far down and
  22976. to the right as it's possible to go whilst keeping the child component
  22977. on-screen.
  22978. */
  22979. void setViewPositionProportionately (const double proportionX,
  22980. const double proportionY);
  22981. /** Returns the position within the child component of the top-left of its visible area.
  22982. @see getViewWidth, setViewPosition
  22983. */
  22984. int getViewPositionX() const throw() { return lastVX; }
  22985. /** Returns the position within the child component of the top-left of its visible area.
  22986. @see getViewHeight, setViewPosition
  22987. */
  22988. int getViewPositionY() const throw() { return lastVY; }
  22989. /** Returns the width of the visible area of the child component.
  22990. This may be less than the width of this Viewport if there's a vertical scrollbar
  22991. or if the child component is itself smaller.
  22992. */
  22993. int getViewWidth() const throw() { return lastVW; }
  22994. /** Returns the height of the visible area of the child component.
  22995. This may be less than the height of this Viewport if there's a horizontal scrollbar
  22996. or if the child component is itself smaller.
  22997. */
  22998. int getViewHeight() const throw() { return lastVH; }
  22999. /** Returns the width available within this component for the contents.
  23000. This will be the width of the viewport component minus the width of a
  23001. vertical scrollbar (if visible).
  23002. */
  23003. int getMaximumVisibleWidth() const throw();
  23004. /** Returns the height available within this component for the contents.
  23005. This will be the height of the viewport component minus the space taken up
  23006. by a horizontal scrollbar (if visible).
  23007. */
  23008. int getMaximumVisibleHeight() const throw();
  23009. /** Callback method that is called when the visible area changes.
  23010. This will be called when the visible area is moved either be scrolling or
  23011. by calls to setViewPosition(), etc.
  23012. */
  23013. virtual void visibleAreaChanged (int visibleX, int visibleY,
  23014. int visibleW, int visibleH);
  23015. /** Turns scrollbars on or off.
  23016. If set to false, the scrollbars won't ever appear. When true (the default)
  23017. they will appear only when needed.
  23018. */
  23019. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  23020. const bool showHorizontalScrollbarIfNeeded);
  23021. /** True if the vertical scrollbar is enabled.
  23022. @see setScrollBarsShown
  23023. */
  23024. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  23025. /** True if the horizontal scrollbar is enabled.
  23026. @see setScrollBarsShown
  23027. */
  23028. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  23029. /** Changes the width of the scrollbars.
  23030. If this isn't specified, the default width from the LookAndFeel class will be used.
  23031. @see LookAndFeel::getDefaultScrollbarWidth
  23032. */
  23033. void setScrollBarThickness (const int thickness);
  23034. /** Returns the thickness of the scrollbars.
  23035. @see setScrollBarThickness
  23036. */
  23037. int getScrollBarThickness() const throw();
  23038. /** Changes the distance that a single-step click on a scrollbar button
  23039. will move the viewport.
  23040. */
  23041. void setSingleStepSizes (const int stepX, const int stepY);
  23042. /** Shows or hides the buttons on any scrollbars that are used.
  23043. @see ScrollBar::setButtonVisibility
  23044. */
  23045. void setScrollBarButtonVisibility (const bool buttonsVisible);
  23046. /** Returns a pointer to the scrollbar component being used.
  23047. Handy if you need to customise the bar somehow.
  23048. */
  23049. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  23050. /** Returns a pointer to the scrollbar component being used.
  23051. Handy if you need to customise the bar somehow.
  23052. */
  23053. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  23054. juce_UseDebuggingNewOperator
  23055. /** @internal */
  23056. void resized();
  23057. /** @internal */
  23058. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  23059. /** @internal */
  23060. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23061. /** @internal */
  23062. bool keyPressed (const KeyPress& key);
  23063. /** @internal */
  23064. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  23065. /** @internal */
  23066. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23067. private:
  23068. Component* contentComp;
  23069. int lastVX, lastVY, lastVW, lastVH;
  23070. int scrollBarThickness;
  23071. int singleStepX, singleStepY;
  23072. bool showHScrollbar, showVScrollbar;
  23073. Component* contentHolder;
  23074. ScrollBar* verticalScrollBar;
  23075. ScrollBar* horizontalScrollBar;
  23076. void updateVisibleRegion();
  23077. Viewport (const Viewport&);
  23078. const Viewport& operator= (const Viewport&);
  23079. };
  23080. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  23081. /********* End of inlined file: juce_Viewport.h *********/
  23082. /**
  23083. A panel that holds a list of PropertyComponent objects.
  23084. This panel displays a list of PropertyComponents, and allows them to be organised
  23085. into collapsible sections.
  23086. To use, simply create one of these and add your properties to it with addProperties()
  23087. or addSection().
  23088. @see PropertyComponent
  23089. */
  23090. class JUCE_API PropertyPanel : public Component
  23091. {
  23092. public:
  23093. /** Creates an empty property panel. */
  23094. PropertyPanel();
  23095. /** Destructor. */
  23096. ~PropertyPanel();
  23097. /** Deletes all property components from the panel.
  23098. */
  23099. void clear();
  23100. /** Adds a set of properties to the panel.
  23101. The components in the list will be owned by this object and will be automatically
  23102. deleted later on when no longer needed.
  23103. These properties are added without them being inside a named section. If you
  23104. want them to be kept together in a collapsible section, use addSection() instead.
  23105. */
  23106. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  23107. /** Adds a set of properties to the panel.
  23108. These properties are added at the bottom of the list, under a section heading with
  23109. a plus/minus button that allows it to be opened and closed.
  23110. The components in the list will be owned by this object and will be automatically
  23111. deleted later on when no longer needed.
  23112. To add properies without them being in a section, use addProperties().
  23113. */
  23114. void addSection (const String& sectionTitle,
  23115. const Array <PropertyComponent*>& newPropertyComponents,
  23116. const bool shouldSectionInitiallyBeOpen = true);
  23117. /** Calls the refresh() method of all PropertyComponents in the panel */
  23118. void refreshAll() const;
  23119. /** Returns a list of all the names of sections in the panel.
  23120. These are the sections that have been added with addSection().
  23121. */
  23122. const StringArray getSectionNames() const;
  23123. /** Returns true if the section at this index is currently open.
  23124. The index is from 0 up to the number of items returned by getSectionNames().
  23125. */
  23126. bool isSectionOpen (const int sectionIndex) const;
  23127. /** Opens or closes one of the sections.
  23128. The index is from 0 up to the number of items returned by getSectionNames().
  23129. */
  23130. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  23131. /** Enables or disables one of the sections.
  23132. The index is from 0 up to the number of items returned by getSectionNames().
  23133. */
  23134. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  23135. /** Saves the current state of open/closed sections so it can be restored later.
  23136. The caller is responsible for deleting the object that is returned.
  23137. To restore this state, use restoreOpennessState().
  23138. @see restoreOpennessState
  23139. */
  23140. XmlElement* getOpennessState() const;
  23141. /** Restores a previously saved arrangement of open/closed sections.
  23142. This will try to restore a snapshot of the panel's state that was created by
  23143. the getOpennessState() method. If any of the sections named in the original
  23144. XML aren't present, they will be ignored.
  23145. @see getOpennessState
  23146. */
  23147. void restoreOpennessState (const XmlElement& newState);
  23148. /** Sets a message to be displayed when there are no properties in the panel.
  23149. The default message is "nothing selected".
  23150. */
  23151. void setMessageWhenEmpty (const String& newMessage);
  23152. /** Returns the message that is displayed when there are no properties.
  23153. @see setMessageWhenEmpty
  23154. */
  23155. const String& getMessageWhenEmpty() const throw();
  23156. /** @internal */
  23157. void paint (Graphics& g);
  23158. /** @internal */
  23159. void resized();
  23160. juce_UseDebuggingNewOperator
  23161. private:
  23162. Viewport* viewport;
  23163. Component* propertyHolderComponent;
  23164. String messageWhenEmpty;
  23165. void updatePropHolderLayout() const;
  23166. void updatePropHolderLayout (const int width) const;
  23167. };
  23168. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  23169. /********* End of inlined file: juce_PropertyPanel.h *********/
  23170. /**
  23171. A type of UI component that displays the parameters of an AudioProcessor as
  23172. a simple list of sliders.
  23173. This can be used for showing an editor for a processor that doesn't supply
  23174. its own custom editor.
  23175. @see AudioProcessor
  23176. */
  23177. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  23178. {
  23179. public:
  23180. GenericAudioProcessorEditor (AudioProcessor* const owner);
  23181. ~GenericAudioProcessorEditor();
  23182. void paint (Graphics& g);
  23183. void resized();
  23184. juce_UseDebuggingNewOperator
  23185. private:
  23186. PropertyPanel* panel;
  23187. };
  23188. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23189. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23190. #endif
  23191. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23192. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23193. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23194. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23195. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23196. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23197. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23198. /********* Start of inlined file: juce_AudioSource.h *********/
  23199. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23200. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23201. /**
  23202. Used by AudioSource::getNextAudioBlock().
  23203. */
  23204. struct JUCE_API AudioSourceChannelInfo
  23205. {
  23206. /** The destination buffer to fill with audio data.
  23207. When the AudioSource::getNextAudioBlock() method is called, the active section
  23208. of this buffer should be filled with whatever output the source produces.
  23209. Only the samples specified by the startSample and numSamples members of this structure
  23210. should be affected by the call.
  23211. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23212. method can be treated as the input if the source is performing some kind of filter operation,
  23213. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23214. a handy way of doing this.
  23215. The number of channels in the buffer could be anything, so the AudioSource
  23216. must cope with this in whatever way is appropriate for its function.
  23217. */
  23218. AudioSampleBuffer* buffer;
  23219. /** The first sample in the buffer from which the callback is expected
  23220. to write data. */
  23221. int startSample;
  23222. /** The number of samples in the buffer which the callback is expected to
  23223. fill with data. */
  23224. int numSamples;
  23225. /** Convenient method to clear the buffer if the source is not producing any data. */
  23226. void clearActiveBufferRegion() const
  23227. {
  23228. if (buffer != 0)
  23229. buffer->clear (startSample, numSamples);
  23230. }
  23231. };
  23232. /**
  23233. Base class for objects that can produce a continuous stream of audio.
  23234. @see AudioFormatReaderSource, ResamplingAudioSource
  23235. */
  23236. class JUCE_API AudioSource
  23237. {
  23238. protected:
  23239. /** Creates an AudioSource. */
  23240. AudioSource() throw() {}
  23241. public:
  23242. /** Destructor. */
  23243. virtual ~AudioSource() {}
  23244. /** Tells the source to prepare for playing.
  23245. The source can use this opportunity to initialise anything it needs to.
  23246. Note that this method could be called more than once in succession without
  23247. a matching call to releaseResources(), so make sure your code is robust and
  23248. can handle that kind of situation.
  23249. @param samplesPerBlockExpected the number of samples that the source
  23250. will be expected to supply each time its
  23251. getNextAudioBlock() method is called. This
  23252. number may vary slightly, because it will be dependent
  23253. on audio hardware callbacks, and these aren't
  23254. guaranteed to always use a constant block size, so
  23255. the source should be able to cope with small variations.
  23256. @param sampleRate the sample rate that the output will be used at - this
  23257. is needed by sources such as tone generators.
  23258. @see releaseResources, getNextAudioBlock
  23259. */
  23260. virtual void prepareToPlay (int samplesPerBlockExpected,
  23261. double sampleRate) = 0;
  23262. /** Allows the source to release anything it no longer needs after playback has stopped.
  23263. This will be called when the source is no longer going to have its getNextAudioBlock()
  23264. method called, so it should release any spare memory, etc. that it might have
  23265. allocated during the prepareToPlay() call.
  23266. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23267. releaseResources(), and it may be called more than once in succession, so make sure your
  23268. code is robust and doesn't make any assumptions about when it will be called.
  23269. @see prepareToPlay, getNextAudioBlock
  23270. */
  23271. virtual void releaseResources() = 0;
  23272. /** Called repeatedly to fetch subsequent blocks of audio data.
  23273. After calling the prepareToPlay() method, this callback will be made each
  23274. time the audio playback hardware (or whatever other destination the audio
  23275. data is going to) needs another block of data.
  23276. It will generally be called on a high-priority system thread, or possibly even
  23277. an interrupt, so be careful not to do too much work here, as that will cause
  23278. audio glitches!
  23279. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23280. */
  23281. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23282. };
  23283. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23284. /********* End of inlined file: juce_AudioSource.h *********/
  23285. /**
  23286. A type of AudioSource which can be repositioned.
  23287. The basic AudioSource just streams continuously with no idea of a current
  23288. time or length, so the PositionableAudioSource is used for a finite stream
  23289. that has a current read position.
  23290. @see AudioSource, AudioTransportSource
  23291. */
  23292. class JUCE_API PositionableAudioSource : public AudioSource
  23293. {
  23294. protected:
  23295. /** Creates the PositionableAudioSource. */
  23296. PositionableAudioSource() throw() {}
  23297. public:
  23298. /** Destructor */
  23299. ~PositionableAudioSource() {}
  23300. /** Tells the stream to move to a new position.
  23301. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23302. should return samples from this position.
  23303. Note that this may be called on a different thread to getNextAudioBlock(),
  23304. so the subclass should make sure it's synchronised.
  23305. */
  23306. virtual void setNextReadPosition (int newPosition) = 0;
  23307. /** Returns the position from which the next block will be returned.
  23308. @see setNextReadPosition
  23309. */
  23310. virtual int getNextReadPosition() const = 0;
  23311. /** Returns the total length of the stream (in samples). */
  23312. virtual int getTotalLength() const = 0;
  23313. /** Returns true if this source is actually playing in a loop. */
  23314. virtual bool isLooping() const = 0;
  23315. };
  23316. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23317. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23318. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23319. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23320. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23321. class AudioFormat;
  23322. /**
  23323. Reads samples from an audio file stream.
  23324. A subclass that reads a specific type of audio format will be created by
  23325. an AudioFormat object.
  23326. @see AudioFormat, AudioFormatWriter
  23327. */
  23328. class JUCE_API AudioFormatReader
  23329. {
  23330. protected:
  23331. /** Creates an AudioFormatReader object.
  23332. @param sourceStream the stream to read from - this will be deleted
  23333. by this object when it is no longer needed. (Some
  23334. specialised readers might not use this parameter and
  23335. can leave it as 0).
  23336. @param formatName the description that will be returned by the getFormatName()
  23337. method
  23338. */
  23339. AudioFormatReader (InputStream* const sourceStream,
  23340. const String& formatName);
  23341. public:
  23342. /** Destructor. */
  23343. virtual ~AudioFormatReader();
  23344. /** Returns a description of what type of format this is.
  23345. E.g. "AIFF"
  23346. */
  23347. const String getFormatName() const throw() { return formatName; }
  23348. /** Reads samples from the stream.
  23349. @param destSamples an array of buffers into which the sample data for each
  23350. channel will be written.
  23351. If the format is fixed-point, each channel will be written
  23352. as an array of 32-bit signed integers using the full
  23353. range -0x80000000 to 0x7fffffff, regardless of the source's
  23354. bit-depth. If it is a floating-point format, you should cast
  23355. the resulting array to a (float**) to get the values (in the
  23356. range -1.0 to 1.0 or beyond)
  23357. If the format is stereo, then destSamples[0] is the left channel
  23358. data, and destSamples[1] is the right channel.
  23359. The array passed in should be zero-terminated, and it's ok to
  23360. pass in an array with a different number of channels than
  23361. the number in the stream, so if you pass in an array with only
  23362. one channel and the stream is stereo, the reader will
  23363. put a merged sum of the stereo channels into the single
  23364. destination channel.
  23365. @param startSample the offset into the audio stream from which the samples
  23366. should be read, as a number of samples from the start of the
  23367. stream. It's ok for this to be beyond the start or end of the
  23368. available data - any samples that can't be read will be padded
  23369. with zeros.
  23370. @param numSamples the number of samples to read. If this is greater than the
  23371. number of samples available, the result will be padded with
  23372. zeros
  23373. @returns true if the operation succeeded, false if there was an error. Note
  23374. that reading sections of data beyond the extent of the stream isn't an
  23375. error - the reader should just return zeros for these regions
  23376. @see readMaxLevels
  23377. */
  23378. virtual bool read (int** destSamples,
  23379. int64 startSample,
  23380. int numSamples) = 0;
  23381. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23382. This will read a block of samples from the stream, and measure the
  23383. highest and lowest sample levels from the channels in that section, returning
  23384. these as normalised floating-point levels.
  23385. @param startSample the offset into the audio stream to start reading from. It's
  23386. ok for this to be beyond the start or end of the stream.
  23387. @param numSamples how many samples to read
  23388. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23389. @param highestLeft on return, this is the highest absolute sample from the left channel
  23390. @param lowestRight on return, this is the lowest absolute sample from the right
  23391. channel (if there is one)
  23392. @param highestRight on return, this is the highest absolute sample from the right
  23393. channel (if there is one)
  23394. @see read
  23395. */
  23396. virtual void readMaxLevels (int64 startSample,
  23397. int64 numSamples,
  23398. float& lowestLeft,
  23399. float& highestLeft,
  23400. float& lowestRight,
  23401. float& highestRight);
  23402. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23403. This will read from the source, either forwards or backwards between two sample
  23404. positions, until it finds a sample whose magnitude lies between two specified levels.
  23405. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23406. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23407. points when you're searching for a continuous range of samples
  23408. @param startSample the first sample to look at
  23409. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23410. the search will go backwards
  23411. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23412. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23413. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23414. of this many consecutive samples, all of which lie
  23415. within the target range. When it finds such a sequence,
  23416. it returns the position of the first in-range sample
  23417. it found (i.e. the earliest one if scanning forwards, the
  23418. latest one if scanning backwards)
  23419. */
  23420. int64 searchForLevel (int64 startSample,
  23421. int64 numSamplesToSearch,
  23422. const double magnitudeRangeMinimum,
  23423. const double magnitudeRangeMaximum,
  23424. const int minimumConsecutiveSamples);
  23425. /** The sample-rate of the stream. */
  23426. double sampleRate;
  23427. /** The number of bits per sample, e.g. 16, 24, 32. */
  23428. unsigned int bitsPerSample;
  23429. /** The total number of samples in the audio stream. */
  23430. int64 lengthInSamples;
  23431. /** The total number of channels in the audio stream. */
  23432. unsigned int numChannels;
  23433. /** Indicates whether the data is floating-point or fixed. */
  23434. bool usesFloatingPointData;
  23435. /** A set of metadata values that the reader has pulled out of the stream.
  23436. Exactly what these values are depends on the format, so you can
  23437. check out the format implementation code to see what kind of stuff
  23438. they understand.
  23439. */
  23440. StringPairArray metadataValues;
  23441. /** The input stream, for use by subclasses. */
  23442. InputStream* input;
  23443. juce_UseDebuggingNewOperator
  23444. private:
  23445. String formatName;
  23446. AudioFormatReader (const AudioFormatReader&);
  23447. const AudioFormatReader& operator= (const AudioFormatReader&);
  23448. };
  23449. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23450. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23451. /**
  23452. A type of AudioSource that will read from an AudioFormatReader.
  23453. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23454. */
  23455. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23456. {
  23457. public:
  23458. /** Creates an AudioFormatReaderSource for a given reader.
  23459. @param sourceReader the reader to use as the data source
  23460. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23461. when this object is deleted; if false it will be
  23462. left up to the caller to manage its lifetime
  23463. */
  23464. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23465. const bool deleteReaderWhenThisIsDeleted);
  23466. /** Destructor. */
  23467. ~AudioFormatReaderSource();
  23468. /** Toggles loop-mode.
  23469. If set to true, it will continuously loop the input source. If false,
  23470. it will just emit silence after the source has finished.
  23471. @see isLooping
  23472. */
  23473. void setLooping (const bool shouldLoop) throw();
  23474. /** Returns whether loop-mode is turned on or not. */
  23475. bool isLooping() const { return looping; }
  23476. /** Returns the reader that's being used. */
  23477. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23478. /** Implementation of the AudioSource method. */
  23479. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23480. /** Implementation of the AudioSource method. */
  23481. void releaseResources();
  23482. /** Implementation of the AudioSource method. */
  23483. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23484. /** Implements the PositionableAudioSource method. */
  23485. void setNextReadPosition (int newPosition);
  23486. /** Implements the PositionableAudioSource method. */
  23487. int getNextReadPosition() const;
  23488. /** Implements the PositionableAudioSource method. */
  23489. int getTotalLength() const;
  23490. juce_UseDebuggingNewOperator
  23491. private:
  23492. AudioFormatReader* reader;
  23493. bool deleteReader;
  23494. int volatile nextPlayPos;
  23495. bool volatile looping;
  23496. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23497. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23498. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23499. };
  23500. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23501. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23502. #endif
  23503. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23504. #endif
  23505. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23506. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23507. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23508. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23509. /**
  23510. Wrapper class to continuously stream audio from an audio source to an
  23511. AudioIODevice.
  23512. This object acts as an AudioIODeviceCallback, so can be attached to an
  23513. output device, and will stream audio from an AudioSource.
  23514. */
  23515. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23516. {
  23517. public:
  23518. /** Creates an empty AudioSourcePlayer. */
  23519. AudioSourcePlayer();
  23520. /** Destructor.
  23521. Make sure this object isn't still being used by an AudioIODevice before
  23522. deleting it!
  23523. */
  23524. virtual ~AudioSourcePlayer();
  23525. /** Changes the current audio source to play from.
  23526. If the source passed in is already being used, this method will do nothing.
  23527. If the source is not null, its prepareToPlay() method will be called
  23528. before it starts being used for playback.
  23529. If there's another source currently playing, its releaseResources() method
  23530. will be called after it has been swapped for the new one.
  23531. @param newSource the new source to use - this will NOT be deleted
  23532. by this object when no longer needed, so it's the
  23533. caller's responsibility to manage it.
  23534. */
  23535. void setSource (AudioSource* newSource);
  23536. /** Returns the source that's playing.
  23537. May return 0 if there's no source.
  23538. */
  23539. AudioSource* getCurrentSource() const throw() { return source; }
  23540. /** Sets a gain to apply to the audio data. */
  23541. void setGain (const float newGain) throw();
  23542. /** Implementation of the AudioIODeviceCallback method. */
  23543. void audioDeviceIOCallback (const float** inputChannelData,
  23544. int totalNumInputChannels,
  23545. float** outputChannelData,
  23546. int totalNumOutputChannels,
  23547. int numSamples);
  23548. /** Implementation of the AudioIODeviceCallback method. */
  23549. void audioDeviceAboutToStart (AudioIODevice* device);
  23550. /** Implementation of the AudioIODeviceCallback method. */
  23551. void audioDeviceStopped();
  23552. juce_UseDebuggingNewOperator
  23553. private:
  23554. CriticalSection readLock;
  23555. AudioSource* source;
  23556. double sampleRate;
  23557. int bufferSize;
  23558. float* channels [128];
  23559. float* outputChans [128];
  23560. const float* inputChans [128];
  23561. AudioSampleBuffer tempBuffer;
  23562. float lastGain, gain;
  23563. AudioSourcePlayer (const AudioSourcePlayer&);
  23564. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23565. };
  23566. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23567. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23568. #endif
  23569. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23570. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23571. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23572. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23573. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23574. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23575. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23576. /**
  23577. An AudioSource which takes another source as input, and buffers it using a thread.
  23578. Create this as a wrapper around another thread, and it will read-ahead with
  23579. a background thread to smooth out playback. You can either create one of these
  23580. directly, or use it indirectly using an AudioTransportSource.
  23581. @see PositionableAudioSource, AudioTransportSource
  23582. */
  23583. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23584. {
  23585. public:
  23586. /** Creates a BufferingAudioSource.
  23587. @param source the input source to read from
  23588. @param deleteSourceWhenDeleted if true, then the input source object will
  23589. be deleted when this object is deleted
  23590. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23591. */
  23592. BufferingAudioSource (PositionableAudioSource* source,
  23593. const bool deleteSourceWhenDeleted,
  23594. int numberOfSamplesToBuffer);
  23595. /** Destructor.
  23596. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23597. flag was set in the constructor.
  23598. */
  23599. ~BufferingAudioSource();
  23600. /** Implementation of the AudioSource method. */
  23601. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23602. /** Implementation of the AudioSource method. */
  23603. void releaseResources();
  23604. /** Implementation of the AudioSource method. */
  23605. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23606. /** Implements the PositionableAudioSource method. */
  23607. void setNextReadPosition (int newPosition);
  23608. /** Implements the PositionableAudioSource method. */
  23609. int getNextReadPosition() const;
  23610. /** Implements the PositionableAudioSource method. */
  23611. int getTotalLength() const { return source->getTotalLength(); }
  23612. /** Implements the PositionableAudioSource method. */
  23613. bool isLooping() const { return source->isLooping(); }
  23614. juce_UseDebuggingNewOperator
  23615. private:
  23616. PositionableAudioSource* source;
  23617. bool deleteSourceWhenDeleted;
  23618. int numberOfSamplesToBuffer;
  23619. AudioSampleBuffer buffer;
  23620. CriticalSection bufferStartPosLock;
  23621. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23622. bool wasSourceLooping;
  23623. double volatile sampleRate;
  23624. friend class SharedBufferingAudioSourceThread;
  23625. bool readNextBufferChunk();
  23626. void readBufferSection (int start, int length, int bufferOffset);
  23627. BufferingAudioSource (const BufferingAudioSource&);
  23628. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23629. };
  23630. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23631. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23632. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23633. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23634. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23635. /**
  23636. A type of AudioSource that takes an input source and changes its sample rate.
  23637. @see AudioSource
  23638. */
  23639. class JUCE_API ResamplingAudioSource : public AudioSource
  23640. {
  23641. public:
  23642. /** Creates a ResamplingAudioSource for a given input source.
  23643. @param inputSource the input source to read from
  23644. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23645. this object is deleted
  23646. */
  23647. ResamplingAudioSource (AudioSource* const inputSource,
  23648. const bool deleteInputWhenDeleted);
  23649. /** Destructor. */
  23650. ~ResamplingAudioSource();
  23651. /** Changes the resampling ratio.
  23652. (This value can be changed at any time, even while the source is running).
  23653. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23654. values will speed it up; lower values will slow it
  23655. down. The ratio must be greater than 0
  23656. */
  23657. void setResamplingRatio (const double samplesInPerOutputSample);
  23658. /** Returns the current resampling ratio.
  23659. This is the value that was set by setResamplingRatio().
  23660. */
  23661. double getResamplingRatio() const throw() { return ratio; }
  23662. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23663. void releaseResources();
  23664. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23665. juce_UseDebuggingNewOperator
  23666. private:
  23667. AudioSource* const input;
  23668. const bool deleteInputWhenDeleted;
  23669. double ratio, lastRatio;
  23670. AudioSampleBuffer buffer;
  23671. int bufferPos, sampsInBuffer;
  23672. double subSampleOffset;
  23673. double coefficients[6];
  23674. CriticalSection ratioLock;
  23675. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23676. void createLowPass (const double proportionalRate);
  23677. struct FilterState
  23678. {
  23679. double x1, x2, y1, y2;
  23680. };
  23681. FilterState filterStates[2];
  23682. void resetFilters();
  23683. void applyFilter (float* samples, int num, FilterState& fs);
  23684. ResamplingAudioSource (const ResamplingAudioSource&);
  23685. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23686. };
  23687. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23688. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23689. /**
  23690. An AudioSource that takes a PositionableAudioSource and allows it to be
  23691. played, stopped, started, etc.
  23692. This can also be told use a buffer and background thread to read ahead, and
  23693. if can correct for different sample-rates.
  23694. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23695. to control playback of an audio file.
  23696. @see AudioSource, AudioSourcePlayer
  23697. */
  23698. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23699. public ChangeBroadcaster
  23700. {
  23701. public:
  23702. /** Creates an AudioTransportSource.
  23703. After creating one of these, use the setSource() method to select an input source.
  23704. */
  23705. AudioTransportSource();
  23706. /** Destructor. */
  23707. ~AudioTransportSource();
  23708. /** Sets the reader that is being used as the input source.
  23709. This will stop playback, reset the position to 0 and change to the new reader.
  23710. The source passed in will not be deleted by this object, so must be managed by
  23711. the caller.
  23712. @param newSource the new input source to use. This may be zero
  23713. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23714. is zero, no reading ahead will be done; if it's
  23715. greater than zero, a BufferingAudioSource will be used
  23716. to do the reading-ahead
  23717. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23718. rate of the source, and playback will be sample-rate
  23719. adjusted to maintain playback at the correct pitch. If
  23720. this is 0, no sample-rate adjustment will be performed
  23721. */
  23722. void setSource (PositionableAudioSource* const newSource,
  23723. int readAheadBufferSize = 0,
  23724. double sourceSampleRateToCorrectFor = 0.0);
  23725. /** Changes the current playback position in the source stream.
  23726. The next time the getNextAudioBlock() method is called, this
  23727. is the time from which it'll read data.
  23728. @see getPosition
  23729. */
  23730. void setPosition (double newPosition);
  23731. /** Returns the position that the next data block will be read from
  23732. This is a time in seconds.
  23733. */
  23734. double getCurrentPosition() const;
  23735. /** Returns true if the player has stopped because its input stream ran out of data.
  23736. */
  23737. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23738. /** Starts playing (if a source has been selected).
  23739. If it starts playing, this will send a message to any ChangeListeners
  23740. that are registered with this object.
  23741. */
  23742. void start();
  23743. /** Stops playing.
  23744. If it's actually playing, this will send a message to any ChangeListeners
  23745. that are registered with this object.
  23746. */
  23747. void stop();
  23748. /** Returns true if it's currently playing. */
  23749. bool isPlaying() const throw() { return playing; }
  23750. /** Changes the gain to apply to the output.
  23751. @param newGain a factor by which to multiply the outgoing samples,
  23752. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23753. */
  23754. void setGain (const float newGain) throw();
  23755. /** Returns the current gain setting.
  23756. @see setGain
  23757. */
  23758. float getGain() const throw() { return gain; }
  23759. /** Implementation of the AudioSource method. */
  23760. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23761. /** Implementation of the AudioSource method. */
  23762. void releaseResources();
  23763. /** Implementation of the AudioSource method. */
  23764. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23765. /** Implements the PositionableAudioSource method. */
  23766. void setNextReadPosition (int newPosition);
  23767. /** Implements the PositionableAudioSource method. */
  23768. int getNextReadPosition() const;
  23769. /** Implements the PositionableAudioSource method. */
  23770. int getTotalLength() const;
  23771. /** Implements the PositionableAudioSource method. */
  23772. bool isLooping() const;
  23773. juce_UseDebuggingNewOperator
  23774. private:
  23775. PositionableAudioSource* source;
  23776. ResamplingAudioSource* resamplerSource;
  23777. BufferingAudioSource* bufferingSource;
  23778. PositionableAudioSource* positionableSource;
  23779. AudioSource* masterSource;
  23780. CriticalSection callbackLock;
  23781. float volatile gain, lastGain;
  23782. bool volatile playing, stopped;
  23783. double sampleRate, sourceSampleRate;
  23784. int blockSize, readAheadBufferSize;
  23785. bool isPrepared, inputStreamEOF;
  23786. AudioTransportSource (const AudioTransportSource&);
  23787. const AudioTransportSource& operator= (const AudioTransportSource&);
  23788. };
  23789. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23790. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23791. #endif
  23792. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23793. #endif
  23794. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23795. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23796. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23797. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23798. /**
  23799. An AudioSource that takes the audio from another source, and re-maps its
  23800. input and output channels to a different arrangement.
  23801. You can use this to increase or decrease the number of channels that an
  23802. audio source uses, or to re-order those channels.
  23803. Call the reset() method before using it to set up a default mapping, and then
  23804. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23805. create an appropriate mapping, otherwise no channels will be connected and
  23806. it'll produce silence.
  23807. @see AudioSource
  23808. */
  23809. class ChannelRemappingAudioSource : public AudioSource
  23810. {
  23811. public:
  23812. /** Creates a remapping source that will pass on audio from the given input.
  23813. @param source the input source to use. Make sure that this doesn't
  23814. get deleted before the ChannelRemappingAudioSource object
  23815. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23816. when this object is deleted, if false, the caller is
  23817. responsible for its deletion
  23818. */
  23819. ChannelRemappingAudioSource (AudioSource* const source,
  23820. const bool deleteSourceWhenDeleted);
  23821. /** Destructor. */
  23822. ~ChannelRemappingAudioSource();
  23823. /** Specifies a number of channels that this audio source must produce from its
  23824. getNextAudioBlock() callback.
  23825. */
  23826. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23827. /** Clears any mapped channels.
  23828. After this, no channels are mapped, so this object will produce silence. Create
  23829. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23830. */
  23831. void clearAllMappings() throw();
  23832. /** Creates an input channel mapping.
  23833. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23834. data will be sent to destChannelIndex of our input source.
  23835. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23836. source specified when this object was created).
  23837. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23838. during our getNextAudioBlock() callback
  23839. */
  23840. void setInputChannelMapping (const int destChannelIndex,
  23841. const int sourceChannelIndex) throw();
  23842. /** Creates an output channel mapping.
  23843. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23844. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23845. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23846. (i.e. the source specified when this object was created).
  23847. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23848. during our getNextAudioBlock() callback
  23849. */
  23850. void setOutputChannelMapping (const int sourceChannelIndex,
  23851. const int destChannelIndex) throw();
  23852. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23853. our input audio source.
  23854. */
  23855. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23856. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23857. source will be sent to.
  23858. */
  23859. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23860. /** Returns an XML object to encapsulate the state of the mappings.
  23861. @see restoreFromXml
  23862. */
  23863. XmlElement* createXml() const throw();
  23864. /** Restores the mappings from an XML object created by createXML().
  23865. @see createXml
  23866. */
  23867. void restoreFromXml (const XmlElement& e) throw();
  23868. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23869. void releaseResources();
  23870. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23871. juce_UseDebuggingNewOperator
  23872. private:
  23873. int requiredNumberOfChannels;
  23874. Array <int> remappedInputs, remappedOutputs;
  23875. AudioSource* const source;
  23876. const bool deleteSourceWhenDeleted;
  23877. AudioSampleBuffer buffer;
  23878. AudioSourceChannelInfo remappedInfo;
  23879. CriticalSection lock;
  23880. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23881. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23882. };
  23883. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23884. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23885. #endif
  23886. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23887. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23888. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23889. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23890. /**
  23891. An AudioSource that performs an IIR filter on another source.
  23892. */
  23893. class JUCE_API IIRFilterAudioSource : public AudioSource
  23894. {
  23895. public:
  23896. /** Creates a IIRFilterAudioSource for a given input source.
  23897. @param inputSource the input source to read from
  23898. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23899. this object is deleted
  23900. */
  23901. IIRFilterAudioSource (AudioSource* const inputSource,
  23902. const bool deleteInputWhenDeleted);
  23903. /** Destructor. */
  23904. ~IIRFilterAudioSource();
  23905. /** Changes the filter to use the same parameters as the one being passed in.
  23906. */
  23907. void setFilterParameters (const IIRFilter& newSettings);
  23908. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23909. void releaseResources();
  23910. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23911. juce_UseDebuggingNewOperator
  23912. private:
  23913. AudioSource* const input;
  23914. const bool deleteInputWhenDeleted;
  23915. OwnedArray <IIRFilter> iirFilters;
  23916. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23917. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23918. };
  23919. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23920. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23921. #endif
  23922. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23923. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23924. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23925. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23926. /**
  23927. An AudioSource that mixes together the output of a set of other AudioSources.
  23928. Input sources can be added and removed while the mixer is running as long as their
  23929. prepareToPlay() and releaseResources() methods are called before and after adding
  23930. them to the mixer.
  23931. */
  23932. class JUCE_API MixerAudioSource : public AudioSource
  23933. {
  23934. public:
  23935. /** Creates a MixerAudioSource.
  23936. */
  23937. MixerAudioSource();
  23938. /** Destructor. */
  23939. ~MixerAudioSource();
  23940. /** Adds an input source to the mixer.
  23941. If the mixer is running you'll need to make sure that the input source
  23942. is ready to play by calling its prepareToPlay() method before adding it.
  23943. If the mixer is stopped, then its input sources will be automatically
  23944. prepared when the mixer's prepareToPlay() method is called.
  23945. @param newInput the source to add to the mixer
  23946. @param deleteWhenRemoved if true, then this source will be deleted when
  23947. the mixer is deleted or when removeAllInputs() is
  23948. called (unless the source is previously removed
  23949. with the removeInputSource method)
  23950. */
  23951. void addInputSource (AudioSource* newInput,
  23952. const bool deleteWhenRemoved);
  23953. /** Removes an input source.
  23954. If the mixer is running, this will remove the source but not call its
  23955. releaseResources() method, so the caller might want to do this manually.
  23956. @param input the source to remove
  23957. @param deleteSource whether to delete this source after it's been removed
  23958. */
  23959. void removeInputSource (AudioSource* input,
  23960. const bool deleteSource);
  23961. /** Removes all the input sources.
  23962. If the mixer is running, this will remove the sources but not call their
  23963. releaseResources() method, so the caller might want to do this manually.
  23964. Any sources which were added with the deleteWhenRemoved flag set will be
  23965. deleted by this method.
  23966. */
  23967. void removeAllInputs();
  23968. /** Implementation of the AudioSource method.
  23969. This will call prepareToPlay() on all its input sources.
  23970. */
  23971. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23972. /** Implementation of the AudioSource method.
  23973. This will call releaseResources() on all its input sources.
  23974. */
  23975. void releaseResources();
  23976. /** Implementation of the AudioSource method. */
  23977. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23978. juce_UseDebuggingNewOperator
  23979. private:
  23980. VoidArray inputs;
  23981. BitArray inputsToDelete;
  23982. CriticalSection lock;
  23983. AudioSampleBuffer tempBuffer;
  23984. double currentSampleRate;
  23985. int bufferSizeExpected;
  23986. MixerAudioSource (const MixerAudioSource&);
  23987. const MixerAudioSource& operator= (const MixerAudioSource&);
  23988. };
  23989. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23990. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23991. #endif
  23992. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23993. #endif
  23994. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23995. #endif
  23996. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23997. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23998. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23999. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24000. /**
  24001. A simple AudioSource that generates a sine wave.
  24002. */
  24003. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24004. {
  24005. public:
  24006. /** Creates a ToneGeneratorAudioSource. */
  24007. ToneGeneratorAudioSource();
  24008. /** Destructor. */
  24009. ~ToneGeneratorAudioSource();
  24010. /** Sets the signal's amplitude. */
  24011. void setAmplitude (const float newAmplitude);
  24012. /** Sets the signal's frequency. */
  24013. void setFrequency (const double newFrequencyHz);
  24014. /** Implementation of the AudioSource method. */
  24015. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24016. /** Implementation of the AudioSource method. */
  24017. void releaseResources();
  24018. /** Implementation of the AudioSource method. */
  24019. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24020. juce_UseDebuggingNewOperator
  24021. private:
  24022. double frequency, sampleRate;
  24023. double currentPhase, phasePerSample;
  24024. float amplitude;
  24025. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24026. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24027. };
  24028. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24029. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24030. #endif
  24031. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24032. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  24033. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24034. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24035. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  24036. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24037. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24038. class AudioDeviceManager;
  24039. class Component;
  24040. /**
  24041. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24042. To get a list of available audio driver types, use the createDeviceTypes()
  24043. method. Each of the objects returned can then be used to list the available
  24044. devices of that type. E.g.
  24045. @code
  24046. OwnedArray <AudioIODeviceType> types;
  24047. AudioIODeviceType::createDeviceTypes (types);
  24048. for (int i = 0; i < types.size(); ++i)
  24049. {
  24050. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24051. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24052. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24053. for (int j = 0; j < deviceNames.size(); ++j)
  24054. {
  24055. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24056. ...
  24057. }
  24058. }
  24059. @endcode
  24060. For an easier way of managing audio devices and their settings, have a look at the
  24061. AudioDeviceManager class.
  24062. @see AudioIODevice, AudioDeviceManager
  24063. */
  24064. class JUCE_API AudioIODeviceType
  24065. {
  24066. public:
  24067. /** Returns the name of this type of driver that this object manages.
  24068. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24069. */
  24070. const String& getTypeName() const throw() { return typeName; }
  24071. /** Refreshes the object's cached list of known devices.
  24072. This must be called at least once before calling getDeviceNames() or any of
  24073. the other device creation methods.
  24074. */
  24075. virtual void scanForDevices() = 0;
  24076. /** Returns the list of available devices of this type.
  24077. The scanForDevices() method must have been called to create this list.
  24078. @param wantInputNames only really used by DirectSound where devices are split up
  24079. into inputs and outputs, this indicates whether to use
  24080. the input or output name to refer to a pair of devices.
  24081. */
  24082. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  24083. /** Returns the name of the default device.
  24084. This will be one of the names from the getDeviceNames() list.
  24085. @param forInput if true, this means that a default input device should be
  24086. returned; if false, it should return the default output
  24087. */
  24088. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  24089. /** Returns the index of a given device in the list of device names.
  24090. If asInput is true, it shows the index in the inputs list, otherwise it
  24091. looks for it in the outputs list.
  24092. */
  24093. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  24094. /** Returns true if two different devices can be used for the input and output.
  24095. */
  24096. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24097. /** Creates one of the devices of this type.
  24098. The deviceName must be one of the strings returned by getDeviceNames(), and
  24099. scanForDevices() must have been called before this method is used.
  24100. */
  24101. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24102. const String& inputDeviceName) = 0;
  24103. struct DeviceSetupDetails
  24104. {
  24105. AudioDeviceManager* manager;
  24106. int minNumInputChannels, maxNumInputChannels;
  24107. int minNumOutputChannels, maxNumOutputChannels;
  24108. bool useStereoPairs;
  24109. };
  24110. /** Destructor. */
  24111. virtual ~AudioIODeviceType();
  24112. protected:
  24113. AudioIODeviceType (const tchar* const typeName);
  24114. private:
  24115. String typeName;
  24116. AudioIODeviceType (const AudioIODeviceType&);
  24117. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  24118. };
  24119. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24120. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  24121. /********* Start of inlined file: juce_MidiOutput.h *********/
  24122. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24123. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24124. /**
  24125. Represents a midi output device.
  24126. To create one of these, use the static getDevices() method to find out what
  24127. outputs are available, then use the openDevice() method to try to open one.
  24128. @see MidiInput
  24129. */
  24130. class JUCE_API MidiOutput : private Thread
  24131. {
  24132. public:
  24133. /** Returns a list of the available midi output devices.
  24134. You can open one of the devices by passing its index into the
  24135. openDevice() method.
  24136. @see getDefaultDeviceIndex, openDevice
  24137. */
  24138. static const StringArray getDevices();
  24139. /** Returns the index of the default midi output device to use.
  24140. This refers to the index in the list returned by getDevices().
  24141. */
  24142. static int getDefaultDeviceIndex();
  24143. /** Tries to open one of the midi output devices.
  24144. This will return a MidiOutput object if it manages to open it. You can then
  24145. send messages to this device, and delete it when no longer needed.
  24146. If the device can't be opened, this will return a null pointer.
  24147. @param deviceIndex the index of a device from the list returned by getDevices()
  24148. @see getDevices
  24149. */
  24150. static MidiOutput* openDevice (int deviceIndex);
  24151. #if JUCE_LINUX || DOXYGEN
  24152. /** LINUX ONLY - This will try to create a new midi output device.
  24153. This will attempt to create a new midi output device that other apps can connect
  24154. to and use as their midi input.
  24155. Returns 0 if a device can't be created.
  24156. @param deviceName the name to use for the new device
  24157. */
  24158. static MidiOutput* createNewDevice (const String& deviceName);
  24159. #endif
  24160. /** Destructor. */
  24161. virtual ~MidiOutput();
  24162. /** Makes this device output a midi message.
  24163. @see MidiMessage
  24164. */
  24165. virtual void sendMessageNow (const MidiMessage& message);
  24166. /** Sends a midi reset to the device. */
  24167. virtual void reset();
  24168. /** Returns the current volume setting for this device. */
  24169. virtual bool getVolume (float& leftVol,
  24170. float& rightVol);
  24171. /** Changes the overall volume for this device. */
  24172. virtual void setVolume (float leftVol,
  24173. float rightVol);
  24174. /** This lets you supply a block of messages that will be sent out at some point
  24175. in the future.
  24176. The MidiOutput class has an internal thread that can send out timestamped
  24177. messages - this appends a set of messages to its internal buffer, ready for
  24178. sending.
  24179. This will only work if you've already started the thread with startBackgroundThread().
  24180. A time is supplied, at which the block of messages should be sent. This time uses
  24181. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24182. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24183. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24184. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24185. real time.
  24186. */
  24187. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24188. const double millisecondCounterToStartAt,
  24189. double samplesPerSecondForBuffer) throw();
  24190. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24191. */
  24192. virtual void clearAllPendingMessages() throw();
  24193. /** Starts up a background thread so that the device can send blocks of data.
  24194. Call this to get the device ready, before using sendBlockOfMessages().
  24195. */
  24196. virtual void startBackgroundThread() throw();
  24197. /** Stops the background thread, and clears any pending midi events.
  24198. @see startBackgroundThread
  24199. */
  24200. virtual void stopBackgroundThread() throw();
  24201. juce_UseDebuggingNewOperator
  24202. protected:
  24203. void* internal;
  24204. struct PendingMessage
  24205. {
  24206. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24207. MidiMessage message;
  24208. PendingMessage* next;
  24209. juce_UseDebuggingNewOperator
  24210. };
  24211. CriticalSection lock;
  24212. PendingMessage* firstMessage;
  24213. MidiOutput() throw();
  24214. MidiOutput (const MidiOutput&);
  24215. void run();
  24216. };
  24217. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24218. /********* End of inlined file: juce_MidiOutput.h *********/
  24219. /********* Start of inlined file: juce_ComboBox.h *********/
  24220. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24221. #define __JUCE_COMBOBOX_JUCEHEADER__
  24222. /********* Start of inlined file: juce_Label.h *********/
  24223. #ifndef __JUCE_LABEL_JUCEHEADER__
  24224. #define __JUCE_LABEL_JUCEHEADER__
  24225. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24226. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24227. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24228. /**
  24229. Object for monitoring a component, and later testing whether it's still valid.
  24230. Slightly obscure, this one, but it's used internally for making sure that
  24231. after some callbacks, a component hasn't been deleted. It's more reliable than
  24232. just using isValidComponent(), which can provide false-positives if a new
  24233. component is created at the same memory location as an old one.
  24234. */
  24235. class JUCE_API ComponentDeletionWatcher
  24236. {
  24237. public:
  24238. /** Creates a watcher for a given component.
  24239. The component must be valid at the time it's passed in.
  24240. */
  24241. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24242. /** Destructor. */
  24243. ~ComponentDeletionWatcher() throw();
  24244. /** Returns true if the component has been deleted since the time that this
  24245. object was created.
  24246. */
  24247. bool hasBeenDeleted() const throw();
  24248. /** Returns the component that's being watched, or null if it has been deleted. */
  24249. const Component* getComponent() const throw();
  24250. juce_UseDebuggingNewOperator
  24251. private:
  24252. const Component* const componentToWatch;
  24253. const uint32 componentUID;
  24254. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24255. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24256. };
  24257. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24258. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24259. /********* Start of inlined file: juce_TextEditor.h *********/
  24260. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24261. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24262. /********* Start of inlined file: juce_UndoManager.h *********/
  24263. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24264. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24265. /********* Start of inlined file: juce_UndoableAction.h *********/
  24266. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24267. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24268. /**
  24269. Used by the UndoManager class to store an action which can be done
  24270. and undone.
  24271. @see UndoManager
  24272. */
  24273. class JUCE_API UndoableAction
  24274. {
  24275. protected:
  24276. /** Creates an action. */
  24277. UndoableAction() throw() {}
  24278. public:
  24279. /** Destructor. */
  24280. virtual ~UndoableAction() {}
  24281. /** Overridden by a subclass to perform the action.
  24282. This method is called by the UndoManager, and shouldn't be used directly by
  24283. applications.
  24284. Be careful not to make any calls in a perform() method that could call
  24285. recursively back into the UndoManager::perform() method
  24286. @returns true if the action could be performed.
  24287. @see UndoManager::perform
  24288. */
  24289. virtual bool perform() = 0;
  24290. /** Overridden by a subclass to undo the action.
  24291. This method is called by the UndoManager, and shouldn't be used directly by
  24292. applications.
  24293. Be careful not to make any calls in an undo() method that could call
  24294. recursively back into the UndoManager::perform() method
  24295. @returns true if the action could be undone without any errors.
  24296. @see UndoManager::perform
  24297. */
  24298. virtual bool undo() = 0;
  24299. /** Returns a value to indicate how much memory this object takes up.
  24300. Because the UndoManager keeps a list of UndoableActions, this is used
  24301. to work out how much space each one will take up, so that the UndoManager
  24302. can work out how many to keep.
  24303. The default value returned here is 10 - units are arbitrary and
  24304. don't have to be accurate.
  24305. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24306. UndoManager::setMaxNumberOfStoredUnits
  24307. */
  24308. virtual int getSizeInUnits() { return 10; }
  24309. };
  24310. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24311. /********* End of inlined file: juce_UndoableAction.h *********/
  24312. /**
  24313. Manages a list of undo/redo commands.
  24314. An UndoManager object keeps a list of past actions and can use these actions
  24315. to move backwards and forwards through an undo history.
  24316. To use it, create subclasses of UndoableAction which perform all the
  24317. actions you need, then when you need to actually perform an action, create one
  24318. and pass it to the UndoManager's perform() method.
  24319. The manager also uses the concept of 'transactions' to group the actions
  24320. together - all actions performed between calls to beginNewTransaction() are
  24321. grouped together and are all undone/redone as a group.
  24322. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24323. when actions are performed or undone.
  24324. @see UndoableAction
  24325. */
  24326. class JUCE_API UndoManager : public ChangeBroadcaster
  24327. {
  24328. public:
  24329. /** Creates an UndoManager.
  24330. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24331. to indicate how much storage it takes up
  24332. (UndoableAction::getSizeInUnits()), so this
  24333. lets you specify the maximum total number of
  24334. units that the undomanager is allowed to
  24335. keep in memory before letting the older actions
  24336. drop off the end of the list.
  24337. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24338. that will be kept, even if this involves exceeding
  24339. the amount of space specified in maxNumberOfUnitsToKeep
  24340. */
  24341. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24342. const int minimumTransactionsToKeep = 30);
  24343. /** Destructor. */
  24344. ~UndoManager();
  24345. /** Deletes all stored actions in the list. */
  24346. void clearUndoHistory();
  24347. /** Returns the current amount of space to use for storing UndoableAction objects.
  24348. @see setMaxNumberOfStoredUnits
  24349. */
  24350. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24351. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24352. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24353. to indicate how much storage it takes up
  24354. (UndoableAction::getSizeInUnits()), so this
  24355. lets you specify the maximum total number of
  24356. units that the undomanager is allowed to
  24357. keep in memory before letting the older actions
  24358. drop off the end of the list.
  24359. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24360. that will be kept, even if this involves exceeding
  24361. the amount of space specified in maxNumberOfUnitsToKeep
  24362. @see getNumberOfUnitsTakenUpByStoredCommands
  24363. */
  24364. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24365. const int minimumTransactionsToKeep);
  24366. /** Performs an action and adds it to the undo history list.
  24367. @param action the action to perform - this will be deleted by the UndoManager
  24368. when no longer needed
  24369. @param actionName if this string is non-empty, the current transaction will be
  24370. given this name; if it's empty, the current transaction name will
  24371. be left unchanged. See setCurrentTransactionName()
  24372. @returns true if the command succeeds - see UndoableAction::perform
  24373. @see beginNewTransaction
  24374. */
  24375. bool perform (UndoableAction* const action,
  24376. const String& actionName = String::empty);
  24377. /** Starts a new group of actions that together will be treated as a single transaction.
  24378. All actions that are passed to the perform() method between calls to this
  24379. method are grouped together and undone/redone together by a single call to
  24380. undo() or redo().
  24381. @param actionName a description of the transaction that is about to be
  24382. performed
  24383. */
  24384. void beginNewTransaction (const String& actionName = String::empty);
  24385. /** Changes the name stored for the current transaction.
  24386. Each transaction is given a name when the beginNewTransaction() method is
  24387. called, but this can be used to change that name without starting a new
  24388. transaction.
  24389. */
  24390. void setCurrentTransactionName (const String& newName);
  24391. /** Returns true if there's at least one action in the list to undo.
  24392. @see getUndoDescription, undo, canRedo
  24393. */
  24394. bool canUndo() const;
  24395. /** Returns the description of the transaction that would be next to get undone.
  24396. The description returned is the one that was passed into beginNewTransaction
  24397. before the set of actions was performed.
  24398. @see undo
  24399. */
  24400. const String getUndoDescription() const;
  24401. /** Tries to roll-back the last transaction.
  24402. @returns true if the transaction can be undone, and false if it fails, or
  24403. if there aren't any transactions to undo
  24404. */
  24405. bool undo();
  24406. /** Tries to roll-back any actions that were added to the current transaction.
  24407. This will perform an undo() only if there are some actions in the undo list
  24408. that were added after the last call to beginNewTransaction().
  24409. This is useful because it lets you call beginNewTransaction(), then
  24410. perform an operation which may or may not actually perform some actions, and
  24411. then call this method to get rid of any actions that might have been done
  24412. without it rolling back the previous transaction if nothing was actually
  24413. done.
  24414. @returns true if any actions were undone.
  24415. */
  24416. bool undoCurrentTransactionOnly();
  24417. /** Returns a list of the UndoableAction objects that have been performed during the
  24418. transaction that is currently open.
  24419. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24420. were to be called now.
  24421. The first item in the list is the earliest action performed.
  24422. */
  24423. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24424. /** Returns true if there's at least one action in the list to redo.
  24425. @see getRedoDescription, redo, canUndo
  24426. */
  24427. bool canRedo() const;
  24428. /** Returns the description of the transaction that would be next to get redone.
  24429. The description returned is the one that was passed into beginNewTransaction
  24430. before the set of actions was performed.
  24431. @see redo
  24432. */
  24433. const String getRedoDescription() const;
  24434. /** Tries to redo the last transaction that was undone.
  24435. @returns true if the transaction can be redone, and false if it fails, or
  24436. if there aren't any transactions to redo
  24437. */
  24438. bool redo();
  24439. juce_UseDebuggingNewOperator
  24440. private:
  24441. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24442. StringArray transactionNames;
  24443. String currentTransactionName;
  24444. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24445. bool newTransaction, reentrancyCheck;
  24446. // disallow copy constructor
  24447. UndoManager (const UndoManager&);
  24448. const UndoManager& operator= (const UndoManager&);
  24449. };
  24450. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24451. /********* End of inlined file: juce_UndoManager.h *********/
  24452. class TextEditor;
  24453. class TextHolderComponent;
  24454. /**
  24455. Receives callbacks from a TextEditor component when it changes.
  24456. @see TextEditor::addListener
  24457. */
  24458. class JUCE_API TextEditorListener
  24459. {
  24460. public:
  24461. /** Destructor. */
  24462. virtual ~TextEditorListener() {}
  24463. /** Called when the user changes the text in some way. */
  24464. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24465. /** Called when the user presses the return key. */
  24466. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24467. /** Called when the user presses the escape key. */
  24468. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24469. /** Called when the text editor loses focus. */
  24470. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24471. };
  24472. /**
  24473. A component containing text that can be edited.
  24474. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24475. fonts and colours.
  24476. @see TextEditorListener, Label
  24477. */
  24478. class JUCE_API TextEditor : public Component,
  24479. public SettableTooltipClient
  24480. {
  24481. public:
  24482. /** Creates a new, empty text editor.
  24483. @param componentName the name to pass to the component for it to use as its name
  24484. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24485. for all characters that are drawn on screen - e.g. to create
  24486. a password-style textbox containing circular blobs instead of text,
  24487. you could set this value to 0x25cf, which is the unicode character
  24488. for a black splodge (not all fonts include this, though), or 0x2022,
  24489. which is a bullet (probably the best choice for linux).
  24490. */
  24491. TextEditor (const String& componentName = String::empty,
  24492. const tchar passwordCharacter = 0);
  24493. /** Destructor. */
  24494. virtual ~TextEditor();
  24495. /** Puts the editor into either multi- or single-line mode.
  24496. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24497. editor.
  24498. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24499. on if you want a multi-line editor with line-breaks.
  24500. @see isMultiLine, setReturnKeyStartsNewLine
  24501. */
  24502. void setMultiLine (const bool shouldBeMultiLine,
  24503. const bool shouldWordWrap = true);
  24504. /** Returns true if the editor is in multi-line mode.
  24505. */
  24506. bool isMultiLine() const throw();
  24507. /** Changes the behaviour of the return key.
  24508. If set to true, the return key will insert a new-line into the text; if false
  24509. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24510. method. By default this is set to false, and when true it will only insert
  24511. new-lines when in multi-line mode (see setMultiLine()).
  24512. */
  24513. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24514. /** Returns the value set by setReturnKeyStartsNewLine().
  24515. See setReturnKeyStartsNewLine() for more info.
  24516. */
  24517. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24518. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24519. or whether it gets ignored.
  24520. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24521. between components.
  24522. */
  24523. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24524. /** Returns true if the tab key is being used for input.
  24525. @see setTabKeyUsedAsCharacter
  24526. */
  24527. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24528. /** Changes the editor to read-only mode.
  24529. By default, the text editor is not read-only. If you're making it read-only, you
  24530. might also want to call setCaretVisible (false) to get rid of the caret.
  24531. The text can still be highlighted and copied when in read-only mode.
  24532. @see isReadOnly, setCaretVisible
  24533. */
  24534. void setReadOnly (const bool shouldBeReadOnly);
  24535. /** Returns true if the editor is in read-only mode.
  24536. */
  24537. bool isReadOnly() const throw();
  24538. /** Makes the caret visible or invisible.
  24539. By default the caret is visible.
  24540. @see setCaretColour, setCaretPosition
  24541. */
  24542. void setCaretVisible (const bool shouldBeVisible) throw();
  24543. /** Returns true if the caret is enabled.
  24544. @see setCaretVisible
  24545. */
  24546. bool isCaretVisible() const throw() { return caretVisible; }
  24547. /** Enables/disables a vertical scrollbar.
  24548. (This only applies when in multi-line mode). When the text gets too long to fit
  24549. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24550. this is enabled, the scrollbar will be hidden unless it's needed.
  24551. By default the scrollbar is enabled.
  24552. */
  24553. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24554. /** Returns true if scrollbars are enabled.
  24555. @see setScrollbarsShown
  24556. */
  24557. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24558. /** Changes the password character used to disguise the text.
  24559. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24560. for all characters that are drawn on screen - e.g. to create
  24561. a password-style textbox containing circular blobs instead of text,
  24562. you could set this value to 0x25cf, which is the unicode character
  24563. for a black splodge (not all fonts include this, though), or 0x2022,
  24564. which is a bullet (probably the best choice for linux).
  24565. */
  24566. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24567. /** Returns the current password character.
  24568. @see setPasswordCharacter
  24569. l */
  24570. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24571. /** Allows a right-click menu to appear for the editor.
  24572. (This defaults to being enabled).
  24573. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24574. of options such as cut/copy/paste, undo/redo, etc.
  24575. */
  24576. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24577. /** Returns true if the right-click menu is enabled.
  24578. @see setPopupMenuEnabled
  24579. */
  24580. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24581. /** Returns true if a popup-menu is currently being displayed.
  24582. */
  24583. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24584. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24585. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24586. methods.
  24587. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24588. */
  24589. enum ColourIds
  24590. {
  24591. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24592. transparent if necessary. */
  24593. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24594. that because the editor can contain multiple colours, calling this
  24595. method won't change the colour of existing text - to do that, call
  24596. applyFontToAllText() after calling this method.*/
  24597. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24598. the text - this can be transparent if you don't want to show any
  24599. highlighting.*/
  24600. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24601. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24602. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24603. the edge of the component. */
  24604. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24605. the edge of the component when it has focus. */
  24606. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24607. around the edge of the editor. */
  24608. };
  24609. /** Sets the font to use for newly added text.
  24610. This will change the font that will be used next time any text is added or entered
  24611. into the editor. It won't change the font of any existing text - to do that, use
  24612. applyFontToAllText() instead.
  24613. @see applyFontToAllText
  24614. */
  24615. void setFont (const Font& newFont) throw();
  24616. /** Applies a font to all the text in the editor.
  24617. This will also set the current font to use for any new text that's added.
  24618. @see setFont
  24619. */
  24620. void applyFontToAllText (const Font& newFont);
  24621. /** Returns the font that's currently being used for new text.
  24622. @see setFont
  24623. */
  24624. const Font getFont() const throw();
  24625. /** If set to true, focusing on the editor will highlight all its text.
  24626. (Set to false by default).
  24627. This is useful for boxes where you expect the user to re-enter all the
  24628. text when they focus on the component, rather than editing what's already there.
  24629. */
  24630. void setSelectAllWhenFocused (const bool b) throw();
  24631. /** Sets limits on the characters that can be entered.
  24632. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24633. limit is set
  24634. @param allowedCharacters if this is non-empty, then only characters that occur in
  24635. this string are allowed to be entered into the editor.
  24636. */
  24637. void setInputRestrictions (const int maxTextLength,
  24638. const String& allowedCharacters = String::empty) throw();
  24639. /** When the text editor is empty, it can be set to display a message.
  24640. This is handy for things like telling the user what to type in the box - the
  24641. string is only displayed, it's not taken to actually be the contents of
  24642. the editor.
  24643. */
  24644. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24645. /** Changes the size of the scrollbars that are used.
  24646. Handy if you need smaller scrollbars for a small text box.
  24647. */
  24648. void setScrollBarThickness (const int newThicknessPixels);
  24649. /** Shows or hides the buttons on any scrollbars that are used.
  24650. @see ScrollBar::setButtonVisibility
  24651. */
  24652. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24653. /** Registers a listener to be told when things happen to the text.
  24654. @see removeListener
  24655. */
  24656. void addListener (TextEditorListener* const newListener) throw();
  24657. /** Deregisters a listener.
  24658. @see addListener
  24659. */
  24660. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24661. /** Returns the entire contents of the editor. */
  24662. const String getText() const throw();
  24663. /** Returns a section of the contents of the editor. */
  24664. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24665. /** Returns true if there are no characters in the editor.
  24666. This is more efficient than calling getText().isEmpty().
  24667. */
  24668. bool isEmpty() const throw();
  24669. /** Sets the entire content of the editor.
  24670. This will clear the editor and insert the given text (using the current text colour
  24671. and font). You can set the current text colour using
  24672. @code setColour (TextEditor::textColourId, ...);
  24673. @endcode
  24674. @param newText the text to add
  24675. @param sendTextChangeMessage if true, this will cause a change message to
  24676. be sent to all the listeners.
  24677. @see insertText
  24678. */
  24679. void setText (const String& newText,
  24680. const bool sendTextChangeMessage = true);
  24681. /** Inserts some text at the current cursor position.
  24682. If a section of the text is highlighted, it will be replaced by
  24683. this string, otherwise it will be inserted.
  24684. To delete a section of text, you can use setHighlightedRegion() to
  24685. highlight it, and call insertTextAtCursor (String::empty).
  24686. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24687. */
  24688. void insertTextAtCursor (String textToInsert);
  24689. /** Deletes all the text from the editor. */
  24690. void clear();
  24691. /** Deletes the currently selected region, and puts it on the clipboard.
  24692. @see copy, paste, SystemClipboard
  24693. */
  24694. void cut();
  24695. /** Copies any currently selected region to the clipboard.
  24696. @see cut, paste, SystemClipboard
  24697. */
  24698. void copy();
  24699. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24700. @see cut, copy, SystemClipboard
  24701. */
  24702. void paste();
  24703. /** Moves the caret to be in front of a given character.
  24704. @see getCaretPosition
  24705. */
  24706. void setCaretPosition (const int newIndex) throw();
  24707. /** Returns the current index of the caret.
  24708. @see setCaretPosition
  24709. */
  24710. int getCaretPosition() const throw();
  24711. /** Attempts to scroll the text editor so that the caret ends up at
  24712. a specified position.
  24713. This won't affect the caret's position within the text, it tries to scroll
  24714. the entire editor vertically and horizontally so that the caret is sitting
  24715. at the given position (relative to the top-left of this component).
  24716. Depending on the amount of text available, it might not be possible to
  24717. scroll far enough for the caret to reach this exact position, but it
  24718. will go as far as it can in that direction.
  24719. */
  24720. void scrollEditorToPositionCaret (const int desiredCaretX,
  24721. const int desiredCaretY) throw();
  24722. /** Get the graphical position of the caret.
  24723. The rectangle returned is relative to the component's top-left corner.
  24724. @see scrollEditorToPositionCaret
  24725. */
  24726. const Rectangle getCaretRectangle() throw();
  24727. /** Selects a section of the text.
  24728. */
  24729. void setHighlightedRegion (int startIndex,
  24730. int numberOfCharactersToHighlight) throw();
  24731. /** Returns the first character that is selected.
  24732. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24733. will return 0.
  24734. @see setHighlightedRegion, getHighlightedRegionLength
  24735. */
  24736. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24737. /** Returns the number of characters that are selected.
  24738. @see setHighlightedRegion, getHighlightedRegionStart
  24739. */
  24740. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24741. /** Returns the section of text that is currently selected. */
  24742. const String getHighlightedText() const throw();
  24743. /** Finds the index of the character at a given position.
  24744. The co-ordinates are relative to the component's top-left.
  24745. */
  24746. int getTextIndexAt (const int x, const int y) throw();
  24747. /** Returns the total width of the text, as it is currently laid-out.
  24748. This may be larger than the size of the TextEditor, and can change when
  24749. the TextEditor is resized or the text changes.
  24750. */
  24751. int getTextWidth() const throw();
  24752. /** Returns the maximum height of the text, as it is currently laid-out.
  24753. This may be larger than the size of the TextEditor, and can change when
  24754. the TextEditor is resized or the text changes.
  24755. */
  24756. int getTextHeight() const throw();
  24757. /** Changes the size of the gap at the top and left-edge of the editor.
  24758. By default there's a gap of 4 pixels.
  24759. */
  24760. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24761. /** Changes the size of border left around the edge of the component.
  24762. @see getBorder
  24763. */
  24764. void setBorder (const BorderSize& border) throw();
  24765. /** Returns the size of border around the edge of the component.
  24766. @see setBorder
  24767. */
  24768. const BorderSize getBorder() const throw();
  24769. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24770. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24771. set to false, it won't.
  24772. */
  24773. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24774. /** @internal */
  24775. void paint (Graphics& g);
  24776. /** @internal */
  24777. void paintOverChildren (Graphics& g);
  24778. /** @internal */
  24779. void mouseDown (const MouseEvent& e);
  24780. /** @internal */
  24781. void mouseUp (const MouseEvent& e);
  24782. /** @internal */
  24783. void mouseDrag (const MouseEvent& e);
  24784. /** @internal */
  24785. void mouseDoubleClick (const MouseEvent& e);
  24786. /** @internal */
  24787. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24788. /** @internal */
  24789. bool keyPressed (const KeyPress& key);
  24790. /** @internal */
  24791. bool keyStateChanged();
  24792. /** @internal */
  24793. void focusGained (FocusChangeType cause);
  24794. /** @internal */
  24795. void focusLost (FocusChangeType cause);
  24796. /** @internal */
  24797. void resized();
  24798. /** @internal */
  24799. void enablementChanged();
  24800. /** @internal */
  24801. void colourChanged();
  24802. juce_UseDebuggingNewOperator
  24803. protected:
  24804. /** This adds the items to the popup menu.
  24805. By default it adds the cut/copy/paste items, but you can override this if
  24806. you need to replace these with your own items.
  24807. If you want to add your own items to the existing ones, you can override this,
  24808. call the base class's addPopupMenuItems() method, then append your own items.
  24809. When the menu has been shown, performPopupMenuAction() will be called to
  24810. perform the item that the user has chosen.
  24811. The default menu items will be added using item IDs in the range
  24812. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24813. menu IDs.
  24814. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24815. a pointer to the info about it, or may be null if the menu is being triggered
  24816. by some other means.
  24817. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24818. */
  24819. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24820. const MouseEvent* mouseClickEvent);
  24821. /** This is called to perform one of the items that was shown on the popup menu.
  24822. If you've overridden addPopupMenuItems(), you should also override this
  24823. to perform the actions that you've added.
  24824. If you've overridden addPopupMenuItems() but have still left the default items
  24825. on the menu, remember to call the superclass's performPopupMenuAction()
  24826. so that it can perform the default actions if that's what the user clicked on.
  24827. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24828. */
  24829. virtual void performPopupMenuAction (const int menuItemID);
  24830. /** Scrolls the minimum distance needed to get the caret into view. */
  24831. void scrollToMakeSureCursorIsVisible() throw();
  24832. /** @internal */
  24833. void moveCaret (int newCaretPos) throw();
  24834. /** @internal */
  24835. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24836. /** Used internally to dispatch a text-change message. */
  24837. void textChanged() throw();
  24838. /** Counts the number of characters in the text.
  24839. This is quicker than getting the text as a string if you just need to know
  24840. the length.
  24841. */
  24842. int getTotalNumChars() throw();
  24843. /** Begins a new transaction in the UndoManager.
  24844. */
  24845. void newTransaction() throw();
  24846. /** Used internally to trigger an undo or redo. */
  24847. void doUndoRedo (const bool isRedo);
  24848. /** Can be overridden to intercept return key presses directly */
  24849. virtual void returnPressed();
  24850. /** Can be overridden to intercept escape key presses directly */
  24851. virtual void escapePressed();
  24852. /** @internal */
  24853. void handleCommandMessage (int commandId);
  24854. private:
  24855. Viewport* viewport;
  24856. TextHolderComponent* textHolder;
  24857. BorderSize borderSize;
  24858. bool readOnly : 1;
  24859. bool multiline : 1;
  24860. bool wordWrap : 1;
  24861. bool returnKeyStartsNewLine : 1;
  24862. bool caretVisible : 1;
  24863. bool popupMenuEnabled : 1;
  24864. bool selectAllTextWhenFocused : 1;
  24865. bool scrollbarVisible : 1;
  24866. bool wasFocused : 1;
  24867. bool caretFlashState : 1;
  24868. bool keepCursorOnScreen : 1;
  24869. bool tabKeyUsed : 1;
  24870. bool menuActive : 1;
  24871. UndoManager undoManager;
  24872. float cursorX, cursorY, cursorHeight;
  24873. int maxTextLength;
  24874. int selectionStart, selectionEnd;
  24875. int leftIndent, topIndent;
  24876. unsigned int lastTransactionTime;
  24877. Font currentFont;
  24878. int totalNumChars, caretPosition;
  24879. VoidArray sections;
  24880. String textToShowWhenEmpty;
  24881. Colour colourForTextWhenEmpty;
  24882. tchar passwordCharacter;
  24883. enum
  24884. {
  24885. notDragging,
  24886. draggingSelectionStart,
  24887. draggingSelectionEnd
  24888. } dragType;
  24889. String allowedCharacters;
  24890. SortedSet <void*> listeners;
  24891. friend class TextEditorInsertAction;
  24892. friend class TextEditorRemoveAction;
  24893. void coalesceSimilarSections() throw();
  24894. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24895. void clearInternal (UndoManager* const um) throw();
  24896. void insert (const String& text,
  24897. const int insertIndex,
  24898. const Font& font,
  24899. const Colour& colour,
  24900. UndoManager* const um,
  24901. const int caretPositionToMoveTo) throw();
  24902. void reinsert (const int insertIndex,
  24903. const VoidArray& sections) throw();
  24904. void remove (const int startIndex,
  24905. int endIndex,
  24906. UndoManager* const um,
  24907. const int caretPositionToMoveTo) throw();
  24908. void getCharPosition (const int index,
  24909. float& x, float& y,
  24910. float& lineHeight) const throw();
  24911. void updateCaretPosition() throw();
  24912. int indexAtPosition (const float x,
  24913. const float y) throw();
  24914. int findWordBreakAfter (const int position) const throw();
  24915. int findWordBreakBefore (const int position) const throw();
  24916. friend class TextHolderComponent;
  24917. friend class TextEditorViewport;
  24918. void drawContent (Graphics& g);
  24919. void updateTextHolderSize() throw();
  24920. float getWordWrapWidth() const throw();
  24921. void timerCallbackInt();
  24922. void repaintCaret();
  24923. void repaintText (int textStartIndex, int textEndIndex);
  24924. TextEditor (const TextEditor&);
  24925. const TextEditor& operator= (const TextEditor&);
  24926. };
  24927. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24928. /********* End of inlined file: juce_TextEditor.h *********/
  24929. class Label;
  24930. /**
  24931. A class for receiving events from a Label.
  24932. You can register a LabelListener with a Label using the Label::addListener()
  24933. method, and it will be called when the text of the label changes, either because
  24934. of a call to Label::setText() or by the user editing the text (if the label is
  24935. editable).
  24936. @see Label::addListener, Label::removeListener
  24937. */
  24938. class JUCE_API LabelListener
  24939. {
  24940. public:
  24941. /** Destructor. */
  24942. virtual ~LabelListener() {}
  24943. /** Called when a Label's text has changed.
  24944. */
  24945. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24946. };
  24947. /**
  24948. A component that displays a text string, and can optionally become a text
  24949. editor when clicked.
  24950. */
  24951. class JUCE_API Label : public Component,
  24952. public SettableTooltipClient,
  24953. protected TextEditorListener,
  24954. private ComponentListener
  24955. {
  24956. public:
  24957. /** Creates a Label.
  24958. @param componentName the name to give the component
  24959. @param labelText the text to show in the label
  24960. */
  24961. Label (const String& componentName,
  24962. const String& labelText);
  24963. /** Destructor. */
  24964. ~Label();
  24965. /** Changes the label text.
  24966. If broadcastChangeMessage is true and the new text is different to the current
  24967. text, then the class will broadcast a change message to any LabelListeners that
  24968. are registered.
  24969. */
  24970. void setText (const String& newText,
  24971. const bool broadcastChangeMessage);
  24972. /** Returns the label's current text.
  24973. @param returnActiveEditorContents if this is true and the label is currently
  24974. being edited, then this method will return the
  24975. text as it's being shown in the editor. If false,
  24976. then the value returned here won't be updated until
  24977. the user has finished typing and pressed the return
  24978. key.
  24979. */
  24980. const String getText (const bool returnActiveEditorContents = false) const throw();
  24981. /** Changes the font to use to draw the text.
  24982. @see getFont
  24983. */
  24984. void setFont (const Font& newFont) throw();
  24985. /** Returns the font currently being used.
  24986. @see setFont
  24987. */
  24988. const Font& getFont() const throw();
  24989. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24990. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24991. methods.
  24992. Note that you can also use the constants from TextEditor::ColourIds to change the
  24993. colour of the text editor that is opened when a label is editable.
  24994. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24995. */
  24996. enum ColourIds
  24997. {
  24998. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  24999. textColourId = 0x1000281, /**< The colour for the text. */
  25000. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25001. Leave this transparent to not have an outline. */
  25002. };
  25003. /** Sets the style of justification to be used for positioning the text.
  25004. (The default is Justification::centredLeft)
  25005. */
  25006. void setJustificationType (const Justification& justification) throw();
  25007. /** Returns the type of justification, as set in setJustificationType(). */
  25008. const Justification getJustificationType() const throw() { return justification; }
  25009. /** Changes the gap that is left between the edge of the component and the text.
  25010. By default there's a small gap left at the sides of the component to allow for
  25011. the drawing of the border, but you can change this if necessary.
  25012. */
  25013. void setBorderSize (int horizontalBorder, int verticalBorder);
  25014. /** Returns the size of the horizontal gap being left around the text.
  25015. */
  25016. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25017. /** Returns the size of the vertical gap being left around the text.
  25018. */
  25019. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25020. /** Makes this label "stick to" another component.
  25021. This will cause the label to follow another component around, staying
  25022. either to its left or above it.
  25023. @param owner the component to follow
  25024. @param onLeft if true, the label will stay on the left of its component; if
  25025. false, it will stay above it.
  25026. */
  25027. void attachToComponent (Component* owner,
  25028. const bool onLeft);
  25029. /** If this label has been attached to another component using attachToComponent, this
  25030. returns the other component.
  25031. Returns 0 if the label is not attached.
  25032. */
  25033. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25034. /** If the label is attached to the left of another component, this returns true.
  25035. Returns false if the label is above the other component. This is only relevent if
  25036. attachToComponent() has been called.
  25037. */
  25038. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25039. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25040. using ellipsis.
  25041. @see Graphics::drawFittedText
  25042. */
  25043. void setMinimumHorizontalScale (const float newScale);
  25044. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25045. /** Registers a listener that will be called when the label's text changes. */
  25046. void addListener (LabelListener* const listener) throw();
  25047. /** Deregisters a previously-registered listener. */
  25048. void removeListener (LabelListener* const listener) throw();
  25049. /** Makes the label turn into a TextEditor when clicked.
  25050. By default this is turned off.
  25051. If turned on, then single- or double-clicking will turn the label into
  25052. an editor. If the user then changes the text, then the ChangeBroadcaster
  25053. base class will be used to send change messages to any listeners that
  25054. have registered.
  25055. If the user changes the text, the textWasEdited() method will be called
  25056. afterwards, and subclasses can override this if they need to do anything
  25057. special.
  25058. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25059. @param editOnDoubleClick if true, a double-click is needed to start editing
  25060. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25061. edited will discard any changes; if false, then this will
  25062. commit the changes.
  25063. @see showEditor, setEditorColours, TextEditor
  25064. */
  25065. void setEditable (const bool editOnSingleClick,
  25066. const bool editOnDoubleClick = false,
  25067. const bool lossOfFocusDiscardsChanges = false) throw();
  25068. /** Returns true if this option was set using setEditable(). */
  25069. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25070. /** Returns true if this option was set using setEditable(). */
  25071. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25072. /** Returns true if this option has been set in a call to setEditable(). */
  25073. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25074. /** Returns true if the user can edit this label's text. */
  25075. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25076. /** Makes the editor appear as if the label had been clicked by the user.
  25077. @see textWasEdited, setEditable
  25078. */
  25079. void showEditor();
  25080. /** Hides the editor if it was being shown.
  25081. @param discardCurrentEditorContents if true, the label's text will be
  25082. reset to whatever it was before the editor
  25083. was shown; if false, the current contents of the
  25084. editor will be used to set the label's text
  25085. before it is hidden.
  25086. */
  25087. void hideEditor (const bool discardCurrentEditorContents);
  25088. /** Returns true if the editor is currently focused and active. */
  25089. bool isBeingEdited() const throw();
  25090. juce_UseDebuggingNewOperator
  25091. protected:
  25092. /** @internal */
  25093. void paint (Graphics& g);
  25094. /** @internal */
  25095. void resized();
  25096. /** @internal */
  25097. void mouseUp (const MouseEvent& e);
  25098. /** @internal */
  25099. void mouseDoubleClick (const MouseEvent& e);
  25100. /** @internal */
  25101. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25102. /** @internal */
  25103. void componentParentHierarchyChanged (Component& component);
  25104. /** @internal */
  25105. void componentVisibilityChanged (Component& component);
  25106. /** @internal */
  25107. void inputAttemptWhenModal();
  25108. /** @internal */
  25109. void focusGained (FocusChangeType);
  25110. /** @internal */
  25111. void enablementChanged();
  25112. /** @internal */
  25113. KeyboardFocusTraverser* createFocusTraverser();
  25114. /** @internal */
  25115. void textEditorTextChanged (TextEditor& editor);
  25116. /** @internal */
  25117. void textEditorReturnKeyPressed (TextEditor& editor);
  25118. /** @internal */
  25119. void textEditorEscapeKeyPressed (TextEditor& editor);
  25120. /** @internal */
  25121. void textEditorFocusLost (TextEditor& editor);
  25122. /** @internal */
  25123. void colourChanged();
  25124. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25125. Subclasses can override this if they need to customise this component in some way.
  25126. */
  25127. virtual TextEditor* createEditorComponent();
  25128. /** Called after the user changes the text.
  25129. */
  25130. virtual void textWasEdited();
  25131. /** Called when the text has been altered.
  25132. */
  25133. virtual void textWasChanged();
  25134. private:
  25135. String text;
  25136. Font font;
  25137. Justification justification;
  25138. TextEditor* editor;
  25139. SortedSet <void*> listeners;
  25140. Component* ownerComponent;
  25141. ComponentDeletionWatcher* deletionWatcher;
  25142. int horizontalBorderSize, verticalBorderSize;
  25143. float minimumHorizontalScale;
  25144. bool editSingleClick : 1;
  25145. bool editDoubleClick : 1;
  25146. bool lossOfFocusDiscardsChanges : 1;
  25147. bool leftOfOwnerComp : 1;
  25148. bool updateFromTextEditorContents();
  25149. void callChangeListeners();
  25150. Label (const Label&);
  25151. const Label& operator= (const Label&);
  25152. };
  25153. #endif // __JUCE_LABEL_JUCEHEADER__
  25154. /********* End of inlined file: juce_Label.h *********/
  25155. class ComboBox;
  25156. /**
  25157. A class for receiving events from a ComboBox.
  25158. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25159. method, and it will be called when the selected item in the box changes.
  25160. @see ComboBox::addListener, ComboBox::removeListener
  25161. */
  25162. class JUCE_API ComboBoxListener
  25163. {
  25164. public:
  25165. /** Destructor. */
  25166. virtual ~ComboBoxListener() {}
  25167. /** Called when a ComboBox has its selected item changed.
  25168. */
  25169. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25170. };
  25171. /**
  25172. A component that lets the user choose from a drop-down list of choices.
  25173. The combo-box has a list of text strings, each with an associated id number,
  25174. that will be shown in the drop-down list when the user clicks on the component.
  25175. The currently selected choice is displayed in the combo-box, and this can
  25176. either be read-only text, or editable.
  25177. To find out when the user selects a different item or edits the text, you
  25178. can register a ComboBoxListener to receive callbacks.
  25179. @see ComboBoxListener
  25180. */
  25181. class JUCE_API ComboBox : public Component,
  25182. public SettableTooltipClient,
  25183. private LabelListener,
  25184. private AsyncUpdater
  25185. {
  25186. public:
  25187. /** Creates a combo-box.
  25188. On construction, the text field will be empty, so you should call the
  25189. setSelectedId() or setText() method to choose the initial value before
  25190. displaying it.
  25191. @param componentName the name to set for the component (see Component::setName())
  25192. */
  25193. ComboBox (const String& componentName);
  25194. /** Destructor. */
  25195. ~ComboBox();
  25196. /** Sets whether the test in the combo-box is editable.
  25197. The default state for a new ComboBox is non-editable, and can only be changed
  25198. by choosing from the drop-down list.
  25199. */
  25200. void setEditableText (const bool isEditable);
  25201. /** Returns true if the text is directly editable.
  25202. @see setEditableText
  25203. */
  25204. bool isTextEditable() const throw();
  25205. /** Sets the style of justification to be used for positioning the text.
  25206. The default is Justification::centredLeft. The text is displayed using a
  25207. Label component inside the ComboBox.
  25208. */
  25209. void setJustificationType (const Justification& justification) throw();
  25210. /** Returns the current justification for the text box.
  25211. @see setJustificationType
  25212. */
  25213. const Justification getJustificationType() const throw();
  25214. /** Adds an item to be shown in the drop-down list.
  25215. @param newItemText the text of the item to show in the list
  25216. @param newItemId an associated ID number that can be set or retrieved - see
  25217. getSelectedId() and setSelectedId()
  25218. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25219. */
  25220. void addItem (const String& newItemText,
  25221. const int newItemId) throw();
  25222. /** Adds a separator line to the drop-down list.
  25223. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25224. */
  25225. void addSeparator() throw();
  25226. /** Adds a heading to the drop-down list, so that you can group the items into
  25227. different sections.
  25228. The headings are indented slightly differently to set them apart from the
  25229. items on the list, and obviously can't be selected. You might want to add
  25230. separators between your sections too.
  25231. @see addItem, addSeparator
  25232. */
  25233. void addSectionHeading (const String& headingName) throw();
  25234. /** This allows items in the drop-down list to be selectively disabled.
  25235. When you add an item, it's enabled by default, but you can call this
  25236. method to change its status.
  25237. If you disable an item which is already selected, this won't change the
  25238. current selection - it just stops the user choosing that item from the list.
  25239. */
  25240. void setItemEnabled (const int itemId,
  25241. const bool isEnabled) throw();
  25242. /** Changes the text for an existing item.
  25243. */
  25244. void changeItemText (const int itemId,
  25245. const String& newText) throw();
  25246. /** Removes all the items from the drop-down list.
  25247. If this call causes the content to be cleared, then a change-message
  25248. will be broadcast unless dontSendChangeMessage is true.
  25249. @see addItem, removeItem, getNumItems
  25250. */
  25251. void clear (const bool dontSendChangeMessage = false);
  25252. /** Returns the number of items that have been added to the list.
  25253. Note that this doesn't include headers or separators.
  25254. */
  25255. int getNumItems() const throw();
  25256. /** Returns the text for one of the items in the list.
  25257. Note that this doesn't include headers or separators.
  25258. @param index the item's index from 0 to (getNumItems() - 1)
  25259. */
  25260. const String getItemText (const int index) const throw();
  25261. /** Returns the ID for one of the items in the list.
  25262. Note that this doesn't include headers or separators.
  25263. @param index the item's index from 0 to (getNumItems() - 1)
  25264. */
  25265. int getItemId (const int index) const throw();
  25266. /** Returns the ID of the item that's currently shown in the box.
  25267. If no item is selected, or if the text is editable and the user
  25268. has entered something which isn't one of the items in the list, then
  25269. this will return 0.
  25270. @see setSelectedId, getSelectedItemIndex, getText
  25271. */
  25272. int getSelectedId() const throw();
  25273. /** Sets one of the items to be the current selection.
  25274. This will set the ComboBox's text to that of the item that matches
  25275. this ID.
  25276. @param newItemId the new item to select
  25277. @param dontSendChangeMessage if set to true, this method won't trigger a
  25278. change notification
  25279. @see getSelectedId, setSelectedItemIndex, setText
  25280. */
  25281. void setSelectedId (const int newItemId,
  25282. const bool dontSendChangeMessage = false) throw();
  25283. /** Returns the index of the item that's currently shown in the box.
  25284. If no item is selected, or if the text is editable and the user
  25285. has entered something which isn't one of the items in the list, then
  25286. this will return -1.
  25287. @see setSelectedItemIndex, getSelectedId, getText
  25288. */
  25289. int getSelectedItemIndex() const throw();
  25290. /** Sets one of the items to be the current selection.
  25291. This will set the ComboBox's text to that of the item at the given
  25292. index in the list.
  25293. @param newItemIndex the new item to select
  25294. @param dontSendChangeMessage if set to true, this method won't trigger a
  25295. change notification
  25296. @see getSelectedItemIndex, setSelectedId, setText
  25297. */
  25298. void setSelectedItemIndex (const int newItemIndex,
  25299. const bool dontSendChangeMessage = false) throw();
  25300. /** Returns the text that is currently shown in the combo-box's text field.
  25301. If the ComboBox has editable text, then this text may have been edited
  25302. by the user; otherwise it will be one of the items from the list, or
  25303. possibly an empty string if nothing was selected.
  25304. @see setText, getSelectedId, getSelectedItemIndex
  25305. */
  25306. const String getText() const throw();
  25307. /** Sets the contents of the combo-box's text field.
  25308. The text passed-in will be set as the current text regardless of whether
  25309. it is one of the items in the list. If the current text isn't one of the
  25310. items, then getSelectedId() will return -1, otherwise it wil return
  25311. the approriate ID.
  25312. @param newText the text to select
  25313. @param dontSendChangeMessage if set to true, this method won't trigger a
  25314. change notification
  25315. @see getText
  25316. */
  25317. void setText (const String& newText,
  25318. const bool dontSendChangeMessage = false) throw();
  25319. /** Programmatically opens the text editor to allow the user to edit the current item.
  25320. This is the same effect as when the box is clicked-on.
  25321. @see Label::showEditor();
  25322. */
  25323. void showEditor();
  25324. /** Registers a listener that will be called when the box's content changes. */
  25325. void addListener (ComboBoxListener* const listener) throw();
  25326. /** Deregisters a previously-registered listener. */
  25327. void removeListener (ComboBoxListener* const listener) throw();
  25328. /** Sets a message to display when there is no item currently selected.
  25329. @see getTextWhenNothingSelected
  25330. */
  25331. void setTextWhenNothingSelected (const String& newMessage) throw();
  25332. /** Returns the text that is shown when no item is selected.
  25333. @see setTextWhenNothingSelected
  25334. */
  25335. const String getTextWhenNothingSelected() const throw();
  25336. /** Sets the message to show when there are no items in the list, and the user clicks
  25337. on the drop-down box.
  25338. By default it just says "no choices", but this lets you change it to something more
  25339. meaningful.
  25340. */
  25341. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25342. /** Returns the text shown when no items have been added to the list.
  25343. @see setTextWhenNoChoicesAvailable
  25344. */
  25345. const String getTextWhenNoChoicesAvailable() const throw();
  25346. /** Gives the ComboBox a tooltip. */
  25347. void setTooltip (const String& newTooltip);
  25348. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25349. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25350. methods.
  25351. To change the colours of the menu that pops up
  25352. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25353. */
  25354. enum ColourIds
  25355. {
  25356. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25357. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25358. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25359. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25360. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25361. };
  25362. /** @internal */
  25363. void labelTextChanged (Label*);
  25364. /** @internal */
  25365. void enablementChanged();
  25366. /** @internal */
  25367. void colourChanged();
  25368. /** @internal */
  25369. void focusGained (Component::FocusChangeType cause);
  25370. /** @internal */
  25371. void focusLost (Component::FocusChangeType cause);
  25372. /** @internal */
  25373. void handleAsyncUpdate();
  25374. /** @internal */
  25375. const String getTooltip() { return label->getTooltip(); }
  25376. /** @internal */
  25377. void mouseDown (const MouseEvent&);
  25378. /** @internal */
  25379. void mouseDrag (const MouseEvent&);
  25380. /** @internal */
  25381. void mouseUp (const MouseEvent&);
  25382. /** @internal */
  25383. void lookAndFeelChanged();
  25384. /** @internal */
  25385. void paint (Graphics&);
  25386. /** @internal */
  25387. void resized();
  25388. /** @internal */
  25389. bool keyStateChanged();
  25390. /** @internal */
  25391. bool keyPressed (const KeyPress&);
  25392. juce_UseDebuggingNewOperator
  25393. private:
  25394. struct ItemInfo
  25395. {
  25396. String name;
  25397. int itemId;
  25398. bool isEnabled : 1, isHeading : 1;
  25399. bool isSeparator() const throw();
  25400. bool isRealItem() const throw();
  25401. };
  25402. OwnedArray <ItemInfo> items;
  25403. int currentIndex;
  25404. bool isButtonDown;
  25405. bool separatorPending;
  25406. bool menuActive;
  25407. SortedSet <void*> listeners;
  25408. Label* label;
  25409. String textWhenNothingSelected, noChoicesMessage;
  25410. void showPopup();
  25411. ItemInfo* getItemForId (const int itemId) const throw();
  25412. ItemInfo* getItemForIndex (const int index) const throw();
  25413. ComboBox (const ComboBox&);
  25414. const ComboBox& operator= (const ComboBox&);
  25415. };
  25416. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25417. /********* End of inlined file: juce_ComboBox.h *********/
  25418. /**
  25419. Manages the state of some audio and midi i/o devices.
  25420. This class keeps tracks of a currently-selected audio device, through
  25421. with which it continuously streams data from an audio callback, as well as
  25422. one or more midi inputs.
  25423. The idea is that your application will create one global instance of this object,
  25424. and let it take care of creating and deleting specific types of audio devices
  25425. internally. So when the device is changed, your callbacks will just keep running
  25426. without having to worry about this.
  25427. The manager can save and reload all of its device settings as XML, which
  25428. makes it very easy for you to save and reload the audio setup of your
  25429. application.
  25430. And to make it easy to let the user change its settings, there's a component
  25431. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25432. device selection/sample-rate/latency controls.
  25433. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25434. call setAudioCallback() to register your audio callback with it, and use that to process
  25435. your audio data.
  25436. The manager also acts as a handy hub for incoming midi messages, allowing a
  25437. listener to register for messages from either a specific midi device, or from whatever
  25438. the current default midi input device is. The listener then doesn't have to worry about
  25439. re-registering with different midi devices if they are changed or deleted.
  25440. And yet another neat trick is that amount of CPU time being used is measured and
  25441. available with the getCpuUsage() method.
  25442. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25443. listeners whenever one of its settings is changed.
  25444. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25445. */
  25446. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25447. {
  25448. public:
  25449. /** Creates a default AudioDeviceManager.
  25450. Initially no audio device will be selected. You should call the initialise() method
  25451. and register an audio callback with setAudioCallback() before it'll be able to
  25452. actually make any noise.
  25453. */
  25454. AudioDeviceManager();
  25455. /** Destructor. */
  25456. ~AudioDeviceManager();
  25457. /**
  25458. This structure holds a set of properties describing the current audio setup.
  25459. @see AudioDeviceManager::setAudioDeviceSetup()
  25460. */
  25461. struct JUCE_API AudioDeviceSetup
  25462. {
  25463. AudioDeviceSetup();
  25464. bool operator== (const AudioDeviceSetup& other) const;
  25465. /** The name of the audio device used for output.
  25466. This may be the same as the input device.
  25467. */
  25468. String outputDeviceName;
  25469. /** The name of the audio device used for input.
  25470. This may be the same as the output device.
  25471. */
  25472. String inputDeviceName;
  25473. /** The current sample rate.
  25474. This rate is used for both the input and output devices.
  25475. */
  25476. double sampleRate;
  25477. /** The buffer size, in samples.
  25478. This buffer size is used for both the input and output devices.
  25479. */
  25480. int bufferSize;
  25481. /** The set of active input channels.
  25482. The bits that are set in this array indicate the channels of the
  25483. input device that are active.
  25484. */
  25485. BitArray inputChannels;
  25486. /** If this is true, it indicates that the inputChannels array
  25487. should be ignored, and instead, the device's default channels
  25488. should be used.
  25489. */
  25490. bool useDefaultInputChannels;
  25491. /** The set of active output channels.
  25492. The bits that are set in this array indicate the channels of the
  25493. input device that are active.
  25494. */
  25495. BitArray outputChannels;
  25496. /** If this is true, it indicates that the outputChannels array
  25497. should be ignored, and instead, the device's default channels
  25498. should be used.
  25499. */
  25500. bool useDefaultOutputChannels;
  25501. };
  25502. /** Opens a set of audio devices ready for use.
  25503. This will attempt to open either a default audio device, or one that was
  25504. previously saved as XML.
  25505. @param numInputChannelsNeeded a minimum number of input channels needed
  25506. by your app.
  25507. @param numOutputChannelsNeeded a minimum number of output channels to open
  25508. @param savedState either a previously-saved state that was produced
  25509. by createStateXml(), or 0 if you want the manager
  25510. to choose the best device to open.
  25511. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25512. fails to open, then a default device will be used
  25513. instead. If false, then on failure, no device is
  25514. opened.
  25515. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25516. name, then that will be used as the default device
  25517. (assuming that there wasn't one specified in the XML).
  25518. The string can actually be a simple wildcard, containing "*"
  25519. and "?" characters
  25520. @param preferredSetupOptions if this is non-null, the structure will be used as the
  25521. set of preferred settings when opening the device. If you
  25522. use this parameter, the preferredDefaultDeviceName
  25523. field will be ignored
  25524. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25525. */
  25526. const String initialise (const int numInputChannelsNeeded,
  25527. const int numOutputChannelsNeeded,
  25528. const XmlElement* const savedState,
  25529. const bool selectDefaultDeviceOnFailure,
  25530. const String& preferredDefaultDeviceName = String::empty,
  25531. const AudioDeviceSetup* preferredSetupOptions = 0);
  25532. /** Returns some XML representing the current state of the manager.
  25533. This stores the current device, its samplerate, block size, etc, and
  25534. can be restored later with initialise().
  25535. */
  25536. XmlElement* createStateXml() const;
  25537. /** Returns the current device properties that are in use.
  25538. @see setAudioDeviceSetup
  25539. */
  25540. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25541. /** Changes the current device or its settings.
  25542. If you want to change a device property, like the current sample rate or
  25543. block size, you can call getAudioDeviceSetup() to retrieve the current
  25544. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  25545. and pass it back into this method to apply the new settings.
  25546. @param newSetup the settings that you'd like to use
  25547. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25548. settings will be taken as having been explicitly chosen by the
  25549. user, and the next time createStateXml() is called, these settings
  25550. will be returned. If it's false, then the device is treated as a
  25551. temporary or default device, and a call to createStateXml() will
  25552. return either the last settings that were made with treatAsChosenDevice
  25553. as true, or the last XML settings that were passed into initialise().
  25554. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25555. @see getAudioDeviceSetup
  25556. */
  25557. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25558. const bool treatAsChosenDevice);
  25559. /** Returns the currently-active audio device. */
  25560. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25561. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25562. void setCurrentAudioDeviceType (const String& type,
  25563. const bool treatAsChosenDevice);
  25564. /** Closes the currently-open device.
  25565. You can call restartLastAudioDevice() later to reopen it in the same state
  25566. that it was just in.
  25567. */
  25568. void closeAudioDevice();
  25569. /** Tries to reload the last audio device that was running.
  25570. Note that this only reloads the last device that was running before
  25571. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25572. and can only be called after a device has been opened with SetAudioDevice().
  25573. If a device is already open, this call will do nothing.
  25574. */
  25575. void restartLastAudioDevice();
  25576. /** Gives the manager an audio callback to use.
  25577. The manager will redirect callbacks from whatever audio device is currently
  25578. in use to this callback object.
  25579. You can pass 0 in here to stop callbacks being made.
  25580. */
  25581. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25582. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25583. Returns a value between 0 and 1.0
  25584. */
  25585. double getCpuUsage() const;
  25586. /** Enables or disables a midi input device.
  25587. The list of devices can be obtained with the MidiInput::getDevices() method.
  25588. Any incoming messages from enabled input devices will be forwarded on to all the
  25589. listeners that have been registered with the addMidiInputCallback() method. They
  25590. can either register for messages from a particular device, or from just the
  25591. "default" midi input.
  25592. Routing the midi input via an AudioDeviceManager means that when a listener
  25593. registers for the default midi input, this default device can be changed by the
  25594. manager without the listeners having to know about it or re-register.
  25595. It also means that a listener can stay registered for a midi input that is disabled
  25596. or not present, so that when the input is re-enabled, the listener will start
  25597. receiving messages again.
  25598. @see addMidiInputCallback, isMidiInputEnabled
  25599. */
  25600. void setMidiInputEnabled (const String& midiInputDeviceName,
  25601. const bool enabled);
  25602. /** Returns true if a given midi input device is being used.
  25603. @see setMidiInputEnabled
  25604. */
  25605. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25606. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25607. The device name can be empty to indicate that it wants events from whatever the
  25608. current "default" device is. Or it can be the name of one of the midi input devices
  25609. (see MidiInput::getDevices() for the names).
  25610. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25611. events forwarded on to listeners.
  25612. */
  25613. void addMidiInputCallback (const String& midiInputDeviceName,
  25614. MidiInputCallback* callback);
  25615. /** Removes a listener that was previously registered with addMidiInputCallback().
  25616. */
  25617. void removeMidiInputCallback (const String& midiInputDeviceName,
  25618. MidiInputCallback* callback);
  25619. /** Sets a midi output device to use as the default.
  25620. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25621. The specified device will be opened automatically and can be retrieved with the
  25622. getDefaultMidiOutput() method.
  25623. Pass in an empty string to deselect all devices. For the default device, you
  25624. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25625. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25626. */
  25627. void setDefaultMidiOutput (const String& deviceName);
  25628. /** Returns the name of the default midi output.
  25629. @see setDefaultMidiOutput, getDefaultMidiOutput
  25630. */
  25631. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25632. /** Returns the current default midi output device.
  25633. If no device has been selected, or the device can't be opened, this will
  25634. return 0.
  25635. @see getDefaultMidiOutputName
  25636. */
  25637. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25638. /**
  25639. */
  25640. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25641. /** Creates a list of available types.
  25642. This will add a set of new AudioIODeviceType objects to the specified list, to
  25643. represent each available types of device.
  25644. You can override this if your app needs to do something specific, like avoid
  25645. using DirectSound devices, etc.
  25646. */
  25647. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25648. /** Plays a beep through the current audio device.
  25649. This is here to allow the audio setup UI panels to easily include a "test"
  25650. button so that the user can check where the audio is coming from.
  25651. */
  25652. void playTestSound();
  25653. /** Turns on level-measuring.
  25654. When enabled, the device manager will measure the peak input level
  25655. across all channels, and you can get this level by calling getCurrentInputLevel().
  25656. This is mainly intended for audio setup UI panels to use to create a mic
  25657. level display, so that the user can check that they've selected the right
  25658. device.
  25659. A simple filter is used to make the level decay smoothly, but this is
  25660. only intended for giving rough feedback, and not for any kind of accurate
  25661. measurement.
  25662. */
  25663. void enableInputLevelMeasurement (const bool enableMeasurement);
  25664. /** Returns the current input level.
  25665. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25666. See enableInputLevelMeasurement() for more info.
  25667. */
  25668. double getCurrentInputLevel() const;
  25669. juce_UseDebuggingNewOperator
  25670. private:
  25671. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25672. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25673. AudioDeviceSetup currentSetup;
  25674. AudioIODevice* currentAudioDevice;
  25675. AudioIODeviceCallback* currentCallback;
  25676. int numInputChansNeeded, numOutputChansNeeded;
  25677. String currentDeviceType;
  25678. BitArray inputChannels, outputChannels;
  25679. XmlElement* lastExplicitSettings;
  25680. mutable bool listNeedsScanning;
  25681. bool useInputNames, inputLevelMeasurementEnabled;
  25682. double inputLevel;
  25683. AudioSampleBuffer* testSound;
  25684. int testSoundPosition;
  25685. StringArray midiInsFromXml;
  25686. OwnedArray <MidiInput> enabledMidiInputs;
  25687. Array <MidiInputCallback*> midiCallbacks;
  25688. Array <MidiInput*> midiCallbackDevices;
  25689. String defaultMidiOutputName;
  25690. MidiOutput* defaultMidiOutput;
  25691. CriticalSection audioCallbackLock, midiCallbackLock;
  25692. double cpuUsageMs, timeToCpuScale;
  25693. class CallbackHandler : public AudioIODeviceCallback,
  25694. public MidiInputCallback
  25695. {
  25696. public:
  25697. AudioDeviceManager* owner;
  25698. void audioDeviceIOCallback (const float** inputChannelData,
  25699. int totalNumInputChannels,
  25700. float** outputChannelData,
  25701. int totalNumOutputChannels,
  25702. int numSamples);
  25703. void audioDeviceAboutToStart (AudioIODevice*);
  25704. void audioDeviceStopped();
  25705. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25706. };
  25707. CallbackHandler callbackHandler;
  25708. friend class CallbackHandler;
  25709. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25710. int totalNumInputChannels,
  25711. float** outputChannelData,
  25712. int totalNumOutputChannels,
  25713. int numSamples);
  25714. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25715. void audioDeviceStoppedInt();
  25716. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25717. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25718. const BitArray& ins, const BitArray& outs);
  25719. void stopDevice();
  25720. void updateXml();
  25721. void createDeviceTypesIfNeeded();
  25722. void scanDevicesIfNeeded();
  25723. void deleteCurrentDevice();
  25724. double chooseBestSampleRate (double preferred) const;
  25725. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25726. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25727. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25728. AudioDeviceManager (const AudioDeviceManager&);
  25729. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25730. };
  25731. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25732. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25733. #endif
  25734. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25735. #endif
  25736. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25737. #endif
  25738. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25739. #endif
  25740. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25741. #endif
  25742. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25743. /********* Start of inlined file: juce_Sampler.h *********/
  25744. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25745. #define __JUCE_SAMPLER_JUCEHEADER__
  25746. /********* Start of inlined file: juce_Synthesiser.h *********/
  25747. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25748. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25749. /**
  25750. Describes one of the sounds that a Synthesiser can play.
  25751. A synthesiser can contain one or more sounds, and a sound can choose which
  25752. midi notes and channels can trigger it.
  25753. The SynthesiserSound is a passive class that just describes what the sound is -
  25754. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25755. more than one SynthesiserVoice to play the same sound at the same time.
  25756. @see Synthesiser, SynthesiserVoice
  25757. */
  25758. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25759. {
  25760. protected:
  25761. SynthesiserSound();
  25762. public:
  25763. /** Destructor. */
  25764. virtual ~SynthesiserSound();
  25765. /** Returns true if this sound should be played when a given midi note is pressed.
  25766. The Synthesiser will use this information when deciding which sounds to trigger
  25767. for a given note.
  25768. */
  25769. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25770. /** Returns true if the sound should be triggered by midi events on a given channel.
  25771. The Synthesiser will use this information when deciding which sounds to trigger
  25772. for a given note.
  25773. */
  25774. virtual bool appliesToChannel (const int midiChannel) = 0;
  25775. /**
  25776. */
  25777. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25778. juce_UseDebuggingNewOperator
  25779. };
  25780. /**
  25781. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25782. A voice plays a single sound at a time, and a synthesiser holds an array of
  25783. voices so that it can play polyphonically.
  25784. @see Synthesiser, SynthesiserSound
  25785. */
  25786. class JUCE_API SynthesiserVoice
  25787. {
  25788. public:
  25789. /** Creates a voice. */
  25790. SynthesiserVoice();
  25791. /** Destructor. */
  25792. virtual ~SynthesiserVoice();
  25793. /** Returns the midi note that this voice is currently playing.
  25794. Returns a value less than 0 if no note is playing.
  25795. */
  25796. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25797. /** Returns the sound that this voice is currently playing.
  25798. Returns 0 if it's not playing.
  25799. */
  25800. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25801. /** Must return true if this voice object is capable of playing the given sound.
  25802. If there are different classes of sound, and different classes of voice, a voice can
  25803. choose which ones it wants to take on.
  25804. A typical implementation of this method may just return true if there's only one type
  25805. of voice and sound, or it might check the type of the sound object passed-in and
  25806. see if it's one that it understands.
  25807. */
  25808. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25809. /** Called to start a new note.
  25810. This will be called during the rendering callback, so must be fast and thread-safe.
  25811. */
  25812. virtual void startNote (const int midiNoteNumber,
  25813. const float velocity,
  25814. SynthesiserSound* sound,
  25815. const int currentPitchWheelPosition) = 0;
  25816. /** Called to stop a note.
  25817. This will be called during the rendering callback, so must be fast and thread-safe.
  25818. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25819. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25820. and allow the synth to reassign it another sound.
  25821. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25822. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25823. finishes playing (during the rendering callback), it must make sure that it calls
  25824. clearCurrentNote().
  25825. */
  25826. virtual void stopNote (const bool allowTailOff) = 0;
  25827. /** Called to let the voice know that the pitch wheel has been moved.
  25828. This will be called during the rendering callback, so must be fast and thread-safe.
  25829. */
  25830. virtual void pitchWheelMoved (const int newValue) = 0;
  25831. /** Called to let the voice know that a midi controller has been moved.
  25832. This will be called during the rendering callback, so must be fast and thread-safe.
  25833. */
  25834. virtual void controllerMoved (const int controllerNumber,
  25835. const int newValue) = 0;
  25836. /** Renders the next block of data for this voice.
  25837. The output audio data must be added to the current contents of the buffer provided.
  25838. Only the region of the buffer between startSample and (startSample + numSamples)
  25839. should be altered by this method.
  25840. If the voice is currently silent, it should just return without doing anything.
  25841. If the sound that the voice is playing finishes during the course of this rendered
  25842. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25843. The size of the blocks that are rendered can change each time it is called, and may
  25844. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25845. the voice's methods will be called to tell it about note and controller events.
  25846. */
  25847. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25848. int startSample,
  25849. int numSamples) = 0;
  25850. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25851. midi channel.
  25852. If it's not currently playing, this will return false.
  25853. */
  25854. bool isPlayingChannel (const int midiChannel) const;
  25855. /** Changes the voice's reference sample rate.
  25856. The rate is set so that subclasses know the output rate and can set their pitch
  25857. accordingly.
  25858. This method is called by the synth, and subclasses can access the current rate with
  25859. the currentSampleRate member.
  25860. */
  25861. void setCurrentPlaybackSampleRate (const double newRate);
  25862. juce_UseDebuggingNewOperator
  25863. protected:
  25864. /** Returns the current target sample rate at which rendering is being done.
  25865. This is available for subclasses so they can pitch things correctly.
  25866. */
  25867. double getSampleRate() const throw() { return currentSampleRate; }
  25868. /** Resets the state of this voice after a sound has finished playing.
  25869. The subclass must call this when it finishes playing a note and becomes available
  25870. to play new ones.
  25871. It must either call it in the stopNote() method, or if the voice is tailing off,
  25872. then it should call it later during the renderNextBlock method, as soon as it
  25873. finishes its tail-off.
  25874. It can also be called at any time during the render callback if the sound happens
  25875. to have finished, e.g. if it's playing a sample and the sample finishes.
  25876. */
  25877. void clearCurrentNote();
  25878. private:
  25879. friend class Synthesiser;
  25880. double currentSampleRate;
  25881. int currentlyPlayingNote;
  25882. uint32 noteOnTime;
  25883. SynthesiserSound::Ptr currentlyPlayingSound;
  25884. };
  25885. /**
  25886. Base class for a musical device that can play sounds.
  25887. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25888. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25889. which can play back one of these sounds.
  25890. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25891. set of sounds, and a set of voices it can use to play them. If you only give it
  25892. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25893. have available.
  25894. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25895. events that go in will be scanned for note on/off messages, and these are used to
  25896. start and stop the voices playing the appropriate sounds.
  25897. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25898. noteOff() and other controller methods.
  25899. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25900. what the target playback rate is. This value is passed on to the voices so that
  25901. they can pitch their output correctly.
  25902. */
  25903. class JUCE_API Synthesiser
  25904. {
  25905. public:
  25906. /** Creates a new synthesiser.
  25907. You'll need to add some sounds and voices before it'll make any sound..
  25908. */
  25909. Synthesiser();
  25910. /** Destructor. */
  25911. virtual ~Synthesiser();
  25912. /** Deletes all voices. */
  25913. void clearVoices();
  25914. /** Returns the number of voices that have been added. */
  25915. int getNumVoices() const throw() { return voices.size(); }
  25916. /** Returns one of the voices that have been added. */
  25917. SynthesiserVoice* getVoice (const int index) const throw();
  25918. /** Adds a new voice to the synth.
  25919. All the voices should be the same class of object and are treated equally.
  25920. The object passed in will be managed by the synthesiser, which will delete
  25921. it later on when no longer needed. The caller should not retain a pointer to the
  25922. voice.
  25923. */
  25924. void addVoice (SynthesiserVoice* const newVoice);
  25925. /** Deletes one of the voices. */
  25926. void removeVoice (const int index);
  25927. /** Deletes all sounds. */
  25928. void clearSounds();
  25929. /** Returns the number of sounds that have been added to the synth. */
  25930. int getNumSounds() const throw() { return sounds.size(); }
  25931. /** Returns one of the sounds. */
  25932. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25933. /** Adds a new sound to the synthesiser.
  25934. The object passed in is reference counted, so will be deleted when it is removed
  25935. from the synthesiser, and when no voices are still using it.
  25936. */
  25937. void addSound (const SynthesiserSound::Ptr& newSound);
  25938. /** Removes and deletes one of the sounds. */
  25939. void removeSound (const int index);
  25940. /** If set to true, then the synth will try to take over an existing voice if
  25941. it runs out and needs to play another note.
  25942. The value of this boolean is passed into findFreeVoice(), so the result will
  25943. depend on the implementation of this method.
  25944. */
  25945. void setNoteStealingEnabled (const bool shouldStealNotes);
  25946. /** Returns true if note-stealing is enabled.
  25947. @see setNoteStealingEnabled
  25948. */
  25949. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25950. /** Triggers a note-on event.
  25951. The default method here will find all the sounds that want to be triggered by
  25952. this note/channel. For each sound, it'll try to find a free voice, and use the
  25953. voice to start playing the sound.
  25954. Subclasses might want to override this if they need a more complex algorithm.
  25955. This method will be called automatically according to the midi data passed into
  25956. renderNextBlock(), but may be called explicitly too.
  25957. */
  25958. virtual void noteOn (const int midiChannel,
  25959. const int midiNoteNumber,
  25960. const float velocity);
  25961. /** Triggers a note-off event.
  25962. This will turn off any voices that are playing a sound for the given note/channel.
  25963. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25964. (if they can do). If this is false, the notes will all be cut off immediately.
  25965. This method will be called automatically according to the midi data passed into
  25966. renderNextBlock(), but may be called explicitly too.
  25967. */
  25968. virtual void noteOff (const int midiChannel,
  25969. const int midiNoteNumber,
  25970. const bool allowTailOff);
  25971. /** Turns off all notes.
  25972. This will turn off any voices that are playing a sound on the given midi channel.
  25973. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25974. which channel they're playing.
  25975. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25976. (if they can do). If this is false, the notes will all be cut off immediately.
  25977. This method will be called automatically according to the midi data passed into
  25978. renderNextBlock(), but may be called explicitly too.
  25979. */
  25980. virtual void allNotesOff (const int midiChannel,
  25981. const bool allowTailOff);
  25982. /** Sends a pitch-wheel message.
  25983. This will send a pitch-wheel message to any voices that are playing sounds on
  25984. the given midi channel.
  25985. This method will be called automatically according to the midi data passed into
  25986. renderNextBlock(), but may be called explicitly too.
  25987. @param midiChannel the midi channel for the event
  25988. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25989. */
  25990. virtual void handlePitchWheel (const int midiChannel,
  25991. const int wheelValue);
  25992. /** Sends a midi controller message.
  25993. This will send a midi controller message to any voices that are playing sounds on
  25994. the given midi channel.
  25995. This method will be called automatically according to the midi data passed into
  25996. renderNextBlock(), but may be called explicitly too.
  25997. @param midiChannel the midi channel for the event
  25998. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  25999. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  26000. */
  26001. virtual void handleController (const int midiChannel,
  26002. const int controllerNumber,
  26003. const int controllerValue);
  26004. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  26005. render.
  26006. This value is propagated to the voices so that they can use it to render the correct
  26007. pitches.
  26008. */
  26009. void setCurrentPlaybackSampleRate (const double sampleRate);
  26010. /** Creates the next block of audio output.
  26011. This will process the next numSamples of data from all the voices, and add that output
  26012. to the audio block supplied, starting from the offset specified. Note that the
  26013. data will be added to the current contents of the buffer, so you should clear it
  26014. before calling this method if necessary.
  26015. The midi events in the inputMidi buffer are parsed for note and controller events,
  26016. and these are used to trigger the voices. Note that the startSample offset applies
  26017. both to the audio output buffer and the midi input buffer, so any midi events
  26018. with timestamps outside the specified region will be ignored.
  26019. */
  26020. void renderNextBlock (AudioSampleBuffer& outputAudio,
  26021. const MidiBuffer& inputMidi,
  26022. int startSample,
  26023. int numSamples);
  26024. juce_UseDebuggingNewOperator
  26025. protected:
  26026. /** This is used to control access to the rendering callback and the note trigger methods. */
  26027. CriticalSection lock;
  26028. OwnedArray <SynthesiserVoice> voices;
  26029. ReferenceCountedArray <SynthesiserSound> sounds;
  26030. /** The last pitch-wheel values for each midi channel. */
  26031. int lastPitchWheelValues [16];
  26032. /** Searches through the voices to find one that's not currently playing, and which
  26033. can play the given sound.
  26034. Returns 0 if all voices are busy and stealing isn't enabled.
  26035. This can be overridden to implement custom voice-stealing algorithms.
  26036. */
  26037. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  26038. const bool stealIfNoneAvailable) const;
  26039. /** Starts a specified voice playing a particular sound.
  26040. You'll probably never need to call this, it's used internally by noteOn(), but
  26041. may be needed by subclasses for custom behaviours.
  26042. */
  26043. void startVoice (SynthesiserVoice* const voice,
  26044. SynthesiserSound* const sound,
  26045. const int midiChannel,
  26046. const int midiNoteNumber,
  26047. const float velocity);
  26048. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  26049. int findFreeVoice (const bool) const { return 0; }
  26050. private:
  26051. double sampleRate;
  26052. uint32 lastNoteOnCounter;
  26053. bool shouldStealNotes;
  26054. Synthesiser (const Synthesiser&);
  26055. const Synthesiser& operator= (const Synthesiser&);
  26056. };
  26057. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  26058. /********* End of inlined file: juce_Synthesiser.h *********/
  26059. /**
  26060. A subclass of SynthesiserSound that represents a sampled audio clip.
  26061. This is a pretty basic sampler, and just attempts to load the whole audio stream
  26062. into memory.
  26063. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26064. give it some SampledSound objects to play.
  26065. @see SamplerVoice, Synthesiser, SynthesiserSound
  26066. */
  26067. class JUCE_API SamplerSound : public SynthesiserSound
  26068. {
  26069. public:
  26070. /** Creates a sampled sound from an audio reader.
  26071. This will attempt to load the audio from the source into memory and store
  26072. it in this object.
  26073. @param name a name for the sample
  26074. @param source the audio to load. This object can be safely deleted by the
  26075. caller after this constructor returns
  26076. @param midiNotes the set of midi keys that this sound should be played on. This
  26077. is used by the SynthesiserSound::appliesToNote() method
  26078. @param midiNoteForNormalPitch the midi note at which the sample should be played
  26079. with its natural rate. All other notes will be pitched
  26080. up or down relative to this one
  26081. @param attackTimeSecs the attack (fade-in) time, in seconds
  26082. @param releaseTimeSecs the decay (fade-out) time, in seconds
  26083. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  26084. source, in seconds
  26085. */
  26086. SamplerSound (const String& name,
  26087. AudioFormatReader& source,
  26088. const BitArray& midiNotes,
  26089. const int midiNoteForNormalPitch,
  26090. const double attackTimeSecs,
  26091. const double releaseTimeSecs,
  26092. const double maxSampleLengthSeconds);
  26093. /** Destructor. */
  26094. ~SamplerSound();
  26095. /** Returns the sample's name */
  26096. const String& getName() const throw() { return name; }
  26097. /** Returns the audio sample data.
  26098. This could be 0 if there was a problem loading it.
  26099. */
  26100. AudioSampleBuffer* getAudioData() const throw() { return data; }
  26101. bool appliesToNote (const int midiNoteNumber);
  26102. bool appliesToChannel (const int midiChannel);
  26103. juce_UseDebuggingNewOperator
  26104. private:
  26105. friend class SamplerVoice;
  26106. String name;
  26107. AudioSampleBuffer* data;
  26108. double sourceSampleRate;
  26109. BitArray midiNotes;
  26110. int length, attackSamples, releaseSamples;
  26111. int midiRootNote;
  26112. };
  26113. /**
  26114. A subclass of SynthesiserVoice that can play a SamplerSound.
  26115. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26116. give it some SampledSound objects to play.
  26117. @see SamplerSound, Synthesiser, SynthesiserVoice
  26118. */
  26119. class JUCE_API SamplerVoice : public SynthesiserVoice
  26120. {
  26121. public:
  26122. /** Creates a SamplerVoice.
  26123. */
  26124. SamplerVoice();
  26125. /** Destructor. */
  26126. ~SamplerVoice();
  26127. bool canPlaySound (SynthesiserSound* sound);
  26128. void startNote (const int midiNoteNumber,
  26129. const float velocity,
  26130. SynthesiserSound* sound,
  26131. const int currentPitchWheelPosition);
  26132. void stopNote (const bool allowTailOff);
  26133. void pitchWheelMoved (const int newValue);
  26134. void controllerMoved (const int controllerNumber,
  26135. const int newValue);
  26136. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  26137. juce_UseDebuggingNewOperator
  26138. private:
  26139. double pitchRatio;
  26140. double sourceSamplePosition;
  26141. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  26142. bool isInAttack, isInRelease;
  26143. };
  26144. #endif // __JUCE_SAMPLER_JUCEHEADER__
  26145. /********* End of inlined file: juce_Sampler.h *********/
  26146. #endif
  26147. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26148. #endif
  26149. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26150. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26151. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26152. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26153. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  26154. /**
  26155. Implements a plugin format manager for AudioUnits.
  26156. */
  26157. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  26158. {
  26159. public:
  26160. AudioUnitPluginFormat();
  26161. ~AudioUnitPluginFormat();
  26162. const String getName() const { return "AudioUnit"; }
  26163. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26164. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26165. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26166. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26167. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26168. bool doesPluginStillExist (const PluginDescription& desc);
  26169. const FileSearchPath getDefaultLocationsToSearch();
  26170. juce_UseDebuggingNewOperator
  26171. private:
  26172. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  26173. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  26174. };
  26175. #endif
  26176. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26177. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  26178. #endif
  26179. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26180. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  26181. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26182. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26183. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  26184. // Sorry, this file is just a placeholder at the moment!...
  26185. /**
  26186. Implements a plugin format manager for DirectX plugins.
  26187. */
  26188. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  26189. {
  26190. public:
  26191. DirectXPluginFormat();
  26192. ~DirectXPluginFormat();
  26193. const String getName() const { return "DirectX"; }
  26194. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26195. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26196. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26197. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26198. const FileSearchPath getDefaultLocationsToSearch();
  26199. juce_UseDebuggingNewOperator
  26200. private:
  26201. DirectXPluginFormat (const DirectXPluginFormat&);
  26202. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  26203. };
  26204. #endif
  26205. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26206. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  26207. #endif
  26208. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26209. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  26210. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26211. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26212. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  26213. // Sorry, this file is just a placeholder at the moment!...
  26214. /**
  26215. Implements a plugin format manager for DirectX plugins.
  26216. */
  26217. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26218. {
  26219. public:
  26220. LADSPAPluginFormat();
  26221. ~LADSPAPluginFormat();
  26222. const String getName() const { return "LADSPA"; }
  26223. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26224. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26225. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26226. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26227. const FileSearchPath getDefaultLocationsToSearch();
  26228. juce_UseDebuggingNewOperator
  26229. private:
  26230. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26231. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26232. };
  26233. #endif
  26234. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26235. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26236. #endif
  26237. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26238. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  26239. #ifdef __aeffect__
  26240. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26241. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26242. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26243. events to the list.
  26244. This is used by both the VST hosting code and the plugin wrapper.
  26245. */
  26246. class VSTMidiEventList
  26247. {
  26248. public:
  26249. VSTMidiEventList()
  26250. : events (0), numEventsUsed (0), numEventsAllocated (0)
  26251. {
  26252. }
  26253. ~VSTMidiEventList()
  26254. {
  26255. freeEvents();
  26256. }
  26257. void clear()
  26258. {
  26259. numEventsUsed = 0;
  26260. if (events != 0)
  26261. events->numEvents = 0;
  26262. }
  26263. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26264. {
  26265. ensureSize (numEventsUsed + 1);
  26266. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26267. events->numEvents = ++numEventsUsed;
  26268. if (numBytes <= 4)
  26269. {
  26270. if (e->type == kVstSysExType)
  26271. {
  26272. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26273. e->type = kVstMidiType;
  26274. e->byteSize = sizeof (VstMidiEvent);
  26275. e->noteLength = 0;
  26276. e->noteOffset = 0;
  26277. e->detune = 0;
  26278. e->noteOffVelocity = 0;
  26279. }
  26280. e->deltaFrames = frameOffset;
  26281. memcpy (e->midiData, midiData, numBytes);
  26282. }
  26283. else
  26284. {
  26285. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26286. if (se->type == kVstSysExType)
  26287. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26288. else
  26289. se->sysexDump = (char*) juce_malloc (numBytes);
  26290. memcpy (se->sysexDump, midiData, numBytes);
  26291. se->type = kVstSysExType;
  26292. se->byteSize = sizeof (VstMidiSysexEvent);
  26293. se->deltaFrames = frameOffset;
  26294. se->flags = 0;
  26295. se->dumpBytes = numBytes;
  26296. se->resvd1 = 0;
  26297. se->resvd2 = 0;
  26298. }
  26299. }
  26300. // Handy method to pull the events out of an event buffer supplied by the host
  26301. // or plugin.
  26302. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26303. {
  26304. for (int i = 0; i < events->numEvents; ++i)
  26305. {
  26306. const VstEvent* const e = events->events[i];
  26307. if (e != 0)
  26308. {
  26309. if (e->type == kVstMidiType)
  26310. {
  26311. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26312. 4, e->deltaFrames);
  26313. }
  26314. else if (e->type == kVstSysExType)
  26315. {
  26316. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26317. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26318. e->deltaFrames);
  26319. }
  26320. }
  26321. }
  26322. }
  26323. void ensureSize (int numEventsNeeded)
  26324. {
  26325. if (numEventsNeeded > numEventsAllocated)
  26326. {
  26327. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26328. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26329. if (events == 0)
  26330. events = (VstEvents*) juce_calloc (size);
  26331. else
  26332. events = (VstEvents*) juce_realloc (events, size);
  26333. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26334. {
  26335. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26336. (int) sizeof (VstMidiSysexEvent)));
  26337. e->type = kVstMidiType;
  26338. e->byteSize = sizeof (VstMidiEvent);
  26339. events->events[i] = (VstEvent*) e;
  26340. }
  26341. numEventsAllocated = numEventsNeeded;
  26342. }
  26343. }
  26344. void freeEvents()
  26345. {
  26346. if (events != 0)
  26347. {
  26348. for (int i = numEventsAllocated; --i >= 0;)
  26349. {
  26350. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26351. if (e->type == kVstSysExType)
  26352. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26353. juce_free (e);
  26354. }
  26355. juce_free (events);
  26356. events = 0;
  26357. numEventsUsed = 0;
  26358. numEventsAllocated = 0;
  26359. }
  26360. }
  26361. VstEvents* events;
  26362. private:
  26363. int numEventsUsed, numEventsAllocated;
  26364. };
  26365. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26366. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26367. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  26368. #endif
  26369. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26370. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26371. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26372. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26373. #if JUCE_PLUGINHOST_VST
  26374. /**
  26375. Implements a plugin format manager for VSTs.
  26376. */
  26377. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26378. {
  26379. public:
  26380. VSTPluginFormat();
  26381. ~VSTPluginFormat();
  26382. const String getName() const { return "VST"; }
  26383. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26384. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26385. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26386. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26387. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26388. bool doesPluginStillExist (const PluginDescription& desc);
  26389. const FileSearchPath getDefaultLocationsToSearch();
  26390. juce_UseDebuggingNewOperator
  26391. private:
  26392. VSTPluginFormat (const VSTPluginFormat&);
  26393. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26394. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26395. };
  26396. #endif
  26397. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26398. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26399. #endif
  26400. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26401. #endif
  26402. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26403. #endif
  26404. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26405. #endif
  26406. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26407. #endif
  26408. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26409. #endif
  26410. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26411. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26412. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26413. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26414. /**
  26415. Scans a directory for plugins, and adds them to a KnownPluginList.
  26416. To use one of these, create it and call scanNextFile() repeatedly, until
  26417. it returns false.
  26418. */
  26419. class JUCE_API PluginDirectoryScanner
  26420. {
  26421. public:
  26422. /**
  26423. Creates a scanner.
  26424. @param listToAddResultsTo this will get the new types added to it.
  26425. @param formatToLookFor this is the type of format that you want to look for
  26426. @param directoriesToSearch the path to search
  26427. @param searchRecursively true to search recursively
  26428. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26429. be used as a file to store the names of any plugins
  26430. that crash during initialisation. If there are
  26431. any plugins listed in it, then these will always
  26432. be scanned after all other possible files have
  26433. been tried - in this way, even if there's a few
  26434. dodgy plugins in your path, then a couple of rescans
  26435. will still manage to find all the proper plugins.
  26436. It's probably best to choose a file in the user's
  26437. application data directory (alongside your app's
  26438. settings file) for this. The file format it uses
  26439. is just a list of filenames of the modules that
  26440. failed.
  26441. */
  26442. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26443. AudioPluginFormat& formatToLookFor,
  26444. FileSearchPath directoriesToSearch,
  26445. const bool searchRecursively,
  26446. const File& deadMansPedalFile);
  26447. /** Destructor. */
  26448. ~PluginDirectoryScanner();
  26449. /** Tries the next likely-looking file.
  26450. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26451. re-tested if it's not already in the list, or if the file's modification
  26452. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26453. false, the file will always be reloaded and tested.
  26454. Returns false when there are no more files to try.
  26455. */
  26456. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26457. /** Returns the description of the plugin that will be scanned during the next
  26458. call to scanNextFile().
  26459. This is handy if you want to show the user which file is currently getting
  26460. scanned.
  26461. */
  26462. const String getNextPluginFileThatWillBeScanned() const throw();
  26463. /** Returns the estimated progress, between 0 and 1.
  26464. */
  26465. float getProgress() const { return progress; }
  26466. /** This returns a list of all the filenames of things that looked like being
  26467. a plugin file, but which failed to open for some reason.
  26468. */
  26469. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26470. juce_UseDebuggingNewOperator
  26471. private:
  26472. KnownPluginList& list;
  26473. AudioPluginFormat& format;
  26474. StringArray filesOrIdentifiersToScan;
  26475. File deadMansPedalFile;
  26476. StringArray failedFiles;
  26477. int nextIndex;
  26478. float progress;
  26479. const StringArray getDeadMansPedalFile() throw();
  26480. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26481. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26482. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26483. };
  26484. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26485. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26486. #endif
  26487. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26488. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26489. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26490. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26491. /********* Start of inlined file: juce_ListBox.h *********/
  26492. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26493. #define __JUCE_LISTBOX_JUCEHEADER__
  26494. class ListViewport;
  26495. /**
  26496. A subclass of this is used to drive a ListBox.
  26497. @see ListBox
  26498. */
  26499. class JUCE_API ListBoxModel
  26500. {
  26501. public:
  26502. /** Destructor. */
  26503. virtual ~ListBoxModel() {}
  26504. /** This has to return the number of items in the list.
  26505. @see ListBox::getNumRows()
  26506. */
  26507. virtual int getNumRows() = 0;
  26508. /** This method must be implemented to draw a row of the list.
  26509. */
  26510. virtual void paintListBoxItem (int rowNumber,
  26511. Graphics& g,
  26512. int width, int height,
  26513. bool rowIsSelected) = 0;
  26514. /** This is used to create or update a custom component to go in a row of the list.
  26515. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26516. and handle mouse clicks with listBoxItemClicked().
  26517. This method will be called whenever a custom component might need to be updated - e.g.
  26518. when the table is changed, or TableListBox::updateContent() is called.
  26519. If you don't need a custom component for the specified row, then return 0.
  26520. If you do want a custom component, and the existingComponentToUpdate is null, then
  26521. this method must create a suitable new component and return it.
  26522. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26523. by this method. In this case, the method must either update it to make sure it's correctly representing
  26524. the given row (which may be different from the one that the component was created for), or it can
  26525. delete this component and return a new one.
  26526. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26527. */
  26528. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26529. Component* existingComponentToUpdate);
  26530. /** This can be overridden to react to the user clicking on a row.
  26531. @see listBoxItemDoubleClicked
  26532. */
  26533. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26534. /** This can be overridden to react to the user double-clicking on a row.
  26535. @see listBoxItemClicked
  26536. */
  26537. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26538. /** This can be overridden to react to the user double-clicking on a part of the list where
  26539. there are no rows.
  26540. @see listBoxItemClicked
  26541. */
  26542. virtual void backgroundClicked();
  26543. /** Override this to be informed when rows are selected or deselected.
  26544. This will be called whenever a row is selected or deselected. If a range of
  26545. rows is selected all at once, this will just be called once for that event.
  26546. @param lastRowSelected the last row that the user selected. If no
  26547. rows are currently selected, this may be -1.
  26548. */
  26549. virtual void selectedRowsChanged (int lastRowSelected);
  26550. /** Override this to be informed when the delete key is pressed.
  26551. If no rows are selected when they press the key, this won't be called.
  26552. @param lastRowSelected the last row that had been selected when they pressed the
  26553. key - if there are multiple selections, this might not be
  26554. very useful
  26555. */
  26556. virtual void deleteKeyPressed (int lastRowSelected);
  26557. /** Override this to be informed when the return key is pressed.
  26558. If no rows are selected when they press the key, this won't be called.
  26559. @param lastRowSelected the last row that had been selected when they pressed the
  26560. key - if there are multiple selections, this might not be
  26561. very useful
  26562. */
  26563. virtual void returnKeyPressed (int lastRowSelected);
  26564. /** Override this to be informed when the list is scrolled.
  26565. This might be caused by the user moving the scrollbar, or by programmatic changes
  26566. to the list position.
  26567. */
  26568. virtual void listWasScrolled();
  26569. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26570. If this returns a non-empty name then when the user drags a row, the listbox will
  26571. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26572. a drag-and-drop operation, using this string as the source description, with the listbox
  26573. itself as the source component.
  26574. @see DragAndDropContainer::startDragging
  26575. */
  26576. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26577. };
  26578. /**
  26579. A list of items that can be scrolled vertically.
  26580. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26581. either paint each row of the list and respond to events via callbacks, or for
  26582. more specialised tasks, it can supply a custom component to fill each row.
  26583. @see ComboBox, TableListBox
  26584. */
  26585. class JUCE_API ListBox : public Component,
  26586. public SettableTooltipClient
  26587. {
  26588. public:
  26589. /** Creates a ListBox.
  26590. The model pointer passed-in can be null, in which case you can set it later
  26591. with setModel().
  26592. */
  26593. ListBox (const String& componentName,
  26594. ListBoxModel* const model);
  26595. /** Destructor. */
  26596. ~ListBox();
  26597. /** Changes the current data model to display. */
  26598. void setModel (ListBoxModel* const newModel);
  26599. /** Returns the current list model. */
  26600. ListBoxModel* getModel() const throw() { return model; }
  26601. /** Causes the list to refresh its content.
  26602. Call this when the number of rows in the list changes, or if you want it
  26603. to call refreshComponentForRow() on all the row components.
  26604. Be careful not to call it from a different thread, though, as it's not
  26605. thread-safe.
  26606. */
  26607. void updateContent();
  26608. /** Turns on multiple-selection of rows.
  26609. By default this is disabled.
  26610. When your row component gets clicked you'll need to call the
  26611. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26612. clicked and to get it to do the appropriate selection based on whether
  26613. the ctrl/shift keys are held down.
  26614. */
  26615. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26616. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26617. This function is here primarily for the ComboBox class to use, but might be
  26618. useful for some other purpose too.
  26619. */
  26620. void setMouseMoveSelectsRows (bool shouldSelect);
  26621. /** Selects a row.
  26622. If the row is already selected, this won't do anything.
  26623. @param rowNumber the row to select
  26624. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26625. the selected row is off-screen, it'll scroll to make
  26626. sure that row is on-screen
  26627. @param deselectOthersFirst if true and there are multiple selections, these will
  26628. first be deselected before this item is selected
  26629. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26630. deselectAllRows, selectRangeOfRows
  26631. */
  26632. void selectRow (const int rowNumber,
  26633. bool dontScrollToShowThisRow = false,
  26634. bool deselectOthersFirst = true);
  26635. /** Selects a set of rows.
  26636. This will add these rows to the current selection, so you might need to
  26637. clear the current selection first with deselectAllRows()
  26638. @param firstRow the first row to select (inclusive)
  26639. @param lastRow the last row to select (inclusive)
  26640. */
  26641. void selectRangeOfRows (int firstRow,
  26642. int lastRow);
  26643. /** Deselects a row.
  26644. If it's not currently selected, this will do nothing.
  26645. @see selectRow, deselectAllRows
  26646. */
  26647. void deselectRow (const int rowNumber);
  26648. /** Deselects any currently selected rows.
  26649. @see deselectRow
  26650. */
  26651. void deselectAllRows();
  26652. /** Selects or deselects a row.
  26653. If the row's currently selected, this deselects it, and vice-versa.
  26654. */
  26655. void flipRowSelection (const int rowNumber);
  26656. /** Returns a sparse set indicating the rows that are currently selected.
  26657. @see setSelectedRows
  26658. */
  26659. const SparseSet<int> getSelectedRows() const;
  26660. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26661. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26662. method will be called. If it's false, no notification will be sent to the model.
  26663. @see getSelectedRows
  26664. */
  26665. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26666. const bool sendNotificationEventToModel = true);
  26667. /** Checks whether a row is selected.
  26668. */
  26669. bool isRowSelected (const int rowNumber) const;
  26670. /** Returns the number of rows that are currently selected.
  26671. @see getSelectedRow, isRowSelected, getLastRowSelected
  26672. */
  26673. int getNumSelectedRows() const;
  26674. /** Returns the row number of a selected row.
  26675. This will return the row number of the Nth selected row. The row numbers returned will
  26676. be sorted in order from low to high.
  26677. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26678. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26679. selected
  26680. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26681. */
  26682. int getSelectedRow (const int index = 0) const;
  26683. /** Returns the last row that the user selected.
  26684. This isn't the same as the highest row number that is currently selected - if the user
  26685. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26686. If nothing is selected, it will return -1.
  26687. */
  26688. int getLastRowSelected() const;
  26689. /** Multiply-selects rows based on the modifier keys.
  26690. If no modifier keys are down, this will select the given row and
  26691. deselect any others.
  26692. If the ctrl (or command on the Mac) key is down, it'll flip the
  26693. state of the selected row.
  26694. If the shift key is down, it'll select up to the given row from the
  26695. last row selected.
  26696. @see selectRow
  26697. */
  26698. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26699. const ModifierKeys& modifiers);
  26700. /** Scrolls the list to a particular position.
  26701. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26702. 1.0 scrolls to the bottom.
  26703. If the total number of rows all fit onto the screen at once, then this
  26704. method won't do anything.
  26705. @see getVerticalPosition
  26706. */
  26707. void setVerticalPosition (const double newProportion);
  26708. /** Returns the current vertical position as a proportion of the total.
  26709. This can be used in conjunction with setVerticalPosition() to save and restore
  26710. the list's position. It returns a value in the range 0 to 1.
  26711. @see setVerticalPosition
  26712. */
  26713. double getVerticalPosition() const;
  26714. /** Scrolls if necessary to make sure that a particular row is visible.
  26715. */
  26716. void scrollToEnsureRowIsOnscreen (const int row);
  26717. /** Returns a pointer to the scrollbar.
  26718. (Unlikely to be useful for most people).
  26719. */
  26720. ScrollBar* getVerticalScrollBar() const throw();
  26721. /** Returns a pointer to the scrollbar.
  26722. (Unlikely to be useful for most people).
  26723. */
  26724. ScrollBar* getHorizontalScrollBar() const throw();
  26725. /** Finds the row index that contains a given x,y position.
  26726. The position is relative to the ListBox's top-left.
  26727. If no row exists at this position, the method will return -1.
  26728. @see getComponentForRowNumber
  26729. */
  26730. int getRowContainingPosition (const int x, const int y) const throw();
  26731. /** Finds a row index that would be the most suitable place to insert a new
  26732. item for a given position.
  26733. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26734. because it lets you easily choose the best position to insert the item that
  26735. they drop, based on where they drop it.
  26736. If the position is out of range, this will return -1. If the position is
  26737. beyond the end of the list, it will return getNumRows() to indicate the end
  26738. of the list.
  26739. @see getComponentForRowNumber
  26740. */
  26741. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26742. /** Returns the position of one of the rows, relative to the top-left of
  26743. the listbox.
  26744. This may be off-screen, and the range of the row number that is passed-in is
  26745. not checked to see if it's a valid row.
  26746. */
  26747. const Rectangle getRowPosition (const int rowNumber,
  26748. const bool relativeToComponentTopLeft) const throw();
  26749. /** Finds the row component for a given row in the list.
  26750. The component returned will have been created using createRowComponent().
  26751. If the component for this row is off-screen or if the row is out-of-range,
  26752. this will return 0.
  26753. @see getRowContainingPosition
  26754. */
  26755. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26756. /** Returns the row number that the given component represents.
  26757. If the component isn't one of the list's rows, this will return -1.
  26758. */
  26759. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26760. /** Returns the width of a row (which may be less than the width of this component
  26761. if there's a scrollbar).
  26762. */
  26763. int getVisibleRowWidth() const throw();
  26764. /** Sets the height of each row in the list.
  26765. The default height is 22 pixels.
  26766. @see getRowHeight
  26767. */
  26768. void setRowHeight (const int newHeight);
  26769. /** Returns the height of a row in the list.
  26770. @see setRowHeight
  26771. */
  26772. int getRowHeight() const throw() { return rowHeight; }
  26773. /** Returns the number of rows actually visible.
  26774. This is the number of whole rows which will fit on-screen, so the value might
  26775. be more than the actual number of rows in the list.
  26776. */
  26777. int getNumRowsOnScreen() const throw();
  26778. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26779. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26780. methods.
  26781. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26782. */
  26783. enum ColourIds
  26784. {
  26785. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26786. Make this transparent if you don't want the background to be filled. */
  26787. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26788. Make this transparent to not have an outline. */
  26789. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26790. };
  26791. /** Sets the thickness of a border that will be drawn around the box.
  26792. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26793. @see outlineColourId
  26794. */
  26795. void setOutlineThickness (const int outlineThickness);
  26796. /** Returns the thickness of outline that will be drawn around the listbox.
  26797. @see setOutlineColour
  26798. */
  26799. int getOutlineThickness() const throw() { return outlineThickness; }
  26800. /** Sets a component that the list should use as a header.
  26801. This will position the given component at the top of the list, maintaining the
  26802. height of the component passed-in, but rescaling it horizontally to match the
  26803. width of the items in the listbox.
  26804. The component will be deleted when setHeaderComponent() is called with a
  26805. different component, or when the listbox is deleted.
  26806. */
  26807. void setHeaderComponent (Component* const newHeaderComponent);
  26808. /** Changes the width of the rows in the list.
  26809. This can be used to make the list's row components wider than the list itself - the
  26810. width of the rows will be either the width of the list or this value, whichever is
  26811. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26812. appear.
  26813. The default value for this is 0, which means that the rows will always
  26814. be the same width as the list.
  26815. */
  26816. void setMinimumContentWidth (const int newMinimumWidth);
  26817. /** Returns the space currently available for the row items, taking into account
  26818. borders, scrollbars, etc.
  26819. */
  26820. int getVisibleContentWidth() const throw();
  26821. /** Repaints one of the rows.
  26822. This is a lightweight alternative to calling updateContent, and just causes a
  26823. repaint of the row's area.
  26824. */
  26825. void repaintRow (const int rowNumber) throw();
  26826. /** This fairly obscure method creates an image that just shows the currently
  26827. selected row components.
  26828. It's a handy method for doing drag-and-drop, as it can be passed to the
  26829. DragAndDropContainer for use as the drag image.
  26830. Note that it will make the row components temporarily invisible, so if you're
  26831. using custom components this could affect them if they're sensitive to that
  26832. sort of thing.
  26833. @see Component::createComponentSnapshot
  26834. */
  26835. Image* createSnapshotOfSelectedRows();
  26836. /** Returns the viewport that this ListBox uses.
  26837. You may need to use this to change parameters such as whether scrollbars
  26838. are shown, etc.
  26839. */
  26840. Viewport* getViewport() const throw();
  26841. /** @internal */
  26842. bool keyPressed (const KeyPress& key);
  26843. /** @internal */
  26844. bool keyStateChanged();
  26845. /** @internal */
  26846. void paint (Graphics& g);
  26847. /** @internal */
  26848. void paintOverChildren (Graphics& g);
  26849. /** @internal */
  26850. void resized();
  26851. /** @internal */
  26852. void visibilityChanged();
  26853. /** @internal */
  26854. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26855. /** @internal */
  26856. void mouseMove (const MouseEvent&);
  26857. /** @internal */
  26858. void mouseExit (const MouseEvent&);
  26859. /** @internal */
  26860. void mouseUp (const MouseEvent&);
  26861. /** @internal */
  26862. void colourChanged();
  26863. juce_UseDebuggingNewOperator
  26864. private:
  26865. friend class ListViewport;
  26866. friend class TableListBox;
  26867. ListBoxModel* model;
  26868. ListViewport* viewport;
  26869. Component* headerComponent;
  26870. int totalItems, rowHeight, minimumRowWidth;
  26871. int outlineThickness;
  26872. int lastMouseX, lastMouseY, lastRowSelected;
  26873. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26874. SparseSet <int> selected;
  26875. void selectRowInternal (const int rowNumber,
  26876. bool dontScrollToShowThisRow,
  26877. bool deselectOthersFirst,
  26878. bool isMouseClick);
  26879. ListBox (const ListBox&);
  26880. const ListBox& operator= (const ListBox&);
  26881. };
  26882. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26883. /********* End of inlined file: juce_ListBox.h *********/
  26884. /********* Start of inlined file: juce_TextButton.h *********/
  26885. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26886. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26887. /**
  26888. A button that uses the standard lozenge-shaped background with a line of
  26889. text on it.
  26890. @see Button, DrawableButton
  26891. */
  26892. class JUCE_API TextButton : public Button
  26893. {
  26894. public:
  26895. /** Creates a TextButton.
  26896. @param buttonName the text to put in the button (the component's name is also
  26897. initially set to this string, but these can be changed later
  26898. using the setName() and setButtonText() methods)
  26899. @param toolTip an optional string to use as a toolip
  26900. @see Button
  26901. */
  26902. TextButton (const String& buttonName,
  26903. const String& toolTip = String::empty);
  26904. /** Destructor. */
  26905. ~TextButton();
  26906. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26907. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26908. methods.
  26909. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26910. */
  26911. enum ColourIds
  26912. {
  26913. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26914. 'off'). The look-and-feel class might re-interpret this to add
  26915. effects, etc. */
  26916. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26917. 'on'). The look-and-feel class might re-interpret this to add
  26918. effects, etc. */
  26919. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26920. };
  26921. /** Resizes the button to fit neatly around its current text.
  26922. If newHeight is >= 0, the button's height will be changed to this
  26923. value. If it's less than zero, its height will be unaffected.
  26924. */
  26925. void changeWidthToFitText (const int newHeight = -1);
  26926. /** This can be overridden to use different fonts than the default one.
  26927. Note that you'll need to set the font's size appropriately, too.
  26928. */
  26929. virtual const Font getFont();
  26930. juce_UseDebuggingNewOperator
  26931. protected:
  26932. /** @internal */
  26933. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26934. /** @internal */
  26935. void colourChanged();
  26936. private:
  26937. TextButton (const TextButton&);
  26938. const TextButton& operator= (const TextButton&);
  26939. };
  26940. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26941. /********* End of inlined file: juce_TextButton.h *********/
  26942. /**
  26943. A component displaying a list of plugins, with options to scan for them,
  26944. add, remove and sort them.
  26945. */
  26946. class JUCE_API PluginListComponent : public Component,
  26947. public ListBoxModel,
  26948. public ChangeListener,
  26949. public ButtonListener,
  26950. public Timer
  26951. {
  26952. public:
  26953. /**
  26954. Creates the list component.
  26955. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26956. The properties file, if supplied, is used to store the user's last search paths.
  26957. */
  26958. PluginListComponent (KnownPluginList& listToRepresent,
  26959. const File& deadMansPedalFile,
  26960. PropertiesFile* const propertiesToUse);
  26961. /** Destructor. */
  26962. ~PluginListComponent();
  26963. /** @internal */
  26964. void resized();
  26965. /** @internal */
  26966. bool isInterestedInFileDrag (const StringArray& files);
  26967. /** @internal */
  26968. void filesDropped (const StringArray& files, int, int);
  26969. /** @internal */
  26970. int getNumRows();
  26971. /** @internal */
  26972. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26973. /** @internal */
  26974. void deleteKeyPressed (int lastRowSelected);
  26975. /** @internal */
  26976. void buttonClicked (Button* b);
  26977. /** @internal */
  26978. void changeListenerCallback (void*);
  26979. /** @internal */
  26980. void timerCallback();
  26981. juce_UseDebuggingNewOperator
  26982. private:
  26983. KnownPluginList& list;
  26984. File deadMansPedalFile;
  26985. ListBox* listBox;
  26986. TextButton* optionsButton;
  26987. PropertiesFile* propertiesToUse;
  26988. int typeToScan;
  26989. void scanFor (AudioPluginFormat* format);
  26990. PluginListComponent (const PluginListComponent&);
  26991. const PluginListComponent& operator= (const PluginListComponent&);
  26992. };
  26993. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26994. /********* End of inlined file: juce_PluginListComponent.h *********/
  26995. #endif
  26996. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26997. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  26998. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26999. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27000. /********* Start of inlined file: juce_AudioFormat.h *********/
  27001. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27002. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  27003. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  27004. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27005. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27006. /**
  27007. Writes samples to an audio file stream.
  27008. A subclass that writes a specific type of audio format will be created by
  27009. an AudioFormat object.
  27010. After creating one of these with the AudioFormat::createWriterFor() method
  27011. you can call its write() method to store the samples, and then delete it.
  27012. @see AudioFormat, AudioFormatReader
  27013. */
  27014. class JUCE_API AudioFormatWriter
  27015. {
  27016. protected:
  27017. /** Creates an AudioFormatWriter object.
  27018. @param destStream the stream to write to - this will be deleted
  27019. by this object when it is no longer needed
  27020. @param formatName the description that will be returned by the getFormatName()
  27021. method
  27022. @param sampleRate the sample rate to use - the base class just stores
  27023. this value, it doesn't do anything with it
  27024. @param numberOfChannels the number of channels to write - the base class just stores
  27025. this value, it doesn't do anything with it
  27026. @param bitsPerSample the bit depth of the stream - the base class just stores
  27027. this value, it doesn't do anything with it
  27028. */
  27029. AudioFormatWriter (OutputStream* const destStream,
  27030. const String& formatName,
  27031. const double sampleRate,
  27032. const unsigned int numberOfChannels,
  27033. const unsigned int bitsPerSample);
  27034. public:
  27035. /** Destructor. */
  27036. virtual ~AudioFormatWriter();
  27037. /** Returns a description of what type of format this is.
  27038. E.g. "AIFF file"
  27039. */
  27040. const String getFormatName() const throw() { return formatName; }
  27041. /** Writes a set of samples to the audio stream.
  27042. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27043. can use AudioSampleBuffer::writeToAudioWriter().
  27044. @param samplesToWrite an array of arrays containing the sample data for
  27045. each channel to write. This is a zero-terminated
  27046. array of arrays, and can contain a different number
  27047. of channels than the actual stream uses, and the
  27048. writer should do its best to cope with this.
  27049. If the format is fixed-point, each channel will be formatted
  27050. as an array of signed integers using the full 32-bit
  27051. range -0x80000000 to 0x7fffffff, regardless of the source's
  27052. bit-depth. If it is a floating-point format, you should treat
  27053. the arrays as arrays of floats, and just cast it to an (int**)
  27054. to pass it into the method.
  27055. @param numSamples the number of samples to write
  27056. */
  27057. virtual bool write (const int** samplesToWrite,
  27058. int numSamples) = 0;
  27059. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27060. the output.
  27061. This will take care of any floating-point conversion that's required to convert
  27062. between the two formats. It won't deal with sample-rate conversion, though.
  27063. If numSamplesToRead < 0, it will write the entire length of the reader.
  27064. @returns false if it can't read or write properly during the operation
  27065. */
  27066. bool writeFromAudioReader (AudioFormatReader& reader,
  27067. int64 startSample,
  27068. int64 numSamplesToRead);
  27069. /** Reads some samples from an AudioSource, and writes these to the output.
  27070. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27071. @param source the source to read from
  27072. @param numSamplesToRead total number of samples to read and write
  27073. @param samplesPerBlock the maximum number of samples to fetch from the source
  27074. @returns false if it can't read or write properly during the operation
  27075. */
  27076. bool writeFromAudioSource (AudioSource& source,
  27077. int numSamplesToRead,
  27078. const int samplesPerBlock = 2048);
  27079. /** Returns the sample rate being used. */
  27080. double getSampleRate() const throw() { return sampleRate; }
  27081. /** Returns the number of channels being written. */
  27082. int getNumChannels() const throw() { return numChannels; }
  27083. /** Returns the bit-depth of the data being written. */
  27084. int getBitsPerSample() const throw() { return bitsPerSample; }
  27085. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27086. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27087. juce_UseDebuggingNewOperator
  27088. protected:
  27089. /** The sample rate of the stream. */
  27090. double sampleRate;
  27091. /** The number of channels being written to the stream. */
  27092. unsigned int numChannels;
  27093. /** The bit depth of the file. */
  27094. unsigned int bitsPerSample;
  27095. /** True if it's a floating-point format, false if it's fixed-point. */
  27096. bool usesFloatingPointData;
  27097. /** The output stream for Use by subclasses. */
  27098. OutputStream* output;
  27099. private:
  27100. String formatName;
  27101. };
  27102. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27103. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  27104. /**
  27105. Subclasses of AudioFormat are used to read and write different audio
  27106. file formats.
  27107. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27108. */
  27109. class JUCE_API AudioFormat
  27110. {
  27111. public:
  27112. /** Destructor. */
  27113. virtual ~AudioFormat();
  27114. /** Returns the name of this format.
  27115. e.g. "WAV file" or "AIFF file"
  27116. */
  27117. const String& getFormatName() const;
  27118. /** Returns all the file extensions that might apply to a file of this format.
  27119. The first item will be the one that's preferred when creating a new file.
  27120. So for a wav file this might just return ".wav"; for an AIFF file it might
  27121. return two items, ".aif" and ".aiff"
  27122. */
  27123. const StringArray& getFileExtensions() const;
  27124. /** Returns true if this the given file can be read by this format.
  27125. Subclasses shouldn't do too much work here, just check the extension or
  27126. file type. The base class implementation just checks the file's extension
  27127. against one of the ones that was registered in the constructor.
  27128. */
  27129. virtual bool canHandleFile (const File& fileToTest);
  27130. /** Returns a set of sample rates that the format can read and write. */
  27131. virtual const Array <int> getPossibleSampleRates() = 0;
  27132. /** Returns a set of bit depths that the format can read and write. */
  27133. virtual const Array <int> getPossibleBitDepths() = 0;
  27134. /** Returns true if the format can do 2-channel audio. */
  27135. virtual bool canDoStereo() = 0;
  27136. /** Returns true if the format can do 1-channel audio. */
  27137. virtual bool canDoMono() = 0;
  27138. /** Returns true if the format uses compressed data. */
  27139. virtual bool isCompressed();
  27140. /** Returns a list of different qualities that can be used when writing.
  27141. Non-compressed formats will just return an empty array, but for something
  27142. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27143. When calling createWriterFor(), an index from this array is passed in to
  27144. tell the format which option is required.
  27145. */
  27146. virtual const StringArray getQualityOptions();
  27147. /** Tries to create an object that can read from a stream containing audio
  27148. data in this format.
  27149. The reader object that is returned can be used to read from the stream, and
  27150. should then be deleted by the caller.
  27151. @param sourceStream the stream to read from - the AudioFormatReader object
  27152. that is returned will delete this stream when it no longer
  27153. needs it.
  27154. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27155. should delete the stream object that was passed-in. (If a valid
  27156. reader is returned, it will always be in charge of deleting the
  27157. stream, so this parameter is ignored)
  27158. @see AudioFormatReader
  27159. */
  27160. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27161. const bool deleteStreamIfOpeningFails) = 0;
  27162. /** Tries to create an object that can write to a stream with this audio format.
  27163. The writer object that is returned can be used to write to the stream, and
  27164. should then be deleted by the caller.
  27165. If the stream can't be created for some reason (e.g. the parameters passed in
  27166. here aren't suitable), this will return 0.
  27167. @param streamToWriteTo the stream that the data will go to - this will be
  27168. deleted by the AudioFormatWriter object when it's no longer
  27169. needed. If no AudioFormatWriter can be created by this method,
  27170. the stream will NOT be deleted, so that the caller can re-use it
  27171. to try to open a different format, etc
  27172. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27173. returned by getPossibleSampleRates()
  27174. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27175. the choice will depend on the results of canDoMono() and
  27176. canDoStereo()
  27177. @param bitsPerSample the bits per sample to use - this must be one of the values
  27178. returned by getPossibleBitDepths()
  27179. @param metadataValues a set of metadata values that the writer should try to write
  27180. to the stream. Exactly what these are depends on the format,
  27181. and the subclass doesn't actually have to do anything with
  27182. them if it doesn't want to. Have a look at the specific format
  27183. implementation classes to see possible values that can be
  27184. used
  27185. @param qualityOptionIndex the index of one of compression qualities returned by the
  27186. getQualityOptions() method. If there aren't any quality options
  27187. for this format, just pass 0 in this parameter, as it'll be
  27188. ignored
  27189. @see AudioFormatWriter
  27190. */
  27191. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27192. double sampleRateToUse,
  27193. unsigned int numberOfChannels,
  27194. int bitsPerSample,
  27195. const StringPairArray& metadataValues,
  27196. int qualityOptionIndex) = 0;
  27197. protected:
  27198. /** Creates an AudioFormat object.
  27199. @param formatName this sets the value that will be returned by getFormatName()
  27200. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27201. be returned by getFileExtension()
  27202. */
  27203. AudioFormat (const String& formatName,
  27204. const tchar** const fileExtensions);
  27205. private:
  27206. String formatName;
  27207. StringArray fileExtensions;
  27208. };
  27209. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27210. /********* End of inlined file: juce_AudioFormat.h *********/
  27211. /**
  27212. Reads and Writes AIFF format audio files.
  27213. @see AudioFormat
  27214. */
  27215. class JUCE_API AiffAudioFormat : public AudioFormat
  27216. {
  27217. public:
  27218. /** Creates an format object. */
  27219. AiffAudioFormat();
  27220. /** Destructor. */
  27221. ~AiffAudioFormat();
  27222. const Array <int> getPossibleSampleRates();
  27223. const Array <int> getPossibleBitDepths();
  27224. bool canDoStereo();
  27225. bool canDoMono();
  27226. #if JUCE_MAC
  27227. bool canHandleFile (const File& fileToTest);
  27228. #endif
  27229. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27230. const bool deleteStreamIfOpeningFails);
  27231. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27232. double sampleRateToUse,
  27233. unsigned int numberOfChannels,
  27234. int bitsPerSample,
  27235. const StringPairArray& metadataValues,
  27236. int qualityOptionIndex);
  27237. juce_UseDebuggingNewOperator
  27238. };
  27239. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27240. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  27241. #endif
  27242. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27243. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  27244. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27245. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27246. /**
  27247. */
  27248. class AudioCDBurner
  27249. {
  27250. public:
  27251. /** Returns a list of available optical drives.
  27252. Use openDevice() to open one of the items from this list.
  27253. */
  27254. static const StringArray findAvailableDevices();
  27255. /** Tries to open one of the optical drives.
  27256. The deviceIndex is an index into the array returned by findAvailableDevices().
  27257. */
  27258. static AudioCDBurner* openDevice (const int deviceIndex);
  27259. /** Destructor. */
  27260. ~AudioCDBurner();
  27261. /** Returns true if there's a writable disk in the drive.
  27262. */
  27263. bool isDiskPresent() const;
  27264. /** Returns the number of free blocks on the disk.
  27265. There are 75 blocks per second, at 44100Hz.
  27266. */
  27267. int getNumAvailableAudioBlocks() const;
  27268. /** Adds a track to be written.
  27269. The source passed-in here will be kept by this object, and it will
  27270. be used and deleted at some point in the future, either during the
  27271. burn() method or when this AudioCDBurner object is deleted. Your caller
  27272. method shouldn't keep a reference to it or use it again after passing
  27273. it in here.
  27274. */
  27275. bool addAudioTrack (AudioSource* source, int numSamples);
  27276. /**
  27277. Return true to cancel the current burn operation
  27278. */
  27279. class BurnProgressListener
  27280. {
  27281. public:
  27282. BurnProgressListener() throw() {}
  27283. virtual ~BurnProgressListener() {}
  27284. /** Called at intervals to report on the progress of the AudioCDBurner.
  27285. To cancel the burn, return true from this.
  27286. */
  27287. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27288. };
  27289. const String burn (BurnProgressListener* listener,
  27290. const bool ejectDiscAfterwards,
  27291. const bool peformFakeBurnForTesting);
  27292. juce_UseDebuggingNewOperator
  27293. private:
  27294. AudioCDBurner (const int deviceIndex);
  27295. void* internal;
  27296. };
  27297. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27298. /********* End of inlined file: juce_AudioCDBurner.h *********/
  27299. #endif
  27300. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27301. /********* Start of inlined file: juce_AudioCDReader.h *********/
  27302. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27303. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27304. #if JUCE_MAC
  27305. #endif
  27306. /**
  27307. A type of AudioFormatReader that reads from an audio CD.
  27308. One of these can be used to read a CD as if it's one big audio stream. Use the
  27309. getPositionOfTrackStart() method to find where the individual tracks are
  27310. within the stream.
  27311. @see AudioFormatReader
  27312. */
  27313. class JUCE_API AudioCDReader : public AudioFormatReader
  27314. {
  27315. public:
  27316. /** Returns a list of names of Audio CDs currently available for reading.
  27317. If there's a CD drive but no CD in it, this might return an empty list, or
  27318. possibly a device that can be opened but which has no tracks, depending
  27319. on the platform.
  27320. @see createReaderForCD
  27321. */
  27322. static const StringArray getAvailableCDNames();
  27323. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27324. @param index the index of one of the available CDs - use getAvailableCDNames()
  27325. to find out how many there are.
  27326. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27327. caller will be responsible for deleting the object returned.
  27328. */
  27329. static AudioCDReader* createReaderForCD (const int index);
  27330. /** Destructor. */
  27331. ~AudioCDReader();
  27332. /** Implementation of the AudioFormatReader method. */
  27333. bool read (int** destSamples,
  27334. int64 startSampleInFile,
  27335. int numSamples);
  27336. /** Checks whether the CD has been removed from the drive.
  27337. */
  27338. bool isCDStillPresent() const;
  27339. /** Returns the total number of tracks (audio + data).
  27340. */
  27341. int getNumTracks() const;
  27342. /** Finds the sample offset of the start of a track.
  27343. @param trackNum the track number, where 0 is the first track.
  27344. */
  27345. int getPositionOfTrackStart (int trackNum) const;
  27346. /** Returns true if a given track is an audio track.
  27347. @param trackNum the track number, where 0 is the first track.
  27348. */
  27349. bool isTrackAudio (int trackNum) const;
  27350. /** Refreshes the object's table of contents.
  27351. If the disc has been ejected and a different one put in since this
  27352. object was created, this will cause it to update its idea of how many tracks
  27353. there are, etc.
  27354. */
  27355. void refreshTrackLengths();
  27356. /** Enables scanning for indexes within tracks.
  27357. @see getLastIndex
  27358. */
  27359. void enableIndexScanning (bool enabled);
  27360. /** Returns the index number found during the last read() call.
  27361. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27362. Then when the read() method is called, if it comes across an index within that
  27363. block, the index number is stored and returned by this method.
  27364. Some devices might not support indexes, of course.
  27365. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27366. @see enableIndexScanning
  27367. */
  27368. int getLastIndex() const;
  27369. /** Scans a track to find the position of any indexes within it.
  27370. @param trackNumber the track to look in, where 0 is the first track on the disc
  27371. @returns an array of sample positions of any index points found (not including
  27372. the index that marks the start of the track)
  27373. */
  27374. const Array <int> findIndexesInTrack (const int trackNumber);
  27375. /** Returns the CDDB id number for the CD.
  27376. It's not a great way of identifying a disc, but it's traditional.
  27377. */
  27378. int getCDDBId();
  27379. /** Tries to eject the disk.
  27380. Of course this might not be possible, if some other process is using it.
  27381. */
  27382. void ejectDisk();
  27383. juce_UseDebuggingNewOperator
  27384. private:
  27385. #if JUCE_MAC
  27386. File volumeDir;
  27387. OwnedArray<File> tracks;
  27388. Array <int> trackStartSamples;
  27389. int currentReaderTrack;
  27390. AudioFormatReader* reader;
  27391. AudioCDReader (const File& volume);
  27392. public:
  27393. static int compareElements (const File* const, const File* const) throw();
  27394. private:
  27395. #elif JUCE_WIN32
  27396. int numTracks;
  27397. int trackStarts[100];
  27398. bool audioTracks [100];
  27399. void* handle;
  27400. bool indexingEnabled;
  27401. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27402. MemoryBlock buffer;
  27403. AudioCDReader (void* handle);
  27404. int getIndexAt (int samplePos);
  27405. #elif JUCE_LINUX
  27406. AudioCDReader();
  27407. #endif
  27408. AudioCDReader (const AudioCDReader&);
  27409. const AudioCDReader& operator= (const AudioCDReader&);
  27410. };
  27411. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27412. /********* End of inlined file: juce_AudioCDReader.h *********/
  27413. #endif
  27414. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27415. #endif
  27416. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27417. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27418. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27419. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27420. /**
  27421. A class for keeping a list of available audio formats, and for deciding which
  27422. one to use to open a given file.
  27423. You can either use this class as a singleton object, or create instances of it
  27424. yourself. Once created, use its registerFormat() method to tell it which
  27425. formats it should use.
  27426. @see AudioFormat
  27427. */
  27428. class JUCE_API AudioFormatManager
  27429. {
  27430. public:
  27431. /** Creates an empty format manager.
  27432. Before it'll be any use, you'll need to call registerFormat() with all the
  27433. formats you want it to be able to recognise.
  27434. */
  27435. AudioFormatManager();
  27436. /** Destructor. */
  27437. ~AudioFormatManager();
  27438. juce_DeclareSingleton (AudioFormatManager, false);
  27439. /** Adds a format to the manager's list of available file types.
  27440. The object passed-in will be deleted by this object, so don't keep a pointer
  27441. to it!
  27442. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27443. return this one when called.
  27444. */
  27445. void registerFormat (AudioFormat* newFormat,
  27446. const bool makeThisTheDefaultFormat);
  27447. /** Handy method to make it easy to register the formats that come with Juce.
  27448. Currently, this will add WAV and AIFF to the list.
  27449. */
  27450. void registerBasicFormats();
  27451. /** Clears the list of known formats. */
  27452. void clearFormats();
  27453. /** Returns the number of currently registered file formats. */
  27454. int getNumKnownFormats() const;
  27455. /** Returns one of the registered file formats. */
  27456. AudioFormat* getKnownFormat (const int index) const;
  27457. /** Looks for which of the known formats is listed as being for a given file
  27458. extension.
  27459. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27460. */
  27461. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27462. /** Returns the format which has been set as the default one.
  27463. You can set a format as being the default when it is registered. It's useful
  27464. when you want to write to a file, because the best format may change between
  27465. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27466. If none has been set as the default, this method will just return the first
  27467. one in the list.
  27468. */
  27469. AudioFormat* getDefaultFormat() const;
  27470. /** Returns a set of wildcards for file-matching that contains the extensions for
  27471. all known formats.
  27472. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27473. */
  27474. const String getWildcardForAllFormats() const;
  27475. /** Searches through the known formats to try to create a suitable reader for
  27476. this file.
  27477. If none of the registered formats can open the file, it'll return 0. If it
  27478. returns a reader, it's the caller's responsibility to delete the reader.
  27479. */
  27480. AudioFormatReader* createReaderFor (const File& audioFile);
  27481. /** Searches through the known formats to try to create a suitable reader for
  27482. this stream.
  27483. The stream object that is passed-in will be deleted by this method or by the
  27484. reader that is returned, so the caller should not keep any references to it.
  27485. The stream that is passed-in must be capable of being repositioned so
  27486. that all the formats can have a go at opening it.
  27487. If none of the registered formats can open the stream, it'll return 0. If it
  27488. returns a reader, it's the caller's responsibility to delete the reader.
  27489. */
  27490. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27491. juce_UseDebuggingNewOperator
  27492. private:
  27493. VoidArray knownFormats;
  27494. int defaultFormatIndex;
  27495. };
  27496. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27497. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27498. #endif
  27499. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27500. #endif
  27501. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27502. #endif
  27503. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27504. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27505. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27506. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27507. /**
  27508. This class is used to wrap an AudioFormatReader and only read from a
  27509. subsection of the file.
  27510. So if you have a reader which can read a 1000 sample file, you could wrap it
  27511. in one of these to only access, e.g. samples 100 to 200, and any samples
  27512. outside that will come back as 0. Accessing sample 0 from this reader will
  27513. actually read the first sample from the other's subsection, which might
  27514. be at a non-zero position.
  27515. @see AudioFormatReader
  27516. */
  27517. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27518. {
  27519. public:
  27520. /** Creates a AudioSubsectionReader for a given data source.
  27521. @param sourceReader the source reader from which we'll be taking data
  27522. @param subsectionStartSample the sample within the source reader which will be
  27523. mapped onto sample 0 for this reader.
  27524. @param subsectionLength the number of samples from the source that will
  27525. make up the subsection. If this reader is asked for
  27526. any samples beyond this region, it will return zero.
  27527. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27528. this object is deleted.
  27529. */
  27530. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27531. const int64 subsectionStartSample,
  27532. const int64 subsectionLength,
  27533. const bool deleteSourceWhenDeleted);
  27534. /** Destructor. */
  27535. ~AudioSubsectionReader();
  27536. bool read (int** destSamples,
  27537. int64 startSample,
  27538. int numSamples);
  27539. void readMaxLevels (int64 startSample,
  27540. int64 numSamples,
  27541. float& lowestLeft,
  27542. float& highestLeft,
  27543. float& lowestRight,
  27544. float& highestRight);
  27545. juce_UseDebuggingNewOperator
  27546. private:
  27547. AudioFormatReader* const source;
  27548. int64 startSample, length;
  27549. const bool deleteSourceWhenDeleted;
  27550. AudioSubsectionReader (const AudioSubsectionReader&);
  27551. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27552. };
  27553. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27554. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27555. #endif
  27556. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27557. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27558. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27559. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27560. class AudioThumbnailCache;
  27561. /**
  27562. Makes it easy to quickly draw scaled views of the waveform shape of an
  27563. audio file.
  27564. To use this class, just create an AudioThumbNail class for the file you want
  27565. to draw, call setSource to tell it which file or resource to use, then call
  27566. drawChannel() to draw it.
  27567. The class will asynchronously scan the wavefile to create its scaled-down view,
  27568. so you should make your UI repaint itself as this data comes in. To do this, the
  27569. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27570. listeners should repaint themselves.
  27571. The thumbnail stores an internal low-res version of the wave data, and this can
  27572. be loaded and saved to avoid having to scan the file again.
  27573. @see AudioThumbnailCache
  27574. */
  27575. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27576. public TimeSliceClient,
  27577. private Timer
  27578. {
  27579. public:
  27580. /** Creates an audio thumbnail.
  27581. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27582. of the audio data, this is the scale at which it should be done
  27583. @param formatManagerToUse the audio format manager that is used to open the file
  27584. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27585. thread and storage that is used to by the thumbnail, and the cache
  27586. object can be shared between multiple thumbnails
  27587. */
  27588. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27589. AudioFormatManager& formatManagerToUse,
  27590. AudioThumbnailCache& cacheToUse);
  27591. /** Destructor. */
  27592. ~AudioThumbnail();
  27593. /** Specifies the file or stream that contains the audio file.
  27594. For a file, just call
  27595. @code
  27596. setSource (new FileInputSource (file))
  27597. @endcode
  27598. You can pass a zero in here to clear the thumbnail.
  27599. The source that is passed in will be deleted by this object when it is no
  27600. longer needed
  27601. */
  27602. void setSource (InputSource* const newSource);
  27603. /** Reloads the low res thumbnail data from an input stream.
  27604. The thumb will automatically attempt to reload itself from its
  27605. AudioThumbnailCache.
  27606. */
  27607. void loadFrom (InputStream& input);
  27608. /** Saves the low res thumbnail data to an output stream.
  27609. The thumb will automatically attempt to save itself to its
  27610. AudioThumbnailCache after it finishes scanning the wave file.
  27611. */
  27612. void saveTo (OutputStream& output) const;
  27613. /** Returns the number of channels in the file.
  27614. */
  27615. int getNumChannels() const throw();
  27616. /** Returns the length of the audio file.
  27617. */
  27618. double getTotalLength() const throw();
  27619. /** Renders the waveform shape for a channel.
  27620. The waveform will be drawn within the specified rectangle, where startTime
  27621. and endTime specify the times within the audio file that should be positioned
  27622. at the left and right edges of the rectangle.
  27623. The waveform will be scaled vertically so that a full-volume sample will fill
  27624. the rectangle vertically, but you can also specify an extra vertical scale factor
  27625. with the verticalZoomFactor parameter.
  27626. */
  27627. void drawChannel (Graphics& g,
  27628. int x, int y, int w, int h,
  27629. double startTime,
  27630. double endTime,
  27631. int channelNum,
  27632. const float verticalZoomFactor);
  27633. /** Returns true if the low res preview is fully generated.
  27634. */
  27635. bool isFullyLoaded() const throw();
  27636. /** @internal */
  27637. bool useTimeSlice();
  27638. /** @internal */
  27639. void timerCallback();
  27640. juce_UseDebuggingNewOperator
  27641. private:
  27642. AudioFormatManager& formatManagerToUse;
  27643. AudioThumbnailCache& cache;
  27644. InputSource* source;
  27645. CriticalSection readerLock;
  27646. AudioFormatReader* reader;
  27647. MemoryBlock data, cachedLevels;
  27648. int orginalSamplesPerThumbnailSample;
  27649. int numChannelsCached, numSamplesCached;
  27650. double cachedStart, cachedTimePerPixel;
  27651. bool cacheNeedsRefilling;
  27652. void clear();
  27653. AudioFormatReader* createReader() const;
  27654. void generateSection (AudioFormatReader& reader,
  27655. int64 startSample,
  27656. int numSamples);
  27657. char* getChannelData (int channel) const;
  27658. void refillCache (const int numSamples,
  27659. double startTime,
  27660. const double timePerPixel);
  27661. friend class AudioThumbnailCache;
  27662. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27663. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27664. // returns true if more needs to be read
  27665. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27666. };
  27667. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27668. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27669. #endif
  27670. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27671. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27672. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27673. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27674. struct ThumbnailCacheEntry;
  27675. /**
  27676. An instance of this class is used to manage multiple AudioThumbnail objects.
  27677. The cache runs a single background thread that is shared by all the thumbnails
  27678. that need it, and it maintains a set of low-res previews in memory, to avoid
  27679. having to re-scan audio files too often.
  27680. @see AudioThumbnail
  27681. */
  27682. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27683. {
  27684. public:
  27685. /** Creates a cache object.
  27686. The maxNumThumbsToStore parameter lets you specify how many previews should
  27687. be kept in memory at once.
  27688. */
  27689. AudioThumbnailCache (const int maxNumThumbsToStore);
  27690. /** Destructor. */
  27691. ~AudioThumbnailCache();
  27692. /** Clears out any stored thumbnails.
  27693. */
  27694. void clear();
  27695. /** Reloads the specified thumb if this cache contains the appropriate stored
  27696. data.
  27697. This is called automatically by the AudioThumbnail class, so you shouldn't
  27698. normally need to call it directly.
  27699. */
  27700. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27701. /** Stores the cachable data from the specified thumb in this cache.
  27702. This is called automatically by the AudioThumbnail class, so you shouldn't
  27703. normally need to call it directly.
  27704. */
  27705. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27706. juce_UseDebuggingNewOperator
  27707. private:
  27708. OwnedArray <ThumbnailCacheEntry> thumbs;
  27709. int maxNumThumbsToStore;
  27710. friend class AudioThumbnail;
  27711. void addThumbnail (AudioThumbnail* const thumb);
  27712. void removeThumbnail (AudioThumbnail* const thumb);
  27713. };
  27714. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27715. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27716. #endif
  27717. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27718. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27719. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27720. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27721. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27722. /**
  27723. Reads and writes the lossless-compression FLAC audio format.
  27724. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27725. and make sure your include search path and library search path are set up to find
  27726. the FLAC header files and static libraries.
  27727. @see AudioFormat
  27728. */
  27729. class JUCE_API FlacAudioFormat : public AudioFormat
  27730. {
  27731. public:
  27732. FlacAudioFormat();
  27733. ~FlacAudioFormat();
  27734. const Array <int> getPossibleSampleRates();
  27735. const Array <int> getPossibleBitDepths();
  27736. bool canDoStereo();
  27737. bool canDoMono();
  27738. bool isCompressed();
  27739. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27740. const bool deleteStreamIfOpeningFails);
  27741. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27742. double sampleRateToUse,
  27743. unsigned int numberOfChannels,
  27744. int bitsPerSample,
  27745. const StringPairArray& metadataValues,
  27746. int qualityOptionIndex);
  27747. juce_UseDebuggingNewOperator
  27748. };
  27749. #endif
  27750. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27751. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27752. #endif
  27753. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27754. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27755. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27756. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27757. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27758. /**
  27759. Reads and writes the Ogg-Vorbis audio format.
  27760. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27761. and make sure your include search path and library search path are set up to find
  27762. the Vorbis and Ogg header files and static libraries.
  27763. @see AudioFormat,
  27764. */
  27765. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27766. {
  27767. public:
  27768. OggVorbisAudioFormat();
  27769. ~OggVorbisAudioFormat();
  27770. const Array <int> getPossibleSampleRates();
  27771. const Array <int> getPossibleBitDepths();
  27772. bool canDoStereo();
  27773. bool canDoMono();
  27774. bool isCompressed();
  27775. const StringArray getQualityOptions();
  27776. /** Tries to estimate the quality level of an ogg file based on its size.
  27777. If it can't read the file for some reason, this will just return 1 (medium quality),
  27778. otherwise it will return the approximate quality setting that would have been used
  27779. to create the file.
  27780. @see getQualityOptions
  27781. */
  27782. int estimateOggFileQuality (const File& source);
  27783. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27784. const bool deleteStreamIfOpeningFails);
  27785. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27786. double sampleRateToUse,
  27787. unsigned int numberOfChannels,
  27788. int bitsPerSample,
  27789. const StringPairArray& metadataValues,
  27790. int qualityOptionIndex);
  27791. juce_UseDebuggingNewOperator
  27792. };
  27793. #endif
  27794. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27795. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27796. #endif
  27797. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27798. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27799. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27800. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27801. #if JUCE_QUICKTIME
  27802. /**
  27803. Uses QuickTime to read the audio track a movie or media file.
  27804. As well as QuickTime movies, this should also manage to open other audio
  27805. files that quicktime can understand, like mp3, m4a, etc.
  27806. @see AudioFormat
  27807. */
  27808. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27809. {
  27810. public:
  27811. /** Creates a format object. */
  27812. QuickTimeAudioFormat();
  27813. /** Destructor. */
  27814. ~QuickTimeAudioFormat();
  27815. const Array <int> getPossibleSampleRates();
  27816. const Array <int> getPossibleBitDepths();
  27817. bool canDoStereo();
  27818. bool canDoMono();
  27819. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27820. const bool deleteStreamIfOpeningFails);
  27821. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27822. double sampleRateToUse,
  27823. unsigned int numberOfChannels,
  27824. int bitsPerSample,
  27825. const StringPairArray& metadataValues,
  27826. int qualityOptionIndex);
  27827. juce_UseDebuggingNewOperator
  27828. };
  27829. #endif
  27830. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27831. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27832. #endif
  27833. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27834. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27835. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27836. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27837. /**
  27838. Reads and Writes WAV format audio files.
  27839. @see AudioFormat
  27840. */
  27841. class JUCE_API WavAudioFormat : public AudioFormat
  27842. {
  27843. public:
  27844. /** Creates a format object. */
  27845. WavAudioFormat();
  27846. /** Destructor. */
  27847. ~WavAudioFormat();
  27848. /** Metadata property name used by wav readers and writers for adding
  27849. a BWAV chunk to the file.
  27850. @see AudioFormatReader::metadataValues, createWriterFor
  27851. */
  27852. static const tchar* const bwavDescription;
  27853. /** Metadata property name used by wav readers and writers for adding
  27854. a BWAV chunk to the file.
  27855. @see AudioFormatReader::metadataValues, createWriterFor
  27856. */
  27857. static const tchar* const bwavOriginator;
  27858. /** Metadata property name used by wav readers and writers for adding
  27859. a BWAV chunk to the file.
  27860. @see AudioFormatReader::metadataValues, createWriterFor
  27861. */
  27862. static const tchar* const bwavOriginatorRef;
  27863. /** Metadata property name used by wav readers and writers for adding
  27864. a BWAV chunk to the file.
  27865. Date format is: yyyy-mm-dd
  27866. @see AudioFormatReader::metadataValues, createWriterFor
  27867. */
  27868. static const tchar* const bwavOriginationDate;
  27869. /** Metadata property name used by wav readers and writers for adding
  27870. a BWAV chunk to the file.
  27871. Time format is: hh-mm-ss
  27872. @see AudioFormatReader::metadataValues, createWriterFor
  27873. */
  27874. static const tchar* const bwavOriginationTime;
  27875. /** Metadata property name used by wav readers and writers for adding
  27876. a BWAV chunk to the file.
  27877. This is the number of samples from the start of an edit that the
  27878. file is supposed to begin at. Seems like an obvious mistake to
  27879. only allow a file to occur in an edit once, but that's the way
  27880. it is..
  27881. @see AudioFormatReader::metadataValues, createWriterFor
  27882. */
  27883. static const tchar* const bwavTimeReference;
  27884. /** Metadata property name used by wav readers and writers for adding
  27885. a BWAV chunk to the file.
  27886. This is a
  27887. @see AudioFormatReader::metadataValues, createWriterFor
  27888. */
  27889. static const tchar* const bwavCodingHistory;
  27890. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27891. This just makes it easier than using the property names directly, and it
  27892. fills out the time and date in the right format.
  27893. */
  27894. static const StringPairArray createBWAVMetadata (const String& description,
  27895. const String& originator,
  27896. const String& originatorRef,
  27897. const Time& dateAndTime,
  27898. const int64 timeReferenceSamples,
  27899. const String& codingHistory);
  27900. const Array <int> getPossibleSampleRates();
  27901. const Array <int> getPossibleBitDepths();
  27902. bool canDoStereo();
  27903. bool canDoMono();
  27904. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27905. const bool deleteStreamIfOpeningFails);
  27906. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27907. double sampleRateToUse,
  27908. unsigned int numberOfChannels,
  27909. int bitsPerSample,
  27910. const StringPairArray& metadataValues,
  27911. int qualityOptionIndex);
  27912. /** Utility function to replace the metadata in a wav file with a new set of values.
  27913. If possible, this cheats by overwriting just the metadata region of the file, rather
  27914. than by copying the whole file again.
  27915. */
  27916. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  27917. juce_UseDebuggingNewOperator
  27918. };
  27919. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27920. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27921. #endif
  27922. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27923. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  27924. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27925. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27926. /********* Start of inlined file: juce_ActionListenerList.h *********/
  27927. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27928. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27929. /**
  27930. A set of ActionListeners.
  27931. Listeners can be added and removed from the list, and messages can be
  27932. broadcast to all the listeners.
  27933. @see ActionListener, ActionBroadcaster
  27934. */
  27935. class JUCE_API ActionListenerList : public MessageListener
  27936. {
  27937. public:
  27938. /** Creates an empty list. */
  27939. ActionListenerList() throw();
  27940. /** Destructor. */
  27941. ~ActionListenerList() throw();
  27942. /** Adds a listener to the list.
  27943. (Trying to add a listener that's already on the list will have no effect).
  27944. */
  27945. void addActionListener (ActionListener* const listener) throw();
  27946. /** Removes a listener from the list.
  27947. If the listener isn't on the list, this won't have any effect.
  27948. */
  27949. void removeActionListener (ActionListener* const listener) throw();
  27950. /** Removes all listeners from the list. */
  27951. void removeAllActionListeners() throw();
  27952. /** Broadcasts a message to all the registered listeners.
  27953. This sends the message asynchronously.
  27954. If a listener is on the list when this method is called but is removed from
  27955. the list before the message arrives, it won't receive the message. Similarly
  27956. listeners that are added to the list after the message is sent but before it
  27957. arrives won't get the message either.
  27958. */
  27959. void sendActionMessage (const String& message) const;
  27960. /** @internal */
  27961. void handleMessage (const Message&);
  27962. juce_UseDebuggingNewOperator
  27963. private:
  27964. SortedSet <void*> actionListeners_;
  27965. CriticalSection actionListenerLock_;
  27966. ActionListenerList (const ActionListenerList&);
  27967. const ActionListenerList& operator= (const ActionListenerList&);
  27968. };
  27969. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27970. /********* End of inlined file: juce_ActionListenerList.h *********/
  27971. /** Manages a list of ActionListeners, and can send them messages.
  27972. To quickly add methods to your class that can add/remove action
  27973. listeners and broadcast to them, you can derive from this.
  27974. @see ActionListenerList, ActionListener
  27975. */
  27976. class JUCE_API ActionBroadcaster
  27977. {
  27978. public:
  27979. /** Creates an ActionBroadcaster. */
  27980. ActionBroadcaster() throw();
  27981. /** Destructor. */
  27982. virtual ~ActionBroadcaster();
  27983. /** Adds a listener to the list.
  27984. (Trying to add a listener that's already on the list will have no effect).
  27985. */
  27986. void addActionListener (ActionListener* const listener);
  27987. /** Removes a listener from the list.
  27988. If the listener isn't on the list, this won't have any effect.
  27989. */
  27990. void removeActionListener (ActionListener* const listener);
  27991. /** Removes all listeners from the list. */
  27992. void removeAllActionListeners();
  27993. /** Broadcasts a message to all the registered listeners.
  27994. @see ActionListenerList::sendActionMessage
  27995. */
  27996. void sendActionMessage (const String& message) const;
  27997. private:
  27998. ActionListenerList actionListenerList;
  27999. ActionBroadcaster (const ActionBroadcaster&);
  28000. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  28001. };
  28002. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28003. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  28004. #endif
  28005. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  28006. #endif
  28007. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28008. #endif
  28009. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  28010. #endif
  28011. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  28012. #endif
  28013. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  28014. #endif
  28015. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  28016. #endif
  28017. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28018. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  28019. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28020. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28021. class InterprocessConnectionServer;
  28022. /**
  28023. Manages a simple two-way messaging connection to another process, using either
  28024. a socket or a named pipe as the transport medium.
  28025. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  28026. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  28027. and incoming messages will result in a callback via the messageReceived()
  28028. method.
  28029. To open a pipe and wait for another client to connect to it, use the createPipe()
  28030. method.
  28031. To act as a socket server and create connections for one or more client, see the
  28032. InterprocessConnectionServer class.
  28033. @see InterprocessConnectionServer, Socket, NamedPipe
  28034. */
  28035. class JUCE_API InterprocessConnection : public Thread,
  28036. private MessageListener
  28037. {
  28038. public:
  28039. /** Creates a connection.
  28040. Connections are created manually, connecting them with the connectToSocket()
  28041. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  28042. when a client wants to connect.
  28043. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  28044. connectionLost() and messageReceived() methods will
  28045. always be made using the message thread; if false,
  28046. these will be called immediately on the connection's
  28047. own thread.
  28048. @param magicMessageHeaderNumber a magic number to use in the header to check the
  28049. validity of the data blocks being sent and received. This
  28050. can be any number, but the sender and receiver must obviously
  28051. use matching values or they won't recognise each other.
  28052. */
  28053. InterprocessConnection (const bool callbacksOnMessageThread = true,
  28054. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  28055. /** Destructor. */
  28056. ~InterprocessConnection();
  28057. /** Tries to connect this object to a socket.
  28058. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  28059. object waiting to receive client connections on this port number.
  28060. @param hostName the host computer, either a network address or name
  28061. @param portNumber the socket port number to try to connect to
  28062. @param timeOutMillisecs how long to keep trying before giving up
  28063. @returns true if the connection is established successfully
  28064. @see Socket
  28065. */
  28066. bool connectToSocket (const String& hostName,
  28067. const int portNumber,
  28068. const int timeOutMillisecs);
  28069. /** Tries to connect the object to an existing named pipe.
  28070. For this to work, another process on the same computer must already have opened
  28071. an InterprocessConnection object and used createPipe() to create a pipe for this
  28072. to connect to.
  28073. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28074. @returns true if it connects successfully.
  28075. @see createPipe, NamedPipe
  28076. */
  28077. bool connectToPipe (const String& pipeName,
  28078. const int pipeReceiveMessageTimeoutMs = -1);
  28079. /** Tries to create a new pipe for other processes to connect to.
  28080. This creates a pipe with the given name, so that other processes can use
  28081. connectToPipe() to connect to the other end.
  28082. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28083. If another process is already using this pipe, this will fail and return false.
  28084. */
  28085. bool createPipe (const String& pipeName,
  28086. const int pipeReceiveMessageTimeoutMs = -1);
  28087. /** Disconnects and closes any currently-open sockets or pipes. */
  28088. void disconnect();
  28089. /** True if a socket or pipe is currently active. */
  28090. bool isConnected() const;
  28091. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  28092. StreamingSocket* getSocket() const throw() { return socket; }
  28093. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  28094. NamedPipe* getPipe() const throw() { return pipe; }
  28095. /** Returns the name of the machine at the other end of this connection.
  28096. This will return an empty string if the other machine isn't known for
  28097. some reason.
  28098. */
  28099. const String getConnectedHostName() const;
  28100. /** Tries to send a message to the other end of this connection.
  28101. This will fail if it's not connected, or if there's some kind of write error. If
  28102. it succeeds, the connection object at the other end will receive the message by
  28103. a callback to its messageReceived() method.
  28104. @see messageReceived
  28105. */
  28106. bool sendMessage (const MemoryBlock& message);
  28107. /** Called when the connection is first connected.
  28108. If the connection was created with the callbacksOnMessageThread flag set, then
  28109. this will be called on the message thread; otherwise it will be called on a server
  28110. thread.
  28111. */
  28112. virtual void connectionMade() = 0;
  28113. /** Called when the connection is broken.
  28114. If the connection was created with the callbacksOnMessageThread flag set, then
  28115. this will be called on the message thread; otherwise it will be called on a server
  28116. thread.
  28117. */
  28118. virtual void connectionLost() = 0;
  28119. /** Called when a message arrives.
  28120. When the object at the other end of this connection sends us a message with sendMessage(),
  28121. this callback is used to deliver it to us.
  28122. If the connection was created with the callbacksOnMessageThread flag set, then
  28123. this will be called on the message thread; otherwise it will be called on a server
  28124. thread.
  28125. @see sendMessage
  28126. */
  28127. virtual void messageReceived (const MemoryBlock& message) = 0;
  28128. juce_UseDebuggingNewOperator
  28129. private:
  28130. CriticalSection pipeAndSocketLock;
  28131. StreamingSocket* socket;
  28132. NamedPipe* pipe;
  28133. bool callbackConnectionState;
  28134. const bool useMessageThread;
  28135. const uint32 magicMessageHeader;
  28136. int pipeReceiveMessageTimeout;
  28137. friend class InterprocessConnectionServer;
  28138. void initialiseWithSocket (StreamingSocket* const socket_);
  28139. void initialiseWithPipe (NamedPipe* const pipe_);
  28140. void handleMessage (const Message& message);
  28141. void connectionMadeInt();
  28142. void connectionLostInt();
  28143. void deliverDataInt (const MemoryBlock& data);
  28144. bool readNextMessageInt();
  28145. void run();
  28146. InterprocessConnection (const InterprocessConnection&);
  28147. const InterprocessConnection& operator= (const InterprocessConnection&);
  28148. };
  28149. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28150. /********* End of inlined file: juce_InterprocessConnection.h *********/
  28151. #endif
  28152. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28153. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  28154. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28155. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28156. /**
  28157. An object that waits for client sockets to connect to a port on this host, and
  28158. creates InterprocessConnection objects for each one.
  28159. To use this, create a class derived from it which implements the createConnectionObject()
  28160. method, so that it creates suitable connection objects for each client that tries
  28161. to connect.
  28162. @see InterprocessConnection
  28163. */
  28164. class JUCE_API InterprocessConnectionServer : private Thread
  28165. {
  28166. public:
  28167. /** Creates an uninitialised server object.
  28168. */
  28169. InterprocessConnectionServer();
  28170. /** Destructor. */
  28171. ~InterprocessConnectionServer();
  28172. /** Starts an internal thread which listens on the given port number.
  28173. While this is running, in another process tries to connect with the
  28174. InterprocessConnection::connectToSocket() method, this object will call
  28175. createConnectionObject() to create a connection to that client.
  28176. Use stop() to stop the thread running.
  28177. @see createConnectionObject, stop
  28178. */
  28179. bool beginWaitingForSocket (const int portNumber);
  28180. /** Terminates the listener thread, if it's active.
  28181. @see beginWaitingForSocket
  28182. */
  28183. void stop();
  28184. protected:
  28185. /** Creates a suitable connection object for a client process that wants to
  28186. connect to this one.
  28187. This will be called by the listener thread when a client process tries
  28188. to connect, and must return a new InterprocessConnection object that will
  28189. then run as this end of the connection.
  28190. @see InterprocessConnection
  28191. */
  28192. virtual InterprocessConnection* createConnectionObject() = 0;
  28193. public:
  28194. juce_UseDebuggingNewOperator
  28195. private:
  28196. StreamingSocket* volatile socket;
  28197. void run();
  28198. InterprocessConnectionServer (const InterprocessConnectionServer&);
  28199. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  28200. };
  28201. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28202. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  28203. #endif
  28204. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  28205. #endif
  28206. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  28207. #endif
  28208. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28209. /********* Start of inlined file: juce_MessageManager.h *********/
  28210. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28211. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28212. class Component;
  28213. class MessageManagerLock;
  28214. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  28215. */
  28216. typedef void* (MessageCallbackFunction) (void* userData);
  28217. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  28218. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  28219. */
  28220. class JUCE_API MessageManager
  28221. {
  28222. public:
  28223. /** Returns the global instance of the MessageManager. */
  28224. static MessageManager* getInstance() throw();
  28225. /** Runs the event dispatch loop until a stop message is posted.
  28226. This method is only intended to be run by the application's startup routine,
  28227. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  28228. @see stopDispatchLoop
  28229. */
  28230. void runDispatchLoop();
  28231. /** Sends a signal that the dispatch loop should terminate.
  28232. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  28233. will be interrupted and will return.
  28234. @see runDispatchLoop
  28235. */
  28236. void stopDispatchLoop();
  28237. /** Returns true if the stopDispatchLoop() method has been called.
  28238. */
  28239. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  28240. /** Synchronously dispatches messages until a given time has elapsed.
  28241. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  28242. otherwise returns true.
  28243. */
  28244. bool runDispatchLoopUntil (int millisecondsToRunFor);
  28245. /** Calls a function using the message-thread.
  28246. This can be used by any thread to cause this function to be called-back
  28247. by the message thread. If it's the message-thread that's calling this method,
  28248. then the function will just be called; if another thread is calling, a message
  28249. will be posted to the queue, and this method will block until that message
  28250. is delivered, the function is called, and the result is returned.
  28251. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  28252. thread has a critical section locked, which an unrelated message callback then tries to lock
  28253. before the message thread gets round to processing this callback.
  28254. @param callback the function to call - its signature must be @code
  28255. void* myCallbackFunction (void*) @endcode
  28256. @param userData a user-defined pointer that will be passed to the function that gets called
  28257. @returns the value that the callback function returns.
  28258. @see MessageManagerLock
  28259. */
  28260. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  28261. void* userData);
  28262. /** Returns true if the caller-thread is the message thread. */
  28263. bool isThisTheMessageThread() const throw();
  28264. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  28265. (Best to ignore this method unless you really know what you're doing..)
  28266. @see getCurrentMessageThread
  28267. */
  28268. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  28269. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  28270. (Best to ignore this method unless you really know what you're doing..)
  28271. @see setCurrentMessageThread
  28272. */
  28273. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  28274. /** Returns true if the caller thread has currenltly got the message manager locked.
  28275. see the MessageManagerLock class for more info about this.
  28276. This will be true if the caller is the message thread, because that automatically
  28277. gains a lock while a message is being dispatched.
  28278. */
  28279. bool currentThreadHasLockedMessageManager() const throw();
  28280. /** Sends a message to all other JUCE applications that are running.
  28281. @param messageText the string that will be passed to the actionListenerCallback()
  28282. method of the broadcast listeners in the other app.
  28283. @see registerBroadcastListener, ActionListener
  28284. */
  28285. static void broadcastMessage (const String& messageText) throw();
  28286. /** Registers a listener to get told about broadcast messages.
  28287. The actionListenerCallback() callback's string parameter
  28288. is the message passed into broadcastMessage().
  28289. @see broadcastMessage
  28290. */
  28291. void registerBroadcastListener (ActionListener* listener) throw();
  28292. /** Deregisters a broadcast listener. */
  28293. void deregisterBroadcastListener (ActionListener* listener) throw();
  28294. /** @internal */
  28295. void deliverMessage (void*);
  28296. /** @internal */
  28297. void deliverBroadcastMessage (const String&);
  28298. /** @internal */
  28299. ~MessageManager() throw();
  28300. juce_UseDebuggingNewOperator
  28301. private:
  28302. MessageManager() throw();
  28303. friend class MessageListener;
  28304. friend class ChangeBroadcaster;
  28305. friend class ActionBroadcaster;
  28306. static MessageManager* instance;
  28307. SortedSet<const MessageListener*> messageListeners;
  28308. ActionListenerList* broadcastListeners;
  28309. friend class JUCEApplication;
  28310. bool quitMessagePosted, quitMessageReceived;
  28311. Thread::ThreadID messageThreadId;
  28312. VoidArray modalComponents;
  28313. static void* exitModalLoopCallback (void*);
  28314. void postMessageToQueue (Message* const message);
  28315. static void doPlatformSpecificInitialisation();
  28316. static void doPlatformSpecificShutdown();
  28317. friend class MessageManagerLock;
  28318. CriticalSection messageDispatchLock;
  28319. Thread::ThreadID currentLockingThreadId;
  28320. MessageManager (const MessageManager&);
  28321. const MessageManager& operator= (const MessageManager&);
  28322. };
  28323. /** Used to make sure that the calling thread has exclusive access to the message loop.
  28324. Because it's not thread-safe to call any of the Component or other UI classes
  28325. from threads other than the message thread, one of these objects can be used to
  28326. lock the message loop and allow this to be done. The message thread will be
  28327. suspended for the lifetime of the MessageManagerLock object, so create one on
  28328. the stack like this: @code
  28329. void MyThread::run()
  28330. {
  28331. someData = 1234;
  28332. const MessageManagerLock mmLock;
  28333. // the event loop will now be locked so it's safe to make a few calls..
  28334. myComponent->setBounds (newBounds);
  28335. myComponent->repaint();
  28336. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  28337. }
  28338. @endcode
  28339. Obviously be careful not to create one of these and leave it lying around, or
  28340. your app will grind to a halt!
  28341. Another caveat is that using this in conjunction with other CriticalSections
  28342. can create lots of interesting ways of producing a deadlock! In particular, if
  28343. your message thread calls stopThread() for a thread that uses these locks,
  28344. you'll get an (occasional) deadlock..
  28345. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  28346. */
  28347. class JUCE_API MessageManagerLock
  28348. {
  28349. public:
  28350. /** Tries to acquire a lock on the message manager.
  28351. If this constructor
  28352. When this constructor returns, the message manager will have finished processing the
  28353. last message and will not send another message until this MessageManagerLock is
  28354. deleted.
  28355. If the current thread already has the lock, nothing will be done, so it's perfectly
  28356. safe to create these locks recursively.
  28357. */
  28358. MessageManagerLock() throw();
  28359. /** Releases the current thread's lock on the message manager.
  28360. Make sure this object is created and deleted by the same thread,
  28361. otherwise there are no guarantees what will happen!
  28362. */
  28363. ~MessageManagerLock() throw();
  28364. /** Tries to acquire a lock on the message manager.
  28365. This does the same thing as the normal constructor, but while it's waiting to get
  28366. the lock, it checks the specified thread to see if it has been given the
  28367. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  28368. without gaining the lock.
  28369. To find out whether the lock was successful, call lockWasGained(). If this is
  28370. false, your thread is being told to die, so you'd better get out of there.
  28371. If the current thread already has the lock, nothing will be done, so it's perfectly
  28372. safe to create these locks recursively.
  28373. E.g.
  28374. @code
  28375. void run()
  28376. {
  28377. ...
  28378. while (! threadShouldExit())
  28379. {
  28380. MessageManagerLock mml (Thread::getCurrentThread());
  28381. if (! mml.lockWasGained())
  28382. return; // another thread is trying to kill us!
  28383. ..do some locked stuff here..
  28384. }
  28385. ..and now the MM is now unlocked..
  28386. }
  28387. @endcode
  28388. */
  28389. MessageManagerLock (Thread* const threadToCheckForExitSignal) throw();
  28390. /** Returns true if the lock was successfully acquired.
  28391. (See the constructor that takes a Thread for more info).
  28392. */
  28393. bool lockWasGained() const throw() { return locked; }
  28394. private:
  28395. Thread::ThreadID lastLockingThreadId;
  28396. bool locked;
  28397. };
  28398. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28399. /********* End of inlined file: juce_MessageManager.h *********/
  28400. #endif
  28401. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28402. /********* Start of inlined file: juce_MultiTimer.h *********/
  28403. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28404. #define __JUCE_MULTITIMER_JUCEHEADER__
  28405. /**
  28406. A type of timer class that can run multiple timers with different frequencies,
  28407. all of which share a single callback.
  28408. This class is very similar to the Timer class, but allows you run multiple
  28409. separate timers, where each one has a unique ID number. The methods in this
  28410. class are exactly equivalent to those in Timer, but with the addition of
  28411. this ID number.
  28412. To use it, you need to create a subclass of MultiTimer, implementing the
  28413. timerCallback() method. Then you can start timers with startTimer(), and
  28414. each time the callback is triggered, it passes in the ID of the timer that
  28415. caused it.
  28416. @see Timer
  28417. */
  28418. class JUCE_API MultiTimer
  28419. {
  28420. protected:
  28421. /** Creates a MultiTimer.
  28422. When created, no timers are running, so use startTimer() to start things off.
  28423. */
  28424. MultiTimer() throw();
  28425. /** Creates a copy of another timer.
  28426. Note that this timer will not contain any running timers, even if the one you're
  28427. copying from was running.
  28428. */
  28429. MultiTimer (const MultiTimer& other) throw();
  28430. public:
  28431. /** Destructor. */
  28432. virtual ~MultiTimer();
  28433. /** The user-defined callback routine that actually gets called by each of the
  28434. timers that are running.
  28435. It's perfectly ok to call startTimer() or stopTimer() from within this
  28436. callback to change the subsequent intervals.
  28437. */
  28438. virtual void timerCallback (const int timerId) = 0;
  28439. /** Starts a timer and sets the length of interval required.
  28440. If the timer is already started, this will reset it, so the
  28441. time between calling this method and the next timer callback
  28442. will not be less than the interval length passed in.
  28443. @param timerId a unique Id number that identifies the timer to
  28444. start. This is the id that will be passed back
  28445. to the timerCallback() method when this timer is
  28446. triggered
  28447. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28448. rounded up to 1)
  28449. */
  28450. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28451. /** Stops a timer.
  28452. If a timer has been started with the given ID number, it will be cancelled.
  28453. No more callbacks will be made for the specified timer after this method returns.
  28454. If this is called from a different thread, any callbacks that may
  28455. be currently executing may be allowed to finish before the method
  28456. returns.
  28457. */
  28458. void stopTimer (const int timerId) throw();
  28459. /** Checks whether a timer has been started for a specified ID.
  28460. @returns true if a timer with the given ID is running.
  28461. */
  28462. bool isTimerRunning (const int timerId) const throw();
  28463. /** Returns the interval for a specified timer ID.
  28464. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28465. is running for the ID number specified.
  28466. */
  28467. int getTimerInterval (const int timerId) const throw();
  28468. private:
  28469. CriticalSection timerListLock;
  28470. VoidArray timers;
  28471. const MultiTimer& operator= (const MultiTimer&);
  28472. };
  28473. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28474. /********* End of inlined file: juce_MultiTimer.h *********/
  28475. #endif
  28476. #ifndef __JUCE_TIMER_JUCEHEADER__
  28477. #endif
  28478. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28479. #endif
  28480. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28481. /********* Start of inlined file: juce_GradientBrush.h *********/
  28482. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28483. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28484. /********* Start of inlined file: juce_ColourGradient.h *********/
  28485. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28486. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28487. /**
  28488. Structure used to define a colour gradient for painting areas.
  28489. @see GradientBrush
  28490. */
  28491. class JUCE_API ColourGradient
  28492. {
  28493. public:
  28494. /** Creates a gradient object.
  28495. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28496. colour2 should be. In between them there's a gradient.
  28497. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28498. its centre.
  28499. The alpha transparencies of the colours are used, so note that
  28500. if you blend from transparent to a solid colour, the RGB of the transparent
  28501. colour will become visible in parts of the gradient. e.g. blending
  28502. from Colour::transparentBlack to Colours::white will produce a
  28503. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28504. will be white all the way across.
  28505. @see ColourGradient
  28506. */
  28507. ColourGradient (const Colour& colour1,
  28508. const float x1,
  28509. const float y1,
  28510. const Colour& colour2,
  28511. const float x2,
  28512. const float y2,
  28513. const bool isRadial) throw();
  28514. /** Creates an uninitialised gradient.
  28515. If you use this constructor instead of the other one, be sure to set all the
  28516. object's public member variables before using it!
  28517. */
  28518. ColourGradient() throw();
  28519. /** Destructor */
  28520. ~ColourGradient() throw();
  28521. /** Removes any colours that have been added.
  28522. This will also remove any start and end colours, so the gradient won't work. You'll
  28523. need to add more colours with addColour().
  28524. */
  28525. void clearColours() throw();
  28526. /** Adds a colour at a point along the length of the gradient.
  28527. This allows the gradient to go through a spectrum of colours, instead of just a
  28528. start and end colour.
  28529. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28530. of the distance along the line between the two points
  28531. at which the colour should occur.
  28532. @param colour the colour that should be used at this point
  28533. */
  28534. void addColour (const double proportionAlongGradient,
  28535. const Colour& colour) throw();
  28536. /** Multiplies the alpha value of all the colours by the given scale factor */
  28537. void multiplyOpacity (const float multiplier) throw();
  28538. /** Returns the number of colour-stops that have been added. */
  28539. int getNumColours() const throw();
  28540. /** Returns the position along the length of the gradient of the colour with this index.
  28541. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28542. */
  28543. double getColourPosition (const int index) const throw();
  28544. /** Returns the colour that was added with a given index.
  28545. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28546. */
  28547. const Colour getColour (const int index) const throw();
  28548. /** Creates a set of interpolated premultiplied ARGB values.
  28549. The caller must delete the array that is returned using juce_free().
  28550. */
  28551. PixelARGB* createLookupTable (int& numEntries) const throw();
  28552. /** Returns true if all colours are opaque. */
  28553. bool isOpaque() const throw();
  28554. /** Returns true if all colours are completely transparent. */
  28555. bool isInvisible() const throw();
  28556. float x1;
  28557. float y1;
  28558. float x2;
  28559. float y2;
  28560. /** If true, the gradient should be filled circularly, centred around
  28561. (x1, y1), with (x2, y2) defining a point on the circumference.
  28562. If false, the gradient is linear between the two points.
  28563. */
  28564. bool isRadial;
  28565. /** A transform to apply to the resultant gradient shape */
  28566. AffineTransform transform;
  28567. juce_UseDebuggingNewOperator
  28568. private:
  28569. Array <uint32> colours;
  28570. };
  28571. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28572. /********* End of inlined file: juce_ColourGradient.h *********/
  28573. /**
  28574. A Brush that fills areas with a colour gradient.
  28575. The gradient can either be linear or circular.
  28576. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28577. */
  28578. class JUCE_API GradientBrush : public Brush
  28579. {
  28580. public:
  28581. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28582. (x1, y1) is the location relative to the origin of the Graphics context,
  28583. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28584. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28585. its centre.
  28586. The alpha transparencies of the colours are used, so the brush
  28587. need not be completely opaque. Note that this means that if you
  28588. blend from transparent to a solid colour, the RGB of the transparent
  28589. colour will become visible in parts of the gradient. e.g. blending
  28590. from Colour::transparentBlack to Colours::white will produce a
  28591. grey colour, but Colour::transparentWhite to Colours::white will be
  28592. white all the way across.
  28593. @see ColourGradient
  28594. */
  28595. GradientBrush (const Colour& colour1,
  28596. const float x1,
  28597. const float y1,
  28598. const Colour& colour2,
  28599. const float x2,
  28600. const float y2,
  28601. const bool isRadial) throw();
  28602. /** Creates a gradient brush from a ColourGradient object.
  28603. */
  28604. GradientBrush (const ColourGradient& gradient) throw();
  28605. /** Destructor. */
  28606. ~GradientBrush() throw();
  28607. Brush* createCopy() const throw();
  28608. void applyTransform (const AffineTransform& transform) throw();
  28609. void multiplyOpacity (const float multiple) throw();
  28610. bool isInvisible() const throw();
  28611. void paintPath (LowLevelGraphicsContext& context,
  28612. const Path& path, const AffineTransform& transform) throw();
  28613. void paintRectangle (LowLevelGraphicsContext& context,
  28614. int x, int y, int w, int h) throw();
  28615. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28616. const Image& alphaChannelImage, int imageX, int imageY,
  28617. int x, int y, int w, int h) throw();
  28618. juce_UseDebuggingNewOperator
  28619. protected:
  28620. ColourGradient gradient;
  28621. private:
  28622. GradientBrush (const GradientBrush&);
  28623. const GradientBrush& operator= (const GradientBrush&);
  28624. };
  28625. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28626. /********* End of inlined file: juce_GradientBrush.h *********/
  28627. #endif
  28628. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28629. /********* Start of inlined file: juce_ImageBrush.h *********/
  28630. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28631. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28632. /********* Start of inlined file: juce_Image.h *********/
  28633. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28634. #define __JUCE_IMAGE_JUCEHEADER__
  28635. /**
  28636. Holds a fixed-size bitmap.
  28637. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28638. To draw into an image, create a Graphics object for it.
  28639. e.g. @code
  28640. // create a transparent 500x500 image..
  28641. Image myImage (Image::RGB, 500, 500, true);
  28642. Graphics g (myImage);
  28643. g.setColour (Colours::red);
  28644. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28645. @endcode
  28646. Other useful ways to create an image are with the ImageCache class, or the
  28647. ImageFileFormat, which provides a way to load common image files.
  28648. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28649. */
  28650. class JUCE_API Image
  28651. {
  28652. public:
  28653. enum PixelFormat
  28654. {
  28655. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28656. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28657. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28658. };
  28659. /** Creates an in-memory image with a specified size and format.
  28660. @param format the number of colour channels in the image
  28661. @param imageWidth the desired width of the image, in pixels - this value must be
  28662. greater than zero (otherwise a width of 1 will be used)
  28663. @param imageHeight the desired width of the image, in pixels - this value must be
  28664. greater than zero (otherwise a height of 1 will be used)
  28665. @param clearImage if true, the image will initially be cleared to black or transparent
  28666. black. If false, the image may contain random data, and the
  28667. user will have to deal with this
  28668. */
  28669. Image (const PixelFormat format,
  28670. const int imageWidth,
  28671. const int imageHeight,
  28672. const bool clearImage);
  28673. /** Creates a copy of another image.
  28674. @see createCopy
  28675. */
  28676. Image (const Image& other);
  28677. /** Destructor. */
  28678. virtual ~Image();
  28679. /** Returns the image's width (in pixels). */
  28680. int getWidth() const throw() { return imageWidth; }
  28681. /** Returns the image's height (in pixels). */
  28682. int getHeight() const throw() { return imageHeight; }
  28683. /** Returns the image's pixel format. */
  28684. PixelFormat getFormat() const throw() { return format; }
  28685. /** True if the image's format is ARGB. */
  28686. bool isARGB() const throw() { return format == ARGB; }
  28687. /** True if the image's format is RGB. */
  28688. bool isRGB() const throw() { return format == RGB; }
  28689. /** True if the image contains an alpha-channel. */
  28690. bool hasAlphaChannel() const throw() { return format != RGB; }
  28691. /** Clears a section of the image with a given colour.
  28692. This won't do any alpha-blending - it just sets all pixels in the image to
  28693. the given colour (which may be non-opaque if the image has an alpha channel).
  28694. */
  28695. virtual void clear (int x, int y, int w, int h,
  28696. const Colour& colourToClearTo = Colour (0x00000000));
  28697. /** Returns a new image that's a copy of this one.
  28698. A new size for the copied image can be specified, or values less than
  28699. zero can be passed-in to use the image's existing dimensions.
  28700. It's up to the caller to delete the image when no longer needed.
  28701. */
  28702. virtual Image* createCopy (int newWidth = -1,
  28703. int newHeight = -1,
  28704. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28705. /** Returns the colour of one of the pixels in the image.
  28706. If the co-ordinates given are beyond the image's boundaries, this will
  28707. return Colours::transparentBlack.
  28708. (0, 0) is the image's top-left corner.
  28709. @see getAlphaAt, setPixelAt, blendPixelAt
  28710. */
  28711. virtual const Colour getPixelAt (const int x, const int y) const;
  28712. /** Sets the colour of one of the image's pixels.
  28713. If the co-ordinates are beyond the image's boundaries, then nothing will
  28714. happen.
  28715. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28716. just replace the existing pixel with the given one. The colour's opacity
  28717. will be ignored if this image doesn't have an alpha-channel.
  28718. (0, 0) is the image's top-left corner.
  28719. @see blendPixelAt
  28720. */
  28721. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28722. /** Changes the opacity of a pixel.
  28723. This only has an effect if the image has an alpha channel and if the
  28724. given co-ordinates are inside the image's boundary.
  28725. The multiplier must be in the range 0 to 1.0, and the current alpha
  28726. at the given co-ordinates will be multiplied by this value.
  28727. @see getAlphaAt, setPixelAt
  28728. */
  28729. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28730. /** Changes the overall opacity of the image.
  28731. This will multiply the alpha value of each pixel in the image by the given
  28732. amount (limiting the resulting alpha values between 0 and 255). This allows
  28733. you to make an image more or less transparent.
  28734. If the image doesn't have an alpha channel, this won't have any effect.
  28735. */
  28736. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28737. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28738. */
  28739. virtual void desaturate();
  28740. /** Locks some of the pixels in the image so they can be read and written to.
  28741. This returns a pointer to some memory containing the pixels in the given
  28742. rectangle. It also returns values for the line and pixel stride used within
  28743. the data. The format of the pixel data is the same as that of this image.
  28744. When you've finished reading and changing the data, you must call
  28745. releasePixelDataReadWrite() to give the pixels back to the image.
  28746. For images that are stored in memory, this method may just return a direct
  28747. pointer to the image's data, but other types of image may be stored elsewhere,
  28748. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28749. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28750. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28751. instead.
  28752. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28753. */
  28754. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28755. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28756. */
  28757. virtual void releasePixelDataReadWrite (void* sourceData);
  28758. /** Locks some of the pixels in the image so they can be read.
  28759. This returns a pointer to some memory containing the pixels in the given
  28760. rectangle. It also returns values for the line and pixel stride used within
  28761. the data. The format of the pixel data is the same as that of this image.
  28762. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28763. to let the image free the memory if necessary.
  28764. For images that are stored in memory, this method may just return a direct
  28765. pointer to the image's data, but other types of image may be stored elsewhere,
  28766. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28767. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28768. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28769. instead.
  28770. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28771. */
  28772. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28773. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28774. */
  28775. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28776. /** Copies some pixel values to a rectangle of the image.
  28777. The format of the pixel data must match that of the image itself, and the
  28778. rectangle supplied must be within the image's bounds.
  28779. */
  28780. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28781. const uint8* sourcePixelData, int sourceLineStride);
  28782. /** Copies a section of the image to somewhere else within itself.
  28783. */
  28784. virtual void moveImageSection (int destX, int destY,
  28785. int sourceX, int sourceY,
  28786. int width, int height);
  28787. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28788. of the image.
  28789. @param result the list that will have the area added to it
  28790. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28791. above this level will be considered opaque
  28792. */
  28793. void createSolidAreaMask (RectangleList& result,
  28794. const float alphaThreshold = 0.5f) const;
  28795. juce_UseDebuggingNewOperator
  28796. /** Creates a context suitable for drawing onto this image.
  28797. Don't call this method directly! It's used internally by the Graphics class.
  28798. */
  28799. virtual LowLevelGraphicsContext* createLowLevelContext();
  28800. protected:
  28801. const PixelFormat format;
  28802. const int imageWidth, imageHeight;
  28803. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28804. Image (const PixelFormat format,
  28805. const int imageWidth,
  28806. const int imageHeight);
  28807. int pixelStride, lineStride;
  28808. uint8* imageData;
  28809. private:
  28810. const Image& operator= (const Image&);
  28811. };
  28812. #endif // __JUCE_IMAGE_JUCEHEADER__
  28813. /********* End of inlined file: juce_Image.h *********/
  28814. /**
  28815. A Brush that fills areas with tiled repetitions of an image.
  28816. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28817. */
  28818. class JUCE_API ImageBrush : public Brush
  28819. {
  28820. public:
  28821. /* Creates an image brush, ready for use in Graphics::setBrush().
  28822. (x, y) is an anchor point for the top-left of the image
  28823. A reference to the image passed in will be kept, so don't delete
  28824. it within the lifetime of this object
  28825. */
  28826. ImageBrush (Image* const image,
  28827. const int anchorX,
  28828. const int anchorY,
  28829. const float opacity) throw();
  28830. /** Destructor. */
  28831. ~ImageBrush() throw();
  28832. Brush* createCopy() const throw();
  28833. void applyTransform (const AffineTransform& transform) throw();
  28834. void multiplyOpacity (const float multiple) throw();
  28835. bool isInvisible() const throw();
  28836. void paintPath (LowLevelGraphicsContext& context,
  28837. const Path& path, const AffineTransform& transform) throw();
  28838. void paintRectangle (LowLevelGraphicsContext& context,
  28839. int x, int y, int w, int h) throw();
  28840. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28841. const Image& alphaChannelImage, int imageX, int imageY,
  28842. int x, int y, int w, int h) throw();
  28843. juce_UseDebuggingNewOperator
  28844. protected:
  28845. Image* image;
  28846. int anchorX, anchorY;
  28847. float opacity;
  28848. private:
  28849. ImageBrush (const ImageBrush&);
  28850. const ImageBrush& operator= (const ImageBrush&);
  28851. void getStartXY (int& x, int& y) const throw();
  28852. };
  28853. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28854. /********* End of inlined file: juce_ImageBrush.h *********/
  28855. #endif
  28856. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28857. #endif
  28858. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28859. #endif
  28860. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28861. #endif
  28862. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28863. #endif
  28864. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28865. #endif
  28866. #ifndef __JUCE_FONT_JUCEHEADER__
  28867. #endif
  28868. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28869. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28870. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28871. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28872. /**
  28873. An glyph from a particular font, with a particular size, style,
  28874. typeface and position.
  28875. @see GlyphArrangement, Font
  28876. */
  28877. class JUCE_API PositionedGlyph
  28878. {
  28879. public:
  28880. /** Returns the character the glyph represents. */
  28881. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28882. /** Checks whether the glyph is actually empty. */
  28883. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28884. /** Returns the position of the glyph's left-hand edge. */
  28885. float getLeft() const throw() { return x; }
  28886. /** Returns the position of the glyph's right-hand edge. */
  28887. float getRight() const throw() { return x + w; }
  28888. /** Returns the y position of the glyph's baseline. */
  28889. float getBaselineY() const throw() { return y; }
  28890. /** Returns the y position of the top of the glyph. */
  28891. float getTop() const throw() { return y - fontAscent; }
  28892. /** Returns the y position of the bottom of the glyph. */
  28893. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28894. /** Shifts the glyph's position by a relative amount. */
  28895. void moveBy (const float deltaX,
  28896. const float deltaY) throw();
  28897. /** Draws the glyph into a graphics context. */
  28898. void draw (const Graphics& g) const throw();
  28899. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28900. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28901. /** Returns the path for this glyph.
  28902. @param path the glyph's outline will be appended to this path
  28903. */
  28904. void createPath (Path& path) const throw();
  28905. /** Checks to see if a point lies within this glyph. */
  28906. bool hitTest (float x, float y) const throw();
  28907. juce_UseDebuggingNewOperator
  28908. private:
  28909. friend class GlyphArrangement;
  28910. float x, y, w;
  28911. float fontHeight, fontAscent, fontHorizontalScale;
  28912. bool isUnderlined;
  28913. const TypefaceGlyphInfo* glyphInfo;
  28914. PositionedGlyph() throw();
  28915. };
  28916. /**
  28917. A set of glyphs, each with a position.
  28918. You can create a GlyphArrangement, text to it and then draw it onto a
  28919. graphics context. It's used internally by the text methods in the
  28920. Graphics class, but can be used directly if more control is needed.
  28921. @see Font, PositionedGlyph
  28922. */
  28923. class JUCE_API GlyphArrangement
  28924. {
  28925. public:
  28926. /** Creates an empty arrangement. */
  28927. GlyphArrangement() throw();
  28928. /** Takes a copy of another arrangement. */
  28929. GlyphArrangement (const GlyphArrangement& other) throw();
  28930. /** Copies another arrangement onto this one.
  28931. To add another arrangement without clearing this one, use addGlyphArrangement().
  28932. */
  28933. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28934. /** Destructor. */
  28935. ~GlyphArrangement() throw();
  28936. /** Returns the total number of glyphs in the arrangement. */
  28937. int getNumGlyphs() const throw() { return numGlyphs; }
  28938. /** Returns one of the glyphs from the arrangement.
  28939. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28940. careful not to pass an out-of-range index here, as it
  28941. doesn't do any bounds-checking.
  28942. */
  28943. PositionedGlyph& getGlyph (const int index) const throw();
  28944. /** Clears all text from the arrangement and resets it.
  28945. */
  28946. void clear() throw();
  28947. /** Appends a line of text to the arrangement.
  28948. This will add the text as a single line, where x is the left-hand edge of the
  28949. first character, and y is the position for the text's baseline.
  28950. If the text contains new-lines or carriage-returns, this will ignore them - use
  28951. addJustifiedText() to add multi-line arrangements.
  28952. */
  28953. void addLineOfText (const Font& font,
  28954. const String& text,
  28955. const float x,
  28956. const float y) throw();
  28957. /** Adds a line of text, truncating it if it's wider than a specified size.
  28958. This is the same as addLineOfText(), but if the line's width exceeds the value
  28959. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  28960. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  28961. */
  28962. void addCurtailedLineOfText (const Font& font,
  28963. const String& text,
  28964. float x,
  28965. const float y,
  28966. const float maxWidthPixels,
  28967. const bool useEllipsis) throw();
  28968. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  28969. This will add text to the arrangement, breaking it into new lines either where there
  28970. is a new-line or carriage-return character in the text, or where a line's width
  28971. exceeds the value set in maxLineWidth.
  28972. Each line that is added will be laid out using the flags set in horizontalLayout, so
  28973. the lines can be left- or right-justified, or centred horizontally in the space
  28974. between x and (x + maxLineWidth).
  28975. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  28976. lines will be placed below it, separated by a distance of font.getHeight().
  28977. */
  28978. void addJustifiedText (const Font& font,
  28979. const String& text,
  28980. float x, float y,
  28981. const float maxLineWidth,
  28982. const Justification& horizontalLayout) throw();
  28983. /** Tries to fit some text withing a given space.
  28984. This does its best to make the given text readable within the specified rectangle,
  28985. so it useful for labelling things.
  28986. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  28987. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  28988. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  28989. it's been truncated.
  28990. A Justification parameter lets you specify how the text is laid out within the rectangle,
  28991. both horizontally and vertically.
  28992. @see Graphics::drawFittedText
  28993. */
  28994. void addFittedText (const Font& font,
  28995. const String& text,
  28996. float x, float y,
  28997. float width, float height,
  28998. const Justification& layout,
  28999. int maximumLinesToUse,
  29000. const float minimumHorizontalScale = 0.7f) throw();
  29001. /** Appends another glyph arrangement to this one. */
  29002. void addGlyphArrangement (const GlyphArrangement& other) throw();
  29003. /** Draws this glyph arrangement to a graphics context.
  29004. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  29005. method, which renders the glyphs as filled vectors.
  29006. */
  29007. void draw (const Graphics& g) const throw();
  29008. /** Draws this glyph arrangement to a graphics context.
  29009. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  29010. method for non-transformed arrangements.
  29011. */
  29012. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29013. /** Converts the set of glyphs into a path.
  29014. @param path the glyphs' outlines will be appended to this path
  29015. */
  29016. void createPath (Path& path) const throw();
  29017. /** Looks for a glyph that contains the given co-ordinate.
  29018. @returns the index of the glyph, or -1 if none were found.
  29019. */
  29020. int findGlyphIndexAt (float x, float y) const throw();
  29021. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  29022. @param startIndex the first glyph to test
  29023. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  29024. startIndex will be included
  29025. @param left on return, the leftmost co-ordinate of the rectangle
  29026. @param top on return, the top co-ordinate of the rectangle
  29027. @param right on return, the rightmost co-ordinate of the rectangle
  29028. @param bottom on return, the bottom co-ordinate of the rectangle
  29029. @param includeWhitespace if true, the extent of any whitespace characters will also
  29030. be taken into account
  29031. */
  29032. void getBoundingBox (int startIndex,
  29033. int numGlyphs,
  29034. float& left,
  29035. float& top,
  29036. float& right,
  29037. float& bottom,
  29038. const bool includeWhitespace) const throw();
  29039. /** Shifts a set of glyphs by a given amount.
  29040. @param startIndex the first glyph to transform
  29041. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  29042. startIndex will be used
  29043. @param deltaX the amount to add to their x-positions
  29044. @param deltaY the amount to add to their y-positions
  29045. */
  29046. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  29047. const float deltaX,
  29048. const float deltaY) throw();
  29049. /** Removes a set of glyphs from the arrangement.
  29050. @param startIndex the first glyph to remove
  29051. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  29052. startIndex will be deleted
  29053. */
  29054. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  29055. /** Expands or compresses a set of glyphs horizontally.
  29056. @param startIndex the first glyph to transform
  29057. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  29058. startIndex will be used
  29059. @param horizontalScaleFactor how much to scale their horizontal width by
  29060. */
  29061. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  29062. const float horizontalScaleFactor) throw();
  29063. /** Justifies a set of glyphs within a given space.
  29064. This moves the glyphs as a block so that the whole thing is located within the
  29065. given rectangle with the specified layout.
  29066. If the Justification::horizontallyJustified flag is specified, each line will
  29067. be stretched out to fill the specified width.
  29068. */
  29069. void justifyGlyphs (const int startIndex, const int numGlyphs,
  29070. const float x,
  29071. const float y,
  29072. const float width,
  29073. const float height,
  29074. const Justification& justification) throw();
  29075. juce_UseDebuggingNewOperator
  29076. private:
  29077. int numGlyphs, numAllocated;
  29078. PositionedGlyph* glyphs;
  29079. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  29080. void removeLast() throw();
  29081. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  29082. void incGlyphRefCount (const int index) const throw();
  29083. void decGlyphRefCount (const int index) const throw();
  29084. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  29085. };
  29086. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29087. /********* End of inlined file: juce_GlyphArrangement.h *********/
  29088. #endif
  29089. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29090. /********* Start of inlined file: juce_TextLayout.h *********/
  29091. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29092. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  29093. class Graphics;
  29094. /**
  29095. A laid-out arrangement of text.
  29096. You can add text in different fonts to a TextLayout object, then call its
  29097. layout() method to word-wrap it into lines. The layout can then be drawn
  29098. using a graphics context.
  29099. It's handy if you've got a message to display, because you can format it,
  29100. measure the extent of the layout, and then create a suitably-sized window
  29101. to show it in.
  29102. @see Font, Graphics::drawFittedText, GlyphArrangement
  29103. */
  29104. class JUCE_API TextLayout
  29105. {
  29106. public:
  29107. /** Creates an empty text layout.
  29108. Text can then be appended using the appendText() method.
  29109. */
  29110. TextLayout() throw();
  29111. /** Creates a copy of another layout object. */
  29112. TextLayout (const TextLayout& other) throw();
  29113. /** Creates a text layout from an initial string and font. */
  29114. TextLayout (const String& text, const Font& font) throw();
  29115. /** Destructor. */
  29116. ~TextLayout() throw();
  29117. /** Copies another layout onto this one. */
  29118. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  29119. /** Clears the layout, removing all its text. */
  29120. void clear() throw();
  29121. /** Adds a string to the end of the arrangement.
  29122. The string will be broken onto new lines wherever it contains
  29123. carriage-returns or linefeeds. After adding it, you can call layout()
  29124. to wrap long lines into a paragraph and justify it.
  29125. */
  29126. void appendText (const String& textToAppend,
  29127. const Font& fontToUse) throw();
  29128. /** Replaces all the text with a new string.
  29129. This is equivalent to calling clear() followed by appendText().
  29130. */
  29131. void setText (const String& newText,
  29132. const Font& fontToUse) throw();
  29133. /** Breaks the text up to form a paragraph with the given width.
  29134. @param maximumWidth any text wider than this will be split
  29135. across multiple lines
  29136. @param justification how the lines are to be laid-out horizontally
  29137. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29138. width that keeps all the lines of text at a
  29139. similar length - this is good when you're displaying
  29140. a short message and don't want it to get split
  29141. onto two lines with only a couple of words on
  29142. the second line, which looks untidy.
  29143. */
  29144. void layout (int maximumWidth,
  29145. const Justification& justification,
  29146. const bool attemptToBalanceLineLengths) throw();
  29147. /** Returns the overall width of the entire text layout. */
  29148. int getWidth() const throw();
  29149. /** Returns the overall height of the entire text layout. */
  29150. int getHeight() const throw();
  29151. /** Returns the total number of lines of text. */
  29152. int getNumLines() const throw() { return totalLines; }
  29153. /** Returns the width of a particular line of text.
  29154. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29155. */
  29156. int getLineWidth (const int lineNumber) const throw();
  29157. /** Renders the text at a specified position using a graphics context.
  29158. */
  29159. void draw (Graphics& g,
  29160. const int topLeftX,
  29161. const int topLeftY) const throw();
  29162. /** Renders the text within a specified rectangle using a graphics context.
  29163. The justification flags dictate how the block of text should be positioned
  29164. within the rectangle.
  29165. */
  29166. void drawWithin (Graphics& g,
  29167. int x, int y, int w, int h,
  29168. const Justification& layoutFlags) const throw();
  29169. juce_UseDebuggingNewOperator
  29170. private:
  29171. VoidArray tokens;
  29172. int totalLines;
  29173. };
  29174. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29175. /********* End of inlined file: juce_TextLayout.h *********/
  29176. #endif
  29177. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29178. #endif
  29179. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29180. /********* Start of inlined file: juce_EdgeTable.h *********/
  29181. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29182. #define __JUCE_EDGETABLE_JUCEHEADER__
  29183. class Path;
  29184. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  29185. /**
  29186. A table of horizontal scan-line segments - used for rasterising Paths.
  29187. @see Path, Graphics
  29188. */
  29189. class JUCE_API EdgeTable
  29190. {
  29191. public:
  29192. /** Indicates the quality at which the edge table should be generated.
  29193. Higher values will have better quality anti-aliasing, but will take
  29194. longer to generate the edge table and to render it.
  29195. */
  29196. enum OversamplingLevel
  29197. {
  29198. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  29199. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  29200. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  29201. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  29202. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  29203. normal user-interface use. */
  29204. };
  29205. /** Creates an empty edge table ready to have paths added.
  29206. A table is created with a fixed vertical size, and only sections of paths
  29207. which lie within their range will be added to the table.
  29208. @param topY the lowest y co-ordinate that the table can contain
  29209. @param height the number of horizontal lines it can contain
  29210. @param verticalOversampling the amount of oversampling used for anti-aliasing
  29211. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  29212. worth changing this except for very special purposes
  29213. */
  29214. EdgeTable (const int topY,
  29215. const int height,
  29216. const OversamplingLevel verticalOversampling = Oversampling_4times,
  29217. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  29218. /** Creates a copy of another edge table. */
  29219. EdgeTable (const EdgeTable& other) throw();
  29220. /** Copies from another edge table. */
  29221. const EdgeTable& operator= (const EdgeTable& other) throw();
  29222. /** Destructor. */
  29223. ~EdgeTable() throw();
  29224. /** Adds edges to the table for a path.
  29225. This will add horizontal lines to the edge table for any parts of the path
  29226. which lie within the vertical bounds for which this table was created.
  29227. @param path the path to add
  29228. @param transform an optional transform to apply to the path while it's
  29229. being added
  29230. */
  29231. void addPath (const Path& path,
  29232. const AffineTransform& transform) throw();
  29233. /** Reduces the amount of space the table has allocated.
  29234. This will shrink the table down to use as little memory as possible - useful for
  29235. read-only tables that get stored and re-used for rendering.
  29236. */
  29237. void optimiseTable() throw();
  29238. /** Iterates the lines in the table, for rendering.
  29239. This function will iterate each line in the table, and call a user-defined class
  29240. to render each pixel or continuous line of pixels that the table contains.
  29241. @param iterationCallback this templated class must contain the following methods:
  29242. @code
  29243. inline void setEdgeTableYPos (int y);
  29244. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  29245. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  29246. @endcode
  29247. (these don't necessarily have to be 'const', but it might help it go faster)
  29248. @param clipLeft the left-hand edge of the rectangle which should be iterated
  29249. @param clipTop the top edge of the rectangle which should be iterated
  29250. @param clipRight the right-hand edge of the rectangle which should be iterated
  29251. @param clipBottom the bottom edge of the rectangle which should be iterated
  29252. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  29253. */
  29254. template <class EdgeTableIterationCallback>
  29255. void iterate (EdgeTableIterationCallback& iterationCallback,
  29256. const int clipLeft,
  29257. int clipTop,
  29258. const int clipRight,
  29259. int clipBottom,
  29260. const int subPixelXOffset) const
  29261. {
  29262. if (clipTop < top)
  29263. clipTop = top;
  29264. if (clipBottom > top + height)
  29265. clipBottom = top + height;
  29266. const int* singleLine = table + lineStrideElements
  29267. * ((clipTop - top) << (int) oversampling);
  29268. int mergedLineAllocation = 128;
  29269. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  29270. int* mergedLine = (int*) temp.getData();
  29271. const int timesOverSampling = 1 << (int) oversampling;
  29272. for (int y = clipTop; y < clipBottom; ++y)
  29273. {
  29274. int numMergedPoints = 0;
  29275. // sort all the oversampled lines into a single merged line ready to draw..
  29276. for (int over = timesOverSampling; --over >= 0;)
  29277. {
  29278. const int* l = singleLine;
  29279. singleLine += lineStrideElements;
  29280. int num = *l;
  29281. jassert (num >= 0);
  29282. if (num > 0)
  29283. {
  29284. if (numMergedPoints + num >= mergedLineAllocation)
  29285. {
  29286. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  29287. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  29288. mergedLine = (int*) temp.getData();
  29289. }
  29290. while (--num >= 0)
  29291. {
  29292. const int x = *++l;
  29293. const int winding = *++l;
  29294. int n = numMergedPoints << 1;
  29295. while (n > 0)
  29296. {
  29297. const int cx = mergedLine [n - 2];
  29298. if (cx <= x)
  29299. break;
  29300. mergedLine [n] = cx;
  29301. --n;
  29302. mergedLine [n + 2] = mergedLine [n];
  29303. --n;
  29304. }
  29305. mergedLine [n] = x;
  29306. mergedLine [n + 1] = winding;
  29307. ++numMergedPoints;
  29308. }
  29309. }
  29310. }
  29311. if (--numMergedPoints > 0)
  29312. {
  29313. const int* line = mergedLine;
  29314. int x = subPixelXOffset + *line;
  29315. int level = *++line;
  29316. int levelAccumulator = 0;
  29317. iterationCallback.setEdgeTableYPos (y);
  29318. while (--numMergedPoints >= 0)
  29319. {
  29320. const int endX = subPixelXOffset + *++line;
  29321. jassert (endX >= x);
  29322. const int absLevel = abs (level);
  29323. int endOfRun = (endX >> 8);
  29324. if (endOfRun == (x >> 8))
  29325. {
  29326. // small segment within the same pixel, so just save it for the next
  29327. // time round..
  29328. levelAccumulator += (endX - x) * absLevel;
  29329. }
  29330. else
  29331. {
  29332. // plot the fist pixel of this segment, including any accumulated
  29333. // levels from smaller segments that haven't been drawn yet
  29334. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  29335. levelAccumulator >>= 8;
  29336. if (levelAccumulator > 0xff)
  29337. levelAccumulator = 0xff;
  29338. x >>= 8;
  29339. if (x >= clipRight)
  29340. {
  29341. levelAccumulator = 0;
  29342. break;
  29343. }
  29344. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  29345. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29346. if (++x >= clipRight)
  29347. {
  29348. levelAccumulator = 0;
  29349. break;
  29350. }
  29351. // if there's a segment of solid pixels, do it all in one go..
  29352. if (absLevel > 0 && endOfRun > x)
  29353. {
  29354. if (x < clipLeft)
  29355. x = clipLeft;
  29356. if (endOfRun > clipRight)
  29357. endOfRun = clipRight;
  29358. const int numPix = endOfRun - x;
  29359. if (numPix > 0)
  29360. iterationCallback.handleEdgeTableLine (x, numPix,
  29361. jmin (absLevel, 0xff));
  29362. }
  29363. // save the bit at the end to be drawn next time round the loop.
  29364. levelAccumulator = (endX & 0xff) * absLevel;
  29365. }
  29366. level += *++line;
  29367. x = endX;
  29368. }
  29369. if (levelAccumulator > 0)
  29370. {
  29371. levelAccumulator >>= 8;
  29372. if (levelAccumulator > 0xff)
  29373. levelAccumulator = 0xff;
  29374. x >>= 8;
  29375. if (x >= clipLeft && x < clipRight)
  29376. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29377. }
  29378. }
  29379. }
  29380. }
  29381. juce_UseDebuggingNewOperator
  29382. private:
  29383. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29384. int* table;
  29385. int top, height, maxEdgesPerLine, lineStrideElements;
  29386. OversamplingLevel oversampling;
  29387. // this will assume that the y co-ord is within bounds, and will avoid checking
  29388. // this for speed.
  29389. void addEdgePoint (const int x, const int y, const int winding) throw();
  29390. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29391. };
  29392. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29393. /********* End of inlined file: juce_EdgeTable.h *********/
  29394. #endif
  29395. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29396. #endif
  29397. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29398. #endif
  29399. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29400. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29401. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29402. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29403. /**
  29404. Interface class for graphics context objects, used internally by the Graphics class.
  29405. Users are not supposed to create instances of this class directly - do your drawing
  29406. via the Graphics object instead.
  29407. It's a base class for different types of graphics context, that may perform software-based
  29408. or OS-accelerated rendering.
  29409. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29410. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29411. context.
  29412. */
  29413. class JUCE_API LowLevelGraphicsContext
  29414. {
  29415. protected:
  29416. LowLevelGraphicsContext();
  29417. public:
  29418. virtual ~LowLevelGraphicsContext();
  29419. /** Returns true if this device is vector-based, e.g. a printer. */
  29420. virtual bool isVectorDevice() const = 0;
  29421. /** Moves the origin to a new position.
  29422. The co-ords are relative to the current origin, and indicate the new position
  29423. of (0, 0).
  29424. */
  29425. virtual void setOrigin (int x, int y) = 0;
  29426. /** Cliping co-ords are relative to the origin. */
  29427. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29428. /** Cliping co-ords are relative to the origin. */
  29429. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29430. /** Cliping co-ords are relative to the origin. */
  29431. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29432. virtual void saveState() = 0;
  29433. virtual void restoreState() = 0;
  29434. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29435. virtual const Rectangle getClipBounds() const = 0;
  29436. virtual bool isClipEmpty() const = 0;
  29437. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29438. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29439. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29440. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29441. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29442. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29443. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29444. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29445. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29446. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29447. virtual void blendImage (const Image& sourceImage,
  29448. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29449. float alpha) = 0;
  29450. virtual void blendImageRescaling (const Image& sourceImage,
  29451. int destX, int destY, int destW, int destH,
  29452. int sourceX, int sourceY, int sourceW, int sourceH,
  29453. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29454. virtual void blendImageWarping (const Image& sourceImage,
  29455. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29456. const AffineTransform& transform,
  29457. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29458. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29459. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29460. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29461. };
  29462. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29463. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29464. #endif
  29465. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29466. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29467. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29468. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29469. /**
  29470. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29471. into a PostScript document.
  29472. */
  29473. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29474. {
  29475. public:
  29476. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29477. const String& documentTitle,
  29478. const int totalWidth,
  29479. const int totalHeight);
  29480. ~LowLevelGraphicsPostScriptRenderer();
  29481. bool isVectorDevice() const;
  29482. void setOrigin (int x, int y);
  29483. bool reduceClipRegion (int x, int y, int w, int h);
  29484. bool reduceClipRegion (const RectangleList& clipRegion);
  29485. void excludeClipRegion (int x, int y, int w, int h);
  29486. void saveState();
  29487. void restoreState();
  29488. bool clipRegionIntersects (int x, int y, int w, int h);
  29489. const Rectangle getClipBounds() const;
  29490. bool isClipEmpty() const;
  29491. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29492. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29493. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29494. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29495. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29496. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29497. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29498. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29499. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29500. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29501. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29502. int sourceX, int sourceY, float alpha);
  29503. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29504. int sourceX, int sourceY, int sourceW, int sourceH,
  29505. float alpha, const Graphics::ResamplingQuality quality);
  29506. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29507. const AffineTransform& transform,
  29508. float alpha, const Graphics::ResamplingQuality quality);
  29509. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29510. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29511. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29512. juce_UseDebuggingNewOperator
  29513. protected:
  29514. OutputStream& out;
  29515. RectangleList* clip;
  29516. int totalWidth, totalHeight, xOffset, yOffset;
  29517. bool needToClip;
  29518. Colour lastColour;
  29519. struct SavedState
  29520. {
  29521. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29522. ~SavedState();
  29523. RectangleList* clip;
  29524. const int xOffset, yOffset;
  29525. private:
  29526. SavedState (const SavedState&);
  29527. const SavedState& operator= (const SavedState&);
  29528. };
  29529. OwnedArray <SavedState> stateStack;
  29530. void writeClip();
  29531. void writeColour (const Colour& colour);
  29532. void writePath (const Path& path) const;
  29533. void writeXY (const float x, const float y) const;
  29534. void writeTransform (const AffineTransform& trans) const;
  29535. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29536. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29537. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29538. };
  29539. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29540. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29541. #endif
  29542. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29543. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29544. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29545. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29546. /**
  29547. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29548. its rendering in memory.
  29549. User code is not supposed to create instances of this class directly - do all your
  29550. rendering via the Graphics class instead.
  29551. */
  29552. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29553. {
  29554. public:
  29555. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29556. ~LowLevelGraphicsSoftwareRenderer();
  29557. bool isVectorDevice() const;
  29558. void setOrigin (int x, int y);
  29559. bool reduceClipRegion (int x, int y, int w, int h);
  29560. bool reduceClipRegion (const RectangleList& clipRegion);
  29561. void excludeClipRegion (int x, int y, int w, int h);
  29562. void saveState();
  29563. void restoreState();
  29564. bool clipRegionIntersects (int x, int y, int w, int h);
  29565. const Rectangle getClipBounds() const;
  29566. bool isClipEmpty() const;
  29567. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29568. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29569. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29570. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29571. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29572. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29573. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29574. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29575. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29576. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29577. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29578. int sourceX, int sourceY, float alpha);
  29579. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29580. int sourceX, int sourceY, int sourceW, int sourceH,
  29581. float alpha, const Graphics::ResamplingQuality quality);
  29582. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29583. const AffineTransform& transform,
  29584. float alpha, const Graphics::ResamplingQuality quality);
  29585. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29586. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29587. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29588. RectangleList* getRawClipRegion() throw() { return clip; }
  29589. juce_UseDebuggingNewOperator
  29590. protected:
  29591. Image& image;
  29592. RectangleList* clip;
  29593. int xOffset, yOffset;
  29594. struct SavedState
  29595. {
  29596. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29597. ~SavedState();
  29598. RectangleList* clip;
  29599. const int xOffset, yOffset;
  29600. private:
  29601. SavedState (const SavedState&);
  29602. const SavedState& operator= (const SavedState&);
  29603. };
  29604. OwnedArray <SavedState> stateStack;
  29605. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29606. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29607. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29608. const Path& path, const AffineTransform& transform,
  29609. int& x, int& y, int& w, int& h) const;
  29610. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29611. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29612. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29613. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29614. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29615. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29616. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29617. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29618. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29619. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29620. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29621. float alpha);
  29622. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29623. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29624. const AffineTransform& transform,
  29625. float alpha, const Graphics::ResamplingQuality quality);
  29626. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29627. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29628. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29629. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29630. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29631. };
  29632. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29633. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29634. #endif
  29635. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29636. #endif
  29637. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29638. #endif
  29639. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29640. #endif
  29641. #ifndef __JUCE_LINE_JUCEHEADER__
  29642. #endif
  29643. #ifndef __JUCE_PATH_JUCEHEADER__
  29644. #endif
  29645. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29646. /********* Start of inlined file: juce_PathIterator.h *********/
  29647. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29648. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29649. /**
  29650. Flattens a Path object into a series of straight-line sections.
  29651. Use one of these to iterate through a Path object, and it will convert
  29652. all the curves into line sections so it's easy to render or perform
  29653. geometric operations on.
  29654. @see Path
  29655. */
  29656. class JUCE_API PathFlatteningIterator
  29657. {
  29658. public:
  29659. /** Creates a PathFlatteningIterator.
  29660. After creation, use the next() method to initialise the fields in the
  29661. object with the first line's position.
  29662. @param path the path to iterate along
  29663. @param transform a transform to apply to each point in the path being iterated
  29664. @param tolerence the amount by which the curves are allowed to deviate from the
  29665. lines into which they are being broken down - a higher tolerence
  29666. is a bit faster, but less smooth.
  29667. */
  29668. PathFlatteningIterator (const Path& path,
  29669. const AffineTransform& transform = AffineTransform::identity,
  29670. float tolerence = 9.0f) throw();
  29671. /** Destructor. */
  29672. ~PathFlatteningIterator() throw();
  29673. /** Fetches the next line segment from the path.
  29674. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29675. so that they describe the new line segment.
  29676. @returns false when there are no more lines to fetch.
  29677. */
  29678. bool next() throw();
  29679. /** The x position of the start of the current line segment. */
  29680. float x1;
  29681. /** The y position of the start of the current line segment. */
  29682. float y1;
  29683. /** The x position of the end of the current line segment. */
  29684. float x2;
  29685. /** The y position of the end of the current line segment. */
  29686. float y2;
  29687. /** Indicates whether the current line segment is closing a sub-path.
  29688. If the current line is the one that connects the end of a sub-path
  29689. back to the start again, this will be true.
  29690. */
  29691. bool closesSubPath;
  29692. /** The index of the current line within the current sub-path.
  29693. E.g. you can use this to see whether the line is the first one in the
  29694. subpath by seeing if it's 0.
  29695. */
  29696. int subPathIndex;
  29697. /** Returns true if the current segment is the last in the current sub-path. */
  29698. bool isLastInSubpath() const throw() { return stackPos == stackBase
  29699. && (index >= path.numElements
  29700. || points [index] == Path::moveMarker); }
  29701. juce_UseDebuggingNewOperator
  29702. private:
  29703. const Path& path;
  29704. const AffineTransform transform;
  29705. float* points;
  29706. float tolerence, subPathCloseX, subPathCloseY;
  29707. bool isIdentityTransform;
  29708. float* stackBase;
  29709. float* stackPos;
  29710. int index, stackSize;
  29711. PathFlatteningIterator (const PathFlatteningIterator&);
  29712. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29713. };
  29714. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29715. /********* End of inlined file: juce_PathIterator.h *********/
  29716. #endif
  29717. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29718. #endif
  29719. #ifndef __JUCE_POINT_JUCEHEADER__
  29720. #endif
  29721. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29722. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29723. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29724. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29725. /**
  29726. A rectangle whose co-ordinates can be defined in terms of absolute or
  29727. proportional distances.
  29728. Designed mainly for storing component positions, this gives you a lot of
  29729. control over how each co-ordinate is stored, either as an absolute position,
  29730. or as a proportion of the size of a parent rectangle.
  29731. It also allows you to define the anchor points by which the rectangle is
  29732. positioned, so for example you could specify that the top right of the
  29733. rectangle should be an absolute distance from its parent's bottom-right corner.
  29734. This object can be stored as a string, which takes the form "x y w h", including
  29735. symbols like '%' and letters to indicate the anchor point. See its toString()
  29736. method for more info.
  29737. Example usage:
  29738. @code
  29739. class MyComponent
  29740. {
  29741. void resized()
  29742. {
  29743. // this will set the child component's x to be 20% of our width, its y
  29744. // to be 30, its width to be 150, and its height to be 50% of our
  29745. // height..
  29746. const PositionedRectangle pos1 ("20% 30 150 50%");
  29747. pos1.applyToComponent (*myChildComponent1);
  29748. // this will inset the child component with a gap of 10 pixels
  29749. // around each of its edges..
  29750. const PositionedRectangle pos2 ("10 10 20M 20M");
  29751. pos2.applyToComponent (*myChildComponent2);
  29752. }
  29753. };
  29754. @endcode
  29755. */
  29756. class JUCE_API PositionedRectangle
  29757. {
  29758. public:
  29759. /** Creates an empty rectangle with all co-ordinates set to zero.
  29760. The default anchor point is top-left; the default
  29761. */
  29762. PositionedRectangle() throw();
  29763. /** Initialises a PositionedRectangle from a saved string version.
  29764. The string must be in the format generated by toString().
  29765. */
  29766. PositionedRectangle (const String& stringVersion) throw();
  29767. /** Creates a copy of another PositionedRectangle. */
  29768. PositionedRectangle (const PositionedRectangle& other) throw();
  29769. /** Copies another PositionedRectangle. */
  29770. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29771. /** Destructor. */
  29772. ~PositionedRectangle() throw();
  29773. /** Returns a string version of this position, from which it can later be
  29774. re-generated.
  29775. The format is four co-ordinates, "x y w h".
  29776. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29777. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29778. as a percentage, e.g. "80%".
  29779. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29780. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29781. the parent's right-hand edge.
  29782. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29783. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29784. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29785. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29786. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29787. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29788. has "c" appended to it. So "-50Rc" would mean that this component's
  29789. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29790. this component's centre should be placed 40% across the parent's width.
  29791. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29792. the number has "M" appended to it.
  29793. To reload a stored string, use the constructor that takes a string parameter.
  29794. */
  29795. const String toString() const throw();
  29796. /** Calculates the absolute position, given the size of the space that
  29797. it should go in.
  29798. This will work out any proportional distances and sizes relative to the
  29799. target rectangle, and will return the absolute position.
  29800. @see applyToComponent
  29801. */
  29802. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29803. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29804. */
  29805. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29806. double& x,
  29807. double& y,
  29808. double& width,
  29809. double& height) const throw();
  29810. /** This sets the bounds of the given component to this position.
  29811. This is equivalent to writing:
  29812. @code
  29813. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29814. @endcode
  29815. @see getRectangle, updateFromComponent
  29816. */
  29817. void applyToComponent (Component& comp) const throw();
  29818. /** Updates this object's co-ordinates to match the given rectangle.
  29819. This will set all co-ordinates based on the given rectangle, re-calculating
  29820. any proportional distances, and using the current anchor points.
  29821. So for example if the x co-ordinate mode is currently proportional, this will
  29822. re-calculate x based on the rectangle's relative position within the target
  29823. rectangle's width.
  29824. If the target rectangle's width or height are zero then it may not be possible
  29825. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29826. will not be changed.
  29827. */
  29828. void updateFrom (const Rectangle& newPosition,
  29829. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29830. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29831. */
  29832. void updateFromDouble (const double x, const double y,
  29833. const double width, const double height,
  29834. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29835. /** Updates this object's co-ordinates to match the bounds of this component.
  29836. This is equivalent to calling updateFrom() with the component's bounds and
  29837. it parent size.
  29838. If the component doesn't currently have a parent, then proportional co-ordinates
  29839. might not be updated because it would need to know the parent's size to do the
  29840. maths for this.
  29841. */
  29842. void updateFromComponent (const Component& comp) throw();
  29843. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29844. enum AnchorPoint
  29845. {
  29846. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29847. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29848. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29849. };
  29850. /** Specifies how an x or y co-ordinate should be interpreted. */
  29851. enum PositionMode
  29852. {
  29853. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29854. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29855. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29856. 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. */
  29857. };
  29858. /** Specifies how the width or height should be interpreted. */
  29859. enum SizeMode
  29860. {
  29861. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29862. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29863. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29864. };
  29865. /** Sets all options for all co-ordinates.
  29866. This requires a reference rectangle to be specified, because if you're changing any
  29867. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29868. the co-ordinates, and will need to know the parent size so it can calculate this.
  29869. */
  29870. void setModes (const AnchorPoint xAnchorMode,
  29871. const PositionMode xPositionMode,
  29872. const AnchorPoint yAnchorMode,
  29873. const PositionMode yPositionMode,
  29874. const SizeMode widthMode,
  29875. const SizeMode heightMode,
  29876. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29877. /** Returns the anchoring mode for the x co-ordinate.
  29878. To change any of the modes, use setModes().
  29879. */
  29880. AnchorPoint getAnchorPointX() const throw();
  29881. /** Returns the positioning mode for the x co-ordinate.
  29882. To change any of the modes, use setModes().
  29883. */
  29884. PositionMode getPositionModeX() const throw();
  29885. /** Returns the raw x co-ordinate.
  29886. If the x position mode is absolute, then this will be the absolute value. If it's
  29887. proportional, then this will be a fractional proportion, where 1.0 means the full
  29888. width of the parent space.
  29889. */
  29890. double getX() const throw() { return x; }
  29891. /** Sets the raw value of the x co-ordinate.
  29892. See getX() for the meaning of this value.
  29893. */
  29894. void setX (const double newX) throw() { x = newX; }
  29895. /** Returns the anchoring mode for the y co-ordinate.
  29896. To change any of the modes, use setModes().
  29897. */
  29898. AnchorPoint getAnchorPointY() const throw();
  29899. /** Returns the positioning mode for the y co-ordinate.
  29900. To change any of the modes, use setModes().
  29901. */
  29902. PositionMode getPositionModeY() const throw();
  29903. /** Returns the raw y co-ordinate.
  29904. If the y position mode is absolute, then this will be the absolute value. If it's
  29905. proportional, then this will be a fractional proportion, where 1.0 means the full
  29906. height of the parent space.
  29907. */
  29908. double getY() const throw() { return y; }
  29909. /** Sets the raw value of the y co-ordinate.
  29910. See getY() for the meaning of this value.
  29911. */
  29912. void setY (const double newY) throw() { y = newY; }
  29913. /** Returns the mode used to calculate the width.
  29914. To change any of the modes, use setModes().
  29915. */
  29916. SizeMode getWidthMode() const throw();
  29917. /** Returns the raw width value.
  29918. If the width mode is absolute, then this will be the absolute value. If the mode is
  29919. proportional, then this will be a fractional proportion, where 1.0 means the full
  29920. width of the parent space.
  29921. */
  29922. double getWidth() const throw() { return w; }
  29923. /** Sets the raw width value.
  29924. See getWidth() for the details about what this value means.
  29925. */
  29926. void setWidth (const double newWidth) throw() { w = newWidth; }
  29927. /** Returns the mode used to calculate the height.
  29928. To change any of the modes, use setModes().
  29929. */
  29930. SizeMode getHeightMode() const throw();
  29931. /** Returns the raw height value.
  29932. If the height mode is absolute, then this will be the absolute value. If the mode is
  29933. proportional, then this will be a fractional proportion, where 1.0 means the full
  29934. height of the parent space.
  29935. */
  29936. double getHeight() const throw() { return h; }
  29937. /** Sets the raw height value.
  29938. See getHeight() for the details about what this value means.
  29939. */
  29940. void setHeight (const double newHeight) throw() { h = newHeight; }
  29941. /** If the size and position are constance, and wouldn't be affected by changes
  29942. in the parent's size, then this will return true.
  29943. */
  29944. bool isPositionAbsolute() const throw();
  29945. /** Compares two objects. */
  29946. const bool operator== (const PositionedRectangle& other) const throw();
  29947. /** Compares two objects. */
  29948. const bool operator!= (const PositionedRectangle& other) const throw();
  29949. juce_UseDebuggingNewOperator
  29950. private:
  29951. double x, y, w, h;
  29952. uint8 xMode, yMode, wMode, hMode;
  29953. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  29954. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  29955. void decodePosString (const String& s, uint8& mode, double& value) throw();
  29956. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  29957. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  29958. const uint8 xMode, const uint8 wMode,
  29959. const int parentPos, const int parentSize) const throw();
  29960. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  29961. const uint8 xMode, const uint8 wMode,
  29962. const int parentPos, const int parentSize) const throw();
  29963. };
  29964. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29965. /********* End of inlined file: juce_PositionedRectangle.h *********/
  29966. #endif
  29967. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29968. #endif
  29969. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  29970. #endif
  29971. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29972. #endif
  29973. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29974. /********* Start of inlined file: juce_ImageCache.h *********/
  29975. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29976. #define __JUCE_IMAGECACHE_JUCEHEADER__
  29977. /**
  29978. A global cache of images that have been loaded from files or memory.
  29979. If you're loading an image and may need to use the image in more than one
  29980. place, this is used to allow the same image to be shared rather than loading
  29981. multiple copies into memory.
  29982. Another advantage is that after images are released, they will be kept in
  29983. memory for a few seconds before it is actually deleted, so if you're repeatedly
  29984. loading/deleting the same image, it'll reduce the chances of having to reload it
  29985. each time.
  29986. @see Image, ImageFileFormat
  29987. */
  29988. class JUCE_API ImageCache : private DeletedAtShutdown,
  29989. private Timer
  29990. {
  29991. public:
  29992. /** Loads an image from a file, (or just returns the image if it's already cached).
  29993. If the cache already contains an image that was loaded from this file,
  29994. that image will be returned. Otherwise, this method will try to load the
  29995. file, add it to the cache, and return it.
  29996. It's very important not to delete the image that is returned - instead use
  29997. the ImageCache::release() method.
  29998. Also, remember that the image returned is shared, so drawing into it might
  29999. affect other things that are using it!
  30000. @param file the file to try to load
  30001. @returns the image, or null if it there was an error loading it
  30002. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30003. */
  30004. static Image* getFromFile (const File& file);
  30005. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  30006. If the cache already contains an image that was loaded from this block of memory,
  30007. that image will be returned. Otherwise, this method will try to load the
  30008. file, add it to the cache, and return it.
  30009. It's very important not to delete the image that is returned - instead use
  30010. the ImageCache::release() method.
  30011. Also, remember that the image returned is shared, so drawing into it might
  30012. affect other things that are using it!
  30013. @param imageData the block of memory containing the image data
  30014. @param dataSize the data size in bytes
  30015. @returns the image, or null if it there was an error loading it
  30016. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30017. */
  30018. static Image* getFromMemory (const void* imageData,
  30019. const int dataSize);
  30020. /** Releases an image that was previously created by the ImageCache.
  30021. If an image has been returned by the getFromFile() or getFromMemory() methods,
  30022. it mustn't be deleted directly, but should be released with this method
  30023. instead.
  30024. @see getFromFile, getFromMemory
  30025. */
  30026. static void release (Image* const imageToRelease);
  30027. /** Checks whether an image is in the cache or not.
  30028. @returns true if the image is currently in the cache
  30029. */
  30030. static bool isImageInCache (Image* const imageToLookFor);
  30031. /** Increments the reference-count for a cached image.
  30032. If the image isn't in the cache, this method won't do anything.
  30033. */
  30034. static void incReferenceCount (Image* const image);
  30035. /** Checks the cache for an image with a particular hashcode.
  30036. If there's an image in the cache with this hashcode, it will be returned,
  30037. otherwise it will return zero.
  30038. If an image is returned, it must be released with the release() method
  30039. when no longer needed, to maintain the correct reference counts.
  30040. @param hashCode the hash code that would have been associated with the
  30041. image by addImageToCache()
  30042. @see addImageToCache
  30043. */
  30044. static Image* getFromHashCode (const int64 hashCode);
  30045. /** Adds an image to the cache with a user-defined hash-code.
  30046. After calling this, responsibilty for deleting the image will be taken
  30047. by the ImageCache.
  30048. The image will be initially be given a reference count of 1, so call
  30049. the release() method to delete it.
  30050. @param image the image to add
  30051. @param hashCode the hash-code to associate with it
  30052. @see getFromHashCode
  30053. */
  30054. static void addImageToCache (Image* const image,
  30055. const int64 hashCode);
  30056. /** Changes the amount of time before an unused image will be removed from the cache.
  30057. By default this is about 5 seconds.
  30058. */
  30059. static void setCacheTimeout (const int millisecs);
  30060. juce_UseDebuggingNewOperator
  30061. private:
  30062. CriticalSection lock;
  30063. VoidArray images;
  30064. ImageCache() throw();
  30065. ImageCache (const ImageCache&);
  30066. const ImageCache& operator= (const ImageCache&);
  30067. ~ImageCache();
  30068. void timerCallback();
  30069. };
  30070. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  30071. /********* End of inlined file: juce_ImageCache.h *********/
  30072. #endif
  30073. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30074. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  30075. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30076. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30077. /**
  30078. Represents a filter kernel to use in convoluting an image.
  30079. @see Image::applyConvolution
  30080. */
  30081. class JUCE_API ImageConvolutionKernel
  30082. {
  30083. public:
  30084. /** Creates an empty convulution kernel.
  30085. @param size the length of each dimension of the kernel, so e.g. if the size
  30086. is 5, it will create a 5x5 kernel
  30087. */
  30088. ImageConvolutionKernel (const int size) throw();
  30089. /** Destructor. */
  30090. ~ImageConvolutionKernel() throw();
  30091. /** Resets all values in the kernel to zero.
  30092. */
  30093. void clear() throw();
  30094. /** Sets the value of a specific cell in the kernel.
  30095. The x and y parameters must be in the range 0 < x < getKernelSize().
  30096. @see setOverallSum
  30097. */
  30098. void setKernelValue (const int x,
  30099. const int y,
  30100. const float value) throw();
  30101. /** Rescales all values in the kernel to make the total add up to a fixed value.
  30102. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  30103. */
  30104. void setOverallSum (const float desiredTotalSum) throw();
  30105. /** Multiplies all values in the kernel by a value. */
  30106. void rescaleAllValues (const float multiplier) throw();
  30107. /** Intialises the kernel for a gaussian blur.
  30108. @param blurRadius this may be larger or smaller than the kernel's actual
  30109. size but this will obviously be wasteful or clip at the
  30110. edges. Ideally the kernel should be just larger than
  30111. (blurRadius * 2).
  30112. */
  30113. void createGaussianBlur (const float blurRadius) throw();
  30114. /** Returns the size of the kernel.
  30115. E.g. if it's a 3x3 kernel, this returns 3.
  30116. */
  30117. int getKernelSize() const throw() { return size; }
  30118. /** Returns a 2-dimensional array of the kernel's values.
  30119. The size of each dimension of the array will be getKernelSize().
  30120. */
  30121. float** getValues() const throw() { return values; }
  30122. /** Applies the kernel to an image.
  30123. @param destImage the image that will receive the resultant convoluted pixels.
  30124. @param sourceImage an optional source image to read from - if this is 0, then the
  30125. destination image will be used as the source. If an image is
  30126. specified, it must be exactly the same size and type as the destination
  30127. image.
  30128. @param x the region of the image to apply the filter to
  30129. @param y the region of the image to apply the filter to
  30130. @param width the region of the image to apply the filter to
  30131. @param height the region of the image to apply the filter to
  30132. */
  30133. void applyToImage (Image& destImage,
  30134. const Image* sourceImage,
  30135. int x,
  30136. int y,
  30137. int width,
  30138. int height) const;
  30139. juce_UseDebuggingNewOperator
  30140. private:
  30141. float** values;
  30142. int size;
  30143. // no reason not to implement these one day..
  30144. ImageConvolutionKernel (const ImageConvolutionKernel&);
  30145. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  30146. };
  30147. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30148. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  30149. #endif
  30150. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30151. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30152. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30153. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30154. /**
  30155. Base-class for codecs that can read and write image file formats such
  30156. as PNG, JPEG, etc.
  30157. This class also contains static methods to make it easy to load images
  30158. from files, streams or from memory.
  30159. @see Image, ImageCache
  30160. */
  30161. class JUCE_API ImageFileFormat
  30162. {
  30163. protected:
  30164. /** Creates an ImageFormat. */
  30165. ImageFileFormat() throw() {}
  30166. public:
  30167. /** Destructor. */
  30168. virtual ~ImageFileFormat() throw() {}
  30169. /** Returns a description of this file format.
  30170. E.g. "JPEG", "PNG"
  30171. */
  30172. virtual const String getFormatName() = 0;
  30173. /** Returns true if the given stream seems to contain data that this format
  30174. understands.
  30175. The format class should only read the first few bytes of the stream and sniff
  30176. for header bytes that it understands.
  30177. @see decodeImage
  30178. */
  30179. virtual bool canUnderstand (InputStream& input) = 0;
  30180. /** Tries to decode and return an image from the given stream.
  30181. This will be called for an image format after calling its canUnderStand() method
  30182. to see if it can handle the stream.
  30183. @param input the stream to read the data from. The stream will be positioned
  30184. at the start of the image data (but this may not necessarily
  30185. be position 0)
  30186. @returns the image that was decoded, or 0 if it fails. It's the
  30187. caller's responsibility to delete this image when no longer needed.
  30188. @see loadFrom
  30189. */
  30190. virtual Image* decodeImage (InputStream& input) = 0;
  30191. /** Attempts to write an image to a stream.
  30192. To specify extra information like encoding quality, there will be appropriate parameters
  30193. in the subclasses of the specific file types.
  30194. @returns true if it nothing went wrong.
  30195. */
  30196. virtual bool writeImageToStream (const Image& sourceImage,
  30197. OutputStream& destStream) = 0;
  30198. /** Tries the built-in decoders to see if it can find one to read this stream.
  30199. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30200. The object that is returned should not be deleted by the caller.
  30201. @see canUnderstand, decodeImage, loadFrom
  30202. */
  30203. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30204. /** Tries to load an image from a stream.
  30205. This will use the findImageFormatForStream() method to locate a suitable
  30206. codec, and use that to load the image.
  30207. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30208. caller's responsibility to delete this image when no longer needed.
  30209. */
  30210. static Image* loadFrom (InputStream& input);
  30211. /** Tries to load an image from a file.
  30212. This will use the findImageFormatForStream() method to locate a suitable
  30213. codec, and use that to load the image.
  30214. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30215. caller's responsibility to delete this image when no longer needed.
  30216. */
  30217. static Image* loadFrom (const File& file);
  30218. /** Tries to load an image from a block of raw image data.
  30219. This will use the findImageFormatForStream() method to locate a suitable
  30220. codec, and use that to load the image.
  30221. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30222. caller's responsibility to delete this image when no longer needed.
  30223. */
  30224. static Image* loadFrom (const void* rawData,
  30225. const int numBytesOfData);
  30226. };
  30227. /**
  30228. A type of ImageFileFormat for reading and writing PNG files.
  30229. @see ImageFileFormat, JPEGImageFormat
  30230. */
  30231. class PNGImageFormat : public ImageFileFormat
  30232. {
  30233. public:
  30234. PNGImageFormat() throw();
  30235. ~PNGImageFormat() throw();
  30236. const String getFormatName();
  30237. bool canUnderstand (InputStream& input);
  30238. Image* decodeImage (InputStream& input);
  30239. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30240. };
  30241. /**
  30242. A type of ImageFileFormat for reading and writing JPEG files.
  30243. @see ImageFileFormat, PNGImageFormat
  30244. */
  30245. class JPEGImageFormat : public ImageFileFormat
  30246. {
  30247. public:
  30248. JPEGImageFormat() throw();
  30249. ~JPEGImageFormat() throw();
  30250. /** Specifies the quality to be used when writing a JPEG file.
  30251. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30252. any negative value is "default" quality
  30253. */
  30254. void setQuality (const float newQuality);
  30255. const String getFormatName();
  30256. bool canUnderstand (InputStream& input);
  30257. Image* decodeImage (InputStream& input);
  30258. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30259. private:
  30260. float quality;
  30261. };
  30262. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30263. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30264. #endif
  30265. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30266. /********* Start of inlined file: juce_Drawable.h *********/
  30267. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30268. #define __JUCE_DRAWABLE_JUCEHEADER__
  30269. /**
  30270. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30271. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30272. */
  30273. class JUCE_API Drawable
  30274. {
  30275. protected:
  30276. /** The base class can't be instantiated directly.
  30277. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30278. */
  30279. Drawable();
  30280. public:
  30281. /** Destructor. */
  30282. virtual ~Drawable();
  30283. /** Creates a deep copy of this Drawable object.
  30284. Use this to create a new copy of this and any sub-objects in the tree.
  30285. */
  30286. virtual Drawable* createCopy() const = 0;
  30287. /** Renders this Drawable object.
  30288. This is the main rendering method you should call to render a Drawable.
  30289. @see drawWithin
  30290. */
  30291. virtual void draw (Graphics& g,
  30292. const AffineTransform& transform = AffineTransform::identity) const = 0;
  30293. /** Renders the Drawable at a given offset within the Graphics context.
  30294. The co-ordinates passed-in are used to translate the object relative to its own
  30295. origin before drawing it - this is basically a quick way of saying:
  30296. @code
  30297. draw (g, AffineTransform::translation (x, y)).
  30298. @endcode
  30299. */
  30300. void drawAt (Graphics& g,
  30301. const float x,
  30302. const float y) const;
  30303. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30304. changing its aspect-ratio.
  30305. The object can placed arbitrarily within the rectangle based on a Justification type,
  30306. and can either be made as big as possible, or just reduced to fit.
  30307. @param g the graphics context to render onto
  30308. @param destX top-left of the target rectangle to fit it into
  30309. @param destY top-left of the target rectangle to fit it into
  30310. @param destWidth size of the target rectangle to fit the image into
  30311. @param destHeight size of the target rectangle to fit the image into
  30312. @param placement defines the alignment and rescaling to use to fit
  30313. this object within the target rectangle.
  30314. */
  30315. void drawWithin (Graphics& g,
  30316. const int destX,
  30317. const int destY,
  30318. const int destWidth,
  30319. const int destHeight,
  30320. const RectanglePlacement& placement) const;
  30321. /** Returns the smallest rectangle that can contain this Drawable object.
  30322. Co-ordinates are relative to the object's own origin.
  30323. */
  30324. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30325. /** Returns true if the given point is somewhere inside this Drawable.
  30326. Co-ordinates are relative to the object's own origin.
  30327. */
  30328. virtual bool hitTest (float x, float y) const = 0;
  30329. /** Returns the name given to this drawable.
  30330. @see setName
  30331. */
  30332. const String& getName() const throw() { return name; }
  30333. /** Assigns a name to this drawable. */
  30334. void setName (const String& newName) throw() { name = newName; }
  30335. /** Tries to turn some kind of image file into a drawable.
  30336. The data could be an image that the ImageFileFormat class understands, or it
  30337. could be SVG.
  30338. */
  30339. static Drawable* createFromImageData (const void* data, const int numBytes);
  30340. /** Tries to turn a stream containing some kind of image data into a drawable.
  30341. The data could be an image that the ImageFileFormat class understands, or it
  30342. could be SVG.
  30343. */
  30344. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30345. /** Tries to turn a file containing some kind of image data into a drawable.
  30346. The data could be an image that the ImageFileFormat class understands, or it
  30347. could be SVG.
  30348. */
  30349. static Drawable* createFromImageFile (const File& file);
  30350. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30351. into a Drawable tree.
  30352. The object returned must be deleted by the caller. If something goes wrong
  30353. while parsing, it may return 0.
  30354. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30355. implementation, but it can return the basic vector objects.
  30356. */
  30357. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30358. juce_UseDebuggingNewOperator
  30359. private:
  30360. Drawable (const Drawable&);
  30361. const Drawable& operator= (const Drawable&);
  30362. String name;
  30363. };
  30364. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30365. /********* End of inlined file: juce_Drawable.h *********/
  30366. #endif
  30367. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30368. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30369. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30370. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30371. /**
  30372. A drawable object which acts as a container for a set of other Drawables.
  30373. @see Drawable
  30374. */
  30375. class JUCE_API DrawableComposite : public Drawable
  30376. {
  30377. public:
  30378. /** Creates a composite Drawable.
  30379. */
  30380. DrawableComposite();
  30381. /** Destructor. */
  30382. virtual ~DrawableComposite();
  30383. /** Adds a new sub-drawable to this one.
  30384. This passes in a Drawable pointer for this object to look after. To add a copy
  30385. of a drawable, use the form of this method that takes a Drawable reference instead.
  30386. @param drawable the object to add - this will be deleted automatically
  30387. when no longer needed, so the caller mustn't keep any
  30388. pointers to it.
  30389. @param transform the transform to apply to this drawable when it's being
  30390. drawn
  30391. @param index where to insert it in the list of drawables. 0 is the back,
  30392. -1 is the front, or any value from 0 and getNumDrawables()
  30393. can be used
  30394. @see removeDrawable
  30395. */
  30396. void insertDrawable (Drawable* drawable,
  30397. const AffineTransform& transform = AffineTransform::identity,
  30398. const int index = -1);
  30399. /** Adds a new sub-drawable to this one.
  30400. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30401. for this object to look after, use the form of this method that takes a Drawable
  30402. pointer instead.
  30403. @param drawable the object to add - an internal copy will be made of this object
  30404. @param transform the transform to apply to this drawable when it's being
  30405. drawn
  30406. @param index where to insert it in the list of drawables. 0 is the back,
  30407. -1 is the front, or any value from 0 and getNumDrawables()
  30408. can be used
  30409. @see removeDrawable
  30410. */
  30411. void insertDrawable (const Drawable& drawable,
  30412. const AffineTransform& transform = AffineTransform::identity,
  30413. const int index = -1);
  30414. /** Deletes one of the Drawable objects.
  30415. @param index the index of the drawable to delete, between 0
  30416. and (getNumDrawables() - 1).
  30417. @see insertDrawable, getNumDrawables
  30418. */
  30419. void removeDrawable (const int index);
  30420. /** Returns the number of drawables contained inside this one.
  30421. @see getDrawable
  30422. */
  30423. int getNumDrawables() const throw() { return drawables.size(); }
  30424. /** Returns one of the drawables that are contained in this one.
  30425. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30426. to find it.
  30427. The pointer returned is managed by this object and will be deleted when no longer
  30428. needed, so be careful what you do with it.
  30429. @see getNumDrawables
  30430. */
  30431. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30432. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30433. The pointer returned is managed by this object and will be deleted when no longer
  30434. needed, so be careful what you do with it.
  30435. @see getNumDrawables
  30436. */
  30437. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30438. /** Brings one of the Drawables to the front.
  30439. @param index the index of the drawable to move, between 0
  30440. and (getNumDrawables() - 1).
  30441. @see insertDrawable, getNumDrawables
  30442. */
  30443. void bringToFront (const int index);
  30444. /** @internal */
  30445. void draw (Graphics& g, const AffineTransform& transform) const;
  30446. /** @internal */
  30447. void getBounds (float& x, float& y, float& width, float& height) const;
  30448. /** @internal */
  30449. bool hitTest (float x, float y) const;
  30450. /** @internal */
  30451. Drawable* createCopy() const;
  30452. juce_UseDebuggingNewOperator
  30453. private:
  30454. OwnedArray <Drawable> drawables;
  30455. OwnedArray <AffineTransform> transforms;
  30456. DrawableComposite (const DrawableComposite&);
  30457. const DrawableComposite& operator= (const DrawableComposite&);
  30458. };
  30459. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30460. /********* End of inlined file: juce_DrawableComposite.h *********/
  30461. #endif
  30462. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30463. /********* Start of inlined file: juce_DrawableImage.h *********/
  30464. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30465. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30466. /**
  30467. A drawable object which is a bitmap image.
  30468. @see Drawable
  30469. */
  30470. class JUCE_API DrawableImage : public Drawable
  30471. {
  30472. public:
  30473. DrawableImage();
  30474. /** Destructor. */
  30475. virtual ~DrawableImage();
  30476. /** Sets the image that this drawable will render.
  30477. An internal copy is made of the image passed-in. If you want to provide an
  30478. image that this object can take charge of without needing to create a copy,
  30479. use the other setImage() method.
  30480. */
  30481. void setImage (const Image& imageToCopy);
  30482. /** Sets the image that this drawable will render.
  30483. An internal copy of this will not be made, so the caller mustn't delete
  30484. the image while it's still being used by this object.
  30485. A good way to use this is with the ImageCache - if you create an image
  30486. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30487. it'll be released neatly with its reference count being decreased.
  30488. @param imageToUse the image to render
  30489. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30490. then the image will be deleted when this object no longer
  30491. needs it - unless the image was created by the ImageCache,
  30492. in which case it will be released with ImageCache::release().
  30493. */
  30494. void setImage (Image* imageToUse,
  30495. const bool releaseWhenNotNeeded);
  30496. /** Returns the current image. */
  30497. Image* getImage() const throw() { return image; }
  30498. /** Clears (and possibly deletes) the currently set image. */
  30499. void clearImage();
  30500. /** Sets the opacity to use when drawing the image. */
  30501. void setOpacity (const float newOpacity);
  30502. /** Returns the image's opacity. */
  30503. float getOpacity() const throw() { return opacity; }
  30504. /** Sets a colour to draw over the image's alpha channel.
  30505. By default this is transparent so isn't drawn, but if you set a non-transparent
  30506. colour here, then it will be overlaid on the image, using the image's alpha
  30507. channel as a mask.
  30508. This is handy for doing things like darkening or lightening an image by overlaying
  30509. it with semi-transparent black or white.
  30510. */
  30511. void setOverlayColour (const Colour& newOverlayColour);
  30512. /** Returns the overlay colour. */
  30513. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30514. /** @internal */
  30515. void draw (Graphics& g, const AffineTransform& transform) const;
  30516. /** @internal */
  30517. void getBounds (float& x, float& y, float& width, float& height) const;
  30518. /** @internal */
  30519. bool hitTest (float x, float y) const;
  30520. /** @internal */
  30521. Drawable* createCopy() const;
  30522. juce_UseDebuggingNewOperator
  30523. private:
  30524. Image* image;
  30525. bool canDeleteImage;
  30526. float opacity;
  30527. Colour overlayColour;
  30528. DrawableImage (const DrawableImage&);
  30529. const DrawableImage& operator= (const DrawableImage&);
  30530. };
  30531. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30532. /********* End of inlined file: juce_DrawableImage.h *********/
  30533. #endif
  30534. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30535. /********* Start of inlined file: juce_DrawablePath.h *********/
  30536. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30537. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30538. /**
  30539. A drawable object which renders a filled or outlined shape.
  30540. @see Drawable
  30541. */
  30542. class JUCE_API DrawablePath : public Drawable
  30543. {
  30544. public:
  30545. /** Creates a DrawablePath.
  30546. */
  30547. DrawablePath();
  30548. /** Destructor. */
  30549. virtual ~DrawablePath();
  30550. /** Changes the path that will be drawn.
  30551. @see setSolidFill, setOutline
  30552. */
  30553. void setPath (const Path& newPath);
  30554. /** Returns the current path. */
  30555. const Path& getPath() const throw() { return path; }
  30556. /** Sets a colour to fill the path with.
  30557. This colour is used to fill the path - if you don't want the path to be
  30558. filled (e.g. if you're just drawing an outline), set this colour to be
  30559. transparent.
  30560. @see setPath, setOutline
  30561. */
  30562. void setSolidFill (const Colour& newColour);
  30563. /** Sets a custom brush to use to fill the path.
  30564. @see setSolidFill
  30565. */
  30566. void setFillBrush (const Brush& newBrush);
  30567. /** Returns the brush currently being used to fill the shape. */
  30568. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30569. /** Changes the properties of the outline that will be drawn around the path.
  30570. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30571. colour passed-in here will be used for it.
  30572. @see setPath, setSolidFill
  30573. */
  30574. void setOutline (const float thickness,
  30575. const Colour& outlineColour);
  30576. /** Changes the properties of the outline that will be drawn around the path.
  30577. If the stroke type has 0 thickness, no outline will be drawn.
  30578. @see setPath, setSolidFill
  30579. */
  30580. void setOutline (const PathStrokeType& strokeType,
  30581. const Brush& strokeBrush);
  30582. /** Returns the current outline style. */
  30583. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30584. /** Returns the brush currently being used to draw the outline. */
  30585. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30586. /** @internal */
  30587. void draw (Graphics& g, const AffineTransform& transform) const;
  30588. /** @internal */
  30589. void getBounds (float& x, float& y, float& width, float& height) const;
  30590. /** @internal */
  30591. bool hitTest (float x, float y) const;
  30592. /** @internal */
  30593. Drawable* createCopy() const;
  30594. juce_UseDebuggingNewOperator
  30595. private:
  30596. Path path, outline;
  30597. Brush* fillBrush;
  30598. Brush* strokeBrush;
  30599. PathStrokeType strokeType;
  30600. void updateOutline();
  30601. DrawablePath (const DrawablePath&);
  30602. const DrawablePath& operator= (const DrawablePath&);
  30603. };
  30604. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30605. /********* End of inlined file: juce_DrawablePath.h *********/
  30606. #endif
  30607. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30608. /********* Start of inlined file: juce_DrawableText.h *********/
  30609. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30610. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30611. /**
  30612. A drawable object which renders a line of text.
  30613. @see Drawable
  30614. */
  30615. class JUCE_API DrawableText : public Drawable
  30616. {
  30617. public:
  30618. /** Creates a DrawableText object. */
  30619. DrawableText();
  30620. /** Destructor. */
  30621. virtual ~DrawableText();
  30622. /** Sets the block of text to render */
  30623. void setText (const GlyphArrangement& newText);
  30624. /** Sets a single line of text to render.
  30625. This is a convenient method of adding a single line - for
  30626. more complex text, use the setText() that takes a
  30627. GlyphArrangement instead.
  30628. */
  30629. void setText (const String& newText, const Font& fontToUse);
  30630. /** Returns the text arrangement that was set with setText(). */
  30631. const GlyphArrangement& getText() const throw() { return text; }
  30632. /** Sets the colour of the text. */
  30633. void setColour (const Colour& newColour);
  30634. /** Returns the current text colour. */
  30635. const Colour& getColour() const throw() { return colour; }
  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. GlyphArrangement text;
  30647. Colour colour;
  30648. DrawableText (const DrawableText&);
  30649. const DrawableText& operator= (const DrawableText&);
  30650. };
  30651. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30652. /********* End of inlined file: juce_DrawableText.h *********/
  30653. #endif
  30654. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30655. #endif
  30656. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30657. #endif
  30658. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30659. #endif
  30660. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30661. #endif
  30662. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30663. /********* Start of inlined file: juce_ArrowButton.h *********/
  30664. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30665. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30666. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30667. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30668. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30669. /**
  30670. An effect filter that adds a drop-shadow behind the image's content.
  30671. (This will only work on images/components that aren't opaque, of course).
  30672. When added to a component, this effect will draw a soft-edged
  30673. shadow based on what gets drawn inside it. The shadow will also
  30674. be applied to the component's children.
  30675. For speed, this doesn't use a proper gaussian blur, but cheats by
  30676. using a simple bilinear filter. If you need a really high-quality
  30677. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30678. @see Component::setComponentEffect
  30679. */
  30680. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30681. {
  30682. public:
  30683. /** Creates a default drop-shadow effect.
  30684. To customise the shadow's appearance, use the setShadowProperties()
  30685. method.
  30686. */
  30687. DropShadowEffect();
  30688. /** Destructor. */
  30689. ~DropShadowEffect();
  30690. /** Sets up parameters affecting the shadow's appearance.
  30691. @param newRadius the (approximate) radius of the blur used
  30692. @param newOpacity the opacity with which the shadow is rendered
  30693. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30694. component's contents
  30695. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30696. component's contents
  30697. */
  30698. void setShadowProperties (const float newRadius,
  30699. const float newOpacity,
  30700. const int newShadowOffsetX,
  30701. const int newShadowOffsetY);
  30702. /** @internal */
  30703. void applyEffect (Image& sourceImage, Graphics& destContext);
  30704. juce_UseDebuggingNewOperator
  30705. private:
  30706. int offsetX, offsetY;
  30707. float radius, opacity;
  30708. };
  30709. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30710. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30711. /**
  30712. A button with an arrow in it.
  30713. @see Button
  30714. */
  30715. class JUCE_API ArrowButton : public Button
  30716. {
  30717. public:
  30718. /** Creates an ArrowButton.
  30719. @param buttonName the name to give the button
  30720. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30721. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30722. @param arrowColour the colour to use for the arrow
  30723. */
  30724. ArrowButton (const String& buttonName,
  30725. float arrowDirection,
  30726. const Colour& arrowColour);
  30727. /** Destructor. */
  30728. ~ArrowButton();
  30729. juce_UseDebuggingNewOperator
  30730. protected:
  30731. /** @internal */
  30732. void paintButton (Graphics& g,
  30733. bool isMouseOverButton,
  30734. bool isButtonDown);
  30735. /** @internal */
  30736. void buttonStateChanged();
  30737. private:
  30738. Colour colour;
  30739. DropShadowEffect shadow;
  30740. Path path;
  30741. int offset;
  30742. ArrowButton (const ArrowButton&);
  30743. const ArrowButton& operator= (const ArrowButton&);
  30744. };
  30745. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30746. /********* End of inlined file: juce_ArrowButton.h *********/
  30747. #endif
  30748. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30749. #endif
  30750. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30751. /********* Start of inlined file: juce_DrawableButton.h *********/
  30752. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30753. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30754. /**
  30755. A button that displays a Drawable.
  30756. Up to three Drawable objects can be given to this button, to represent the
  30757. 'normal', 'over' and 'down' states.
  30758. @see Button
  30759. */
  30760. class JUCE_API DrawableButton : public Button
  30761. {
  30762. public:
  30763. enum ButtonStyle
  30764. {
  30765. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30766. ImageRaw, /**< The button will just display the images in their normal size and position.
  30767. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30768. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30769. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30770. };
  30771. /** Creates a DrawableButton.
  30772. After creating one of these, use setImages() to specify the drawables to use.
  30773. @param buttonName the name to give the component
  30774. @param buttonStyle the layout to use
  30775. @see ButtonStyle, setButtonStyle, setImages
  30776. */
  30777. DrawableButton (const String& buttonName,
  30778. const ButtonStyle buttonStyle);
  30779. /** Destructor. */
  30780. ~DrawableButton();
  30781. /** Sets up the images to draw for the various button states.
  30782. The button will keep its own internal copies of these drawables.
  30783. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30784. will be made of the object passed-in if it is non-zero.
  30785. @param overImage the thing to draw for the button's 'over' state - if this is
  30786. zero, the button's normal image will be used when the mouse is
  30787. over it. An internal copy will be made of the object passed-in
  30788. if it is non-zero.
  30789. @param downImage the thing to draw for the button's 'down' state - if this is
  30790. zero, the 'over' image will be used instead (or the normal image
  30791. as a last resort). An internal copy will be made of the object
  30792. passed-in if it is non-zero.
  30793. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30794. the normal image will be drawn with a reduced opacity instead.
  30795. An internal copy will be made of the object passed-in if it is
  30796. non-zero.
  30797. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30798. state is 'on'. If this is 0, the normal image is used instead
  30799. @param overImageOn same as the overImage, but this is used when the button's toggle
  30800. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30801. @param downImageOn same as the downImage, but this is used when the button's toggle
  30802. state is 'on'. If this is 0, the overImageOn is drawn instead
  30803. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30804. state is 'on'. If this is 0, the normal image will be drawn instead
  30805. with a reduced opacity
  30806. */
  30807. void setImages (const Drawable* normalImage,
  30808. const Drawable* overImage = 0,
  30809. const Drawable* downImage = 0,
  30810. const Drawable* disabledImage = 0,
  30811. const Drawable* normalImageOn = 0,
  30812. const Drawable* overImageOn = 0,
  30813. const Drawable* downImageOn = 0,
  30814. const Drawable* disabledImageOn = 0);
  30815. /** Changes the button's style.
  30816. @see ButtonStyle
  30817. */
  30818. void setButtonStyle (const ButtonStyle newStyle);
  30819. /** Changes the button's background colours.
  30820. The toggledOffColour is the colour to use when the button's toggle state
  30821. is off, and toggledOnColour when it's on.
  30822. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30823. used to fill the background of the component.
  30824. For an ImageOnButtonBackground style, the colour is used to draw the
  30825. button's lozenge shape and exactly how the colour's used will depend
  30826. on the LookAndFeel.
  30827. */
  30828. void setBackgroundColours (const Colour& toggledOffColour,
  30829. const Colour& toggledOnColour);
  30830. /** Returns the current background colour being used.
  30831. @see setBackgroundColour
  30832. */
  30833. const Colour& getBackgroundColour() const throw();
  30834. /** Gives the button an optional amount of space around the edge of the drawable.
  30835. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30836. ones on a button background. If the button is too small for the given gap, a
  30837. smaller gap will be used.
  30838. By default there's a gap of about 3 pixels.
  30839. */
  30840. void setEdgeIndent (const int numPixelsIndent);
  30841. /** Returns the image that the button is currently displaying. */
  30842. const Drawable* getCurrentImage() const throw();
  30843. const Drawable* getNormalImage() const throw();
  30844. const Drawable* getOverImage() const throw();
  30845. const Drawable* getDownImage() const throw();
  30846. juce_UseDebuggingNewOperator
  30847. protected:
  30848. /** @internal */
  30849. void paintButton (Graphics& g,
  30850. bool isMouseOverButton,
  30851. bool isButtonDown);
  30852. private:
  30853. ButtonStyle style;
  30854. Drawable* normalImage;
  30855. Drawable* overImage;
  30856. Drawable* downImage;
  30857. Drawable* disabledImage;
  30858. Drawable* normalImageOn;
  30859. Drawable* overImageOn;
  30860. Drawable* downImageOn;
  30861. Drawable* disabledImageOn;
  30862. Colour backgroundOff, backgroundOn;
  30863. int edgeIndent;
  30864. void deleteImages();
  30865. DrawableButton (const DrawableButton&);
  30866. const DrawableButton& operator= (const DrawableButton&);
  30867. };
  30868. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30869. /********* End of inlined file: juce_DrawableButton.h *********/
  30870. #endif
  30871. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30872. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30873. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30874. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30875. /**
  30876. A button showing an underlined weblink, that will launch the link
  30877. when it's clicked.
  30878. @see Button
  30879. */
  30880. class JUCE_API HyperlinkButton : public Button
  30881. {
  30882. public:
  30883. /** Creates a HyperlinkButton.
  30884. @param linkText the text that will be displayed in the button - this is
  30885. also set as the Component's name, but the text can be
  30886. changed later with the Button::getButtonText() method
  30887. @param linkURL the URL to launch when the user clicks the button
  30888. */
  30889. HyperlinkButton (const String& linkText,
  30890. const URL& linkURL);
  30891. /** Destructor. */
  30892. ~HyperlinkButton();
  30893. /** Changes the font to use for the text.
  30894. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30895. to match the size of the component.
  30896. */
  30897. void setFont (const Font& newFont,
  30898. const bool resizeToMatchComponentHeight,
  30899. const Justification& justificationType = Justification::horizontallyCentred);
  30900. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30901. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30902. methods.
  30903. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30904. */
  30905. enum ColourIds
  30906. {
  30907. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30908. };
  30909. /** Changes the URL that the button will trigger. */
  30910. void setURL (const URL& newURL) throw();
  30911. /** Returns the URL that the button will trigger. */
  30912. const URL& getURL() const throw() { return url; }
  30913. /** Resizes the button horizontally to fit snugly around the text.
  30914. This won't affect the button's height.
  30915. */
  30916. void changeWidthToFitText();
  30917. juce_UseDebuggingNewOperator
  30918. protected:
  30919. /** @internal */
  30920. void clicked();
  30921. /** @internal */
  30922. void colourChanged();
  30923. /** @internal */
  30924. void paintButton (Graphics& g,
  30925. bool isMouseOverButton,
  30926. bool isButtonDown);
  30927. private:
  30928. URL url;
  30929. Font font;
  30930. bool resizeFont;
  30931. Justification justification;
  30932. const Font getFontToUse() const;
  30933. HyperlinkButton (const HyperlinkButton&);
  30934. const HyperlinkButton& operator= (const HyperlinkButton&);
  30935. };
  30936. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30937. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30938. #endif
  30939. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30940. /********* Start of inlined file: juce_ImageButton.h *********/
  30941. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30942. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30943. /**
  30944. As the title suggests, this is a button containing an image.
  30945. The colour and transparency of the image can be set to vary when the
  30946. button state changes.
  30947. @see Button, ShapeButton, TextButton
  30948. */
  30949. class JUCE_API ImageButton : public Button
  30950. {
  30951. public:
  30952. /** Creates an ImageButton.
  30953. Use setImage() to specify the image to use. The colours and opacities that
  30954. are specified here can be changed later using setDrawingOptions().
  30955. @param name the name to give the component
  30956. */
  30957. ImageButton (const String& name);
  30958. /** Destructor. */
  30959. ~ImageButton();
  30960. /** Sets up the images to draw in various states.
  30961. Important! Bear in mind that if you pass the same image in for more than one of
  30962. these parameters, this button will delete it (or release from the ImageCache)
  30963. multiple times!
  30964. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30965. resized to the same dimensions as the normal image
  30966. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30967. button when the button's size changes
  30968. @param preserveImageProportions if true then any rescaling of the image to fit
  30969. the button will keep the image's x and y proportions
  30970. correct - i.e. it won't distort its shape, although
  30971. this might create gaps around the edges
  30972. @param normalImage the image to use when the button is in its normal state. The
  30973. image passed in will be deleted (or released if it
  30974. was created by the ImageCache class) when the
  30975. button no longer needs it.
  30976. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30977. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30978. normal image - if this colour is transparent, no overlay
  30979. will be drawn. The overlay will be drawn over the top of the
  30980. image, so you can basically add a solid or semi-transparent
  30981. colour to the image to brighten or darken it
  30982. @param overImage the image to use when the mouse is over the button. If
  30983. you want to use the same image as was set in the normalImage
  30984. parameter, this value can be 0. As for normalImage, it
  30985. will be deleted or released by the button when no longer
  30986. needed
  30987. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30988. is over the button
  30989. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30990. image when the mouse is over - if this colour is transparent,
  30991. no overlay will be drawn
  30992. @param downImage an image to use when the button is pressed down. If set
  30993. to zero, the 'over' image will be drawn instead (or the
  30994. normal image if there isn't an 'over' image either). This
  30995. image will be deleted or released by the button when no
  30996. longer needed
  30997. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30998. is pressed
  30999. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  31000. image when the button is pressed down - if this colour is
  31001. transparent, no overlay will be drawn
  31002. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  31003. whenever it's inside the button's bounding rectangle. If
  31004. set to values higher than 0, the mouse will only be
  31005. considered to be over the image when the value of the
  31006. image's alpha channel at that position is greater than
  31007. this level.
  31008. */
  31009. void setImages (const bool resizeButtonNowToFitThisImage,
  31010. const bool rescaleImagesWhenButtonSizeChanges,
  31011. const bool preserveImageProportions,
  31012. Image* const normalImage,
  31013. const float imageOpacityWhenNormal,
  31014. const Colour& overlayColourWhenNormal,
  31015. Image* const overImage,
  31016. const float imageOpacityWhenOver,
  31017. const Colour& overlayColourWhenOver,
  31018. Image* const downImage,
  31019. const float imageOpacityWhenDown,
  31020. const Colour& overlayColourWhenDown,
  31021. const float hitTestAlphaThreshold = 0.0f);
  31022. /** Returns the currently set 'normal' image. */
  31023. Image* getNormalImage() const throw();
  31024. /** Returns the image that's drawn when the mouse is over the button.
  31025. If an 'over' image has been set, this will return it; otherwise it'll
  31026. just return the normal image.
  31027. */
  31028. Image* getOverImage() const throw();
  31029. /** Returns the image that's drawn when the button is held down.
  31030. If a 'down' image has been set, this will return it; otherwise it'll
  31031. return the 'over' image or normal image, depending on what's available.
  31032. */
  31033. Image* getDownImage() const throw();
  31034. juce_UseDebuggingNewOperator
  31035. protected:
  31036. /** @internal */
  31037. bool hitTest (int x, int y);
  31038. /** @internal */
  31039. void paintButton (Graphics& g,
  31040. bool isMouseOverButton,
  31041. bool isButtonDown);
  31042. private:
  31043. bool scaleImageToFit, preserveProportions;
  31044. unsigned char alphaThreshold;
  31045. int imageX, imageY, imageW, imageH;
  31046. Image* normalImage;
  31047. Image* overImage;
  31048. Image* downImage;
  31049. float normalOpacity, overOpacity, downOpacity;
  31050. Colour normalOverlay, overOverlay, downOverlay;
  31051. Image* getCurrentImage() const;
  31052. void deleteImages();
  31053. ImageButton (const ImageButton&);
  31054. const ImageButton& operator= (const ImageButton&);
  31055. };
  31056. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  31057. /********* End of inlined file: juce_ImageButton.h *********/
  31058. #endif
  31059. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31060. /********* Start of inlined file: juce_ShapeButton.h *********/
  31061. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31062. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  31063. /**
  31064. A button that contains a filled shape.
  31065. @see Button, ImageButton, TextButton, ArrowButton
  31066. */
  31067. class JUCE_API ShapeButton : public Button
  31068. {
  31069. public:
  31070. /** Creates a ShapeButton.
  31071. @param name a name to give the component - see Component::setName()
  31072. @param normalColour the colour to fill the shape with when the mouse isn't over
  31073. @param overColour the colour to use when the mouse is over the shape
  31074. @param downColour the colour to use when the button is in the pressed-down state
  31075. */
  31076. ShapeButton (const String& name,
  31077. const Colour& normalColour,
  31078. const Colour& overColour,
  31079. const Colour& downColour);
  31080. /** Destructor. */
  31081. ~ShapeButton();
  31082. /** Sets the shape to use.
  31083. @param newShape the shape to use
  31084. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  31085. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  31086. the button is resized
  31087. @param hasDropShadow if true, the button will be given a drop-shadow effect
  31088. */
  31089. void setShape (const Path& newShape,
  31090. const bool resizeNowToFitThisShape,
  31091. const bool maintainShapeProportions,
  31092. const bool hasDropShadow);
  31093. /** Set the colours to use for drawing the shape.
  31094. @param normalColour the colour to fill the shape with when the mouse isn't over
  31095. @param overColour the colour to use when the mouse is over the shape
  31096. @param downColour the colour to use when the button is in the pressed-down state
  31097. */
  31098. void setColours (const Colour& normalColour,
  31099. const Colour& overColour,
  31100. const Colour& downColour);
  31101. /** Sets up an outline to draw around the shape.
  31102. @param outlineColour the colour to use
  31103. @param outlineStrokeWidth the thickness of line to draw
  31104. */
  31105. void setOutline (const Colour& outlineColour,
  31106. const float outlineStrokeWidth);
  31107. juce_UseDebuggingNewOperator
  31108. protected:
  31109. /** @internal */
  31110. void paintButton (Graphics& g,
  31111. bool isMouseOverButton,
  31112. bool isButtonDown);
  31113. private:
  31114. Colour normalColour, overColour, downColour, outlineColour;
  31115. DropShadowEffect shadow;
  31116. Path shape;
  31117. bool maintainShapeProportions;
  31118. float outlineWidth;
  31119. ShapeButton (const ShapeButton&);
  31120. const ShapeButton& operator= (const ShapeButton&);
  31121. };
  31122. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31123. /********* End of inlined file: juce_ShapeButton.h *********/
  31124. #endif
  31125. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31126. #endif
  31127. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31128. /********* Start of inlined file: juce_ToggleButton.h *********/
  31129. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31130. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31131. /**
  31132. A button that can be toggled on/off.
  31133. All buttons can be toggle buttons, but this lets you create one of the
  31134. standard ones which has a tick-box and a text label next to it.
  31135. @see Button, DrawableButton, TextButton
  31136. */
  31137. class JUCE_API ToggleButton : public Button
  31138. {
  31139. public:
  31140. /** Creates a ToggleButton.
  31141. @param buttonText the text to put in the button (the component's name is also
  31142. initially set to this string, but these can be changed later
  31143. using the setName() and setButtonText() methods)
  31144. */
  31145. ToggleButton (const String& buttonText);
  31146. /** Destructor. */
  31147. ~ToggleButton();
  31148. /** Resizes the button to fit neatly around its current text.
  31149. The button's height won't be affected, only its width.
  31150. */
  31151. void changeWidthToFitText();
  31152. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31153. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31154. methods.
  31155. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31156. */
  31157. enum ColourIds
  31158. {
  31159. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31160. };
  31161. juce_UseDebuggingNewOperator
  31162. protected:
  31163. /** @internal */
  31164. void paintButton (Graphics& g,
  31165. bool isMouseOverButton,
  31166. bool isButtonDown);
  31167. /** @internal */
  31168. void colourChanged();
  31169. private:
  31170. ToggleButton (const ToggleButton&);
  31171. const ToggleButton& operator= (const ToggleButton&);
  31172. };
  31173. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31174. /********* End of inlined file: juce_ToggleButton.h *********/
  31175. #endif
  31176. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31177. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31178. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31179. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31180. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31181. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31182. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31183. /********* Start of inlined file: juce_Toolbar.h *********/
  31184. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31185. #define __JUCE_TOOLBAR_JUCEHEADER__
  31186. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31187. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31188. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31189. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31190. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31191. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31192. /**
  31193. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31194. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31195. derive your component from this class, and make sure that it is somewhere inside a
  31196. DragAndDropContainer component.
  31197. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31198. the operating system onto your component, you don't need any of these classes: instead
  31199. see the FileDragAndDropTarget class.
  31200. @see DragAndDropContainer, FileDragAndDropTarget
  31201. */
  31202. class JUCE_API DragAndDropTarget
  31203. {
  31204. public:
  31205. /** Destructor. */
  31206. virtual ~DragAndDropTarget() {}
  31207. /** Callback to check whether this target is interested in the type of object being
  31208. dragged.
  31209. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31210. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31211. @returns true if this component wants to receive the other callbacks regarging this
  31212. type of object; if it returns false, no other callbacks will be made.
  31213. */
  31214. virtual bool isInterestedInDragSource (const String& sourceDescription,
  31215. Component* sourceComponent) = 0;
  31216. /** Callback to indicate that something is being dragged over this component.
  31217. This gets called when the user moves the mouse into this component while dragging
  31218. something.
  31219. Use this callback as a trigger to make your component repaint itself to give the
  31220. user feedback about whether the item can be dropped here or not.
  31221. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31222. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31223. @param x the mouse x position, relative to this component
  31224. @param y the mouse y position, relative to this component
  31225. @see itemDragExit
  31226. */
  31227. virtual void itemDragEnter (const String& sourceDescription,
  31228. Component* sourceComponent,
  31229. int x,
  31230. int y);
  31231. /** Callback to indicate that the user is dragging something over this component.
  31232. This gets called when the user moves the mouse over this component while dragging
  31233. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  31234. this lets you know what happens in-between.
  31235. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31236. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31237. @param x the mouse x position, relative to this component
  31238. @param y the mouse y position, relative to this component
  31239. */
  31240. virtual void itemDragMove (const String& sourceDescription,
  31241. Component* sourceComponent,
  31242. int x,
  31243. int y);
  31244. /** Callback to indicate that something has been dragged off the edge of this component.
  31245. This gets called when the user moves the mouse out of this component while dragging
  31246. something.
  31247. If you've used itemDragEnter() to repaint your component and give feedback, use this
  31248. as a signal to repaint it in its normal state.
  31249. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31250. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31251. @see itemDragEnter
  31252. */
  31253. virtual void itemDragExit (const String& sourceDescription,
  31254. Component* sourceComponent);
  31255. /** Callback to indicate that the user has dropped something onto this component.
  31256. When the user drops an item this get called, and you can use the description to
  31257. work out whether your object wants to deal with it or not.
  31258. Note that after this is called, the itemDragExit method may not be called, so you should
  31259. clean up in here if there's anything you need to do when the drag finishes.
  31260. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31261. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31262. @param x the mouse x position, relative to this component
  31263. @param y the mouse y position, relative to this component
  31264. */
  31265. virtual void itemDropped (const String& sourceDescription,
  31266. Component* sourceComponent,
  31267. int x,
  31268. int y) = 0;
  31269. /** Overriding this allows the target to tell the drag container whether to
  31270. draw the drag image while the cursor is over it.
  31271. By default it returns true, but if you return false, then the normal drag
  31272. image will not be shown when the cursor is over this target.
  31273. */
  31274. virtual bool shouldDrawDragImageWhenOver();
  31275. };
  31276. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31277. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  31278. /**
  31279. Enables drag-and-drop behaviour for a component and all its sub-components.
  31280. For a component to be able to make or receive drag-and-drop events, one of its parent
  31281. components must derive from this class. It's probably best for the top-level
  31282. component to implement it.
  31283. Then to start a drag operation, any sub-component can just call the startDragging()
  31284. method, and this object will take over, tracking the mouse and sending appropriate
  31285. callbacks to any child components derived from DragAndDropTarget which the mouse
  31286. moves over.
  31287. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31288. the operating system onto your component, you don't need any of these classes: you can do this
  31289. simply by overriding Component::filesDropped().
  31290. @see DragAndDropTarget
  31291. */
  31292. class JUCE_API DragAndDropContainer
  31293. {
  31294. public:
  31295. /** Creates a DragAndDropContainer.
  31296. The object that derives from this class must also be a Component.
  31297. */
  31298. DragAndDropContainer();
  31299. /** Destructor. */
  31300. virtual ~DragAndDropContainer();
  31301. /** Begins a drag-and-drop operation.
  31302. This starts a drag-and-drop operation - call it when the user drags the
  31303. mouse in your drag-source component, and this object will track mouse
  31304. movements until the user lets go of the mouse button, and will send
  31305. appropriate messages to DragAndDropTarget objects that the mouse moves
  31306. over.
  31307. findParentDragContainerFor() is a handy method to call to find the
  31308. drag container to use for a component.
  31309. @param sourceDescription a string to use as the description of the thing being
  31310. dragged - this will be passed to the objects that might be
  31311. dropped-onto so they can decide if they want to handle it or
  31312. not
  31313. @param sourceComponent the component that is being dragged
  31314. @param dragImage the image to drag around underneath the mouse. If this is
  31315. zero, a snapshot of the sourceComponent will be used instead. An
  31316. image passed-in will be deleted by this object when no longer
  31317. needed.
  31318. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  31319. window, and can be dragged to DragAndDropTargets that are the
  31320. children of components other than this one.
  31321. */
  31322. void startDragging (const String& sourceDescription,
  31323. Component* sourceComponent,
  31324. Image* dragImage = 0,
  31325. const bool allowDraggingToOtherJuceWindows = false);
  31326. /** Returns true if something is currently being dragged. */
  31327. bool isDragAndDropActive() const;
  31328. /** Returns the description of the thing that's currently being dragged.
  31329. If nothing's being dragged, this will return an empty string, otherwise it's the
  31330. string that was passed into startDragging().
  31331. @see startDragging
  31332. */
  31333. const String getCurrentDragDescription() const;
  31334. /** Utility to find the DragAndDropContainer for a given Component.
  31335. This will search up this component's parent hierarchy looking for the first
  31336. parent component which is a DragAndDropContainer.
  31337. It's useful when a component wants to call startDragging but doesn't know
  31338. the DragAndDropContainer it should to use.
  31339. Obviously this may return 0 if it doesn't find a suitable component.
  31340. */
  31341. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  31342. /** This performs a synchronous drag-and-drop of a set of files to some external
  31343. application.
  31344. You can call this function in response to a mouseDrag callback, and it will
  31345. block, running its own internal message loop and tracking the mouse, while it
  31346. uses a native operating system drag-and-drop operation to move or copy some
  31347. files to another application.
  31348. @param files a list of filenames to drag
  31349. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  31350. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  31351. @returns true if the files were successfully dropped somewhere, or false if it
  31352. was interrupted
  31353. @see performExternalDragDropOfText
  31354. */
  31355. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  31356. /** This performs a synchronous drag-and-drop of a block of text to some external
  31357. application.
  31358. You can call this function in response to a mouseDrag callback, and it will
  31359. block, running its own internal message loop and tracking the mouse, while it
  31360. uses a native operating system drag-and-drop operation to move or copy some
  31361. text to another application.
  31362. @param text the text to copy
  31363. @returns true if the text was successfully dropped somewhere, or false if it
  31364. was interrupted
  31365. @see performExternalDragDropOfFiles
  31366. */
  31367. static bool performExternalDragDropOfText (const String& text);
  31368. juce_UseDebuggingNewOperator
  31369. protected:
  31370. /** Override this if you want to be able to perform an external drag a set of files
  31371. when the user drags outside of this container component.
  31372. This method will be called when a drag operation moves outside the Juce-based window,
  31373. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31374. to the array passed in, and return true.
  31375. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31376. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31377. @param files on return, the filenames you want to drag
  31378. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31379. it must make a copy of them (see the performExternalDragDropOfFiles()
  31380. method)
  31381. @see performExternalDragDropOfFiles
  31382. */
  31383. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31384. Component* dragSourceComponent,
  31385. StringArray& files,
  31386. bool& canMoveFiles);
  31387. private:
  31388. friend class DragImageComponent;
  31389. Component* dragImageComponent;
  31390. String currentDragDesc;
  31391. };
  31392. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31393. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31394. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31395. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31396. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31397. /**
  31398. Animates a set of components, moving it to a new position.
  31399. To use this, create a ComponentAnimator, and use its animateComponent() method
  31400. to tell it to move components to destination positions. Any number of
  31401. components can be animated by one ComponentAnimator object (if you've got a
  31402. lot of components to move, it's much more efficient to share a single animator
  31403. than to have many animators running at once).
  31404. You'll need to make sure the animator object isn't deleted before it finishes
  31405. moving the components.
  31406. */
  31407. class JUCE_API ComponentAnimator : private Timer
  31408. {
  31409. public:
  31410. /** Creates a ComponentAnimator. */
  31411. ComponentAnimator();
  31412. /** Destructor. */
  31413. ~ComponentAnimator();
  31414. /** Starts a component moving from its current position to a specified position.
  31415. If the component is already in the middle of an animation, that will be abandoned,
  31416. and a new animation will begin, moving the component from its current location.
  31417. The start and end speed parameters let you apply some acceleration to the component's
  31418. movement.
  31419. @param component the component to move
  31420. @param finalPosition the destination position and size to move it to
  31421. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31422. to arrive at its destination
  31423. @param startSpeed a value to indicate the relative start speed of the
  31424. animation. If this is 0, the component will start
  31425. by accelerating from rest; higher values mean that it
  31426. will have an initial speed greater than zero. If the
  31427. value if greater than 1, it will decelerate towards the
  31428. middle of its journey. To move the component at a constant
  31429. rate for its entire animation, set both the start and
  31430. end speeds to 1.0
  31431. @param endSpeed a relative speed at which the component should be moving
  31432. when the animation finishes. If this is 0, the component
  31433. will decelerate to a standstill at its final position; higher
  31434. values mean the component will still be moving when it stops.
  31435. To move the component at a constant rate for its entire
  31436. animation, set both the start and end speeds to 1.0
  31437. */
  31438. void animateComponent (Component* const component,
  31439. const Rectangle& finalPosition,
  31440. const int millisecondsToSpendMoving,
  31441. const double startSpeed = 1.0,
  31442. const double endSpeed = 1.0);
  31443. /** Stops a component if it's currently being animated.
  31444. If moveComponentToItsFinalPosition is true, then the component will
  31445. be immediately moved to its destination position and size. If false, it will be
  31446. left in whatever location it currently occupies.
  31447. */
  31448. void cancelAnimation (Component* const component,
  31449. const bool moveComponentToItsFinalPosition);
  31450. /** Clears all of the active animations.
  31451. If moveComponentsToTheirFinalPositions is true, all the components will
  31452. be immediately set to their final positions. If false, they will be
  31453. left in whatever locations they currently occupy.
  31454. */
  31455. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31456. /** Returns the destination position for a component.
  31457. If the component is being animated, this will return the target position that
  31458. was specified when animateComponent() was called.
  31459. If the specified component isn't currently being animated, this method will just
  31460. return its current position.
  31461. */
  31462. const Rectangle getComponentDestination (Component* const component);
  31463. juce_UseDebuggingNewOperator
  31464. private:
  31465. VoidArray tasks;
  31466. uint32 lastTime;
  31467. void* findTaskFor (Component* const component) const;
  31468. void timerCallback();
  31469. };
  31470. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31471. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31472. class ToolbarItemComponent;
  31473. class ToolbarItemFactory;
  31474. class MissingItemsComponent;
  31475. /**
  31476. A toolbar component.
  31477. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31478. and looks after their order and layout.
  31479. Items (icon buttons or other custom components) are added to a toolbar using a
  31480. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31481. toolbar might contain more than one instance of a particular item type.
  31482. Toolbars can be interactively customised, allowing the user to drag the items
  31483. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31484. component as a source of new items.
  31485. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31486. */
  31487. class JUCE_API Toolbar : public Component,
  31488. public DragAndDropContainer,
  31489. public DragAndDropTarget,
  31490. private ButtonListener
  31491. {
  31492. public:
  31493. /** Creates an empty toolbar component.
  31494. To add some icons or other components to your toolbar, you'll need to
  31495. create a ToolbarItemFactory class that can create a suitable set of
  31496. ToolbarItemComponents.
  31497. @see ToolbarItemFactory, ToolbarItemComponents
  31498. */
  31499. Toolbar();
  31500. /** Destructor.
  31501. Any items on the bar will be deleted when the toolbar is deleted.
  31502. */
  31503. ~Toolbar();
  31504. /** Changes the bar's orientation.
  31505. @see isVertical
  31506. */
  31507. void setVertical (const bool shouldBeVertical);
  31508. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31509. You can change the bar's orientation with setVertical().
  31510. */
  31511. bool isVertical() const throw() { return vertical; }
  31512. /** Returns the depth of the bar.
  31513. If the bar is horizontal, this will return its height; if it's vertical, it
  31514. will return its width.
  31515. @see getLength
  31516. */
  31517. int getThickness() const throw();
  31518. /** Returns the length of the bar.
  31519. If the bar is horizontal, this will return its width; if it's vertical, it
  31520. will return its height.
  31521. @see getThickness
  31522. */
  31523. int getLength() const throw();
  31524. /** Deletes all items from the bar.
  31525. */
  31526. void clear();
  31527. /** Adds an item to the toolbar.
  31528. The factory's ToolbarItemFactory::createItem() will be called by this method
  31529. to create the component that will actually be added to the bar.
  31530. The new item will be inserted at the specified index (if the index is -1, it
  31531. will be added to the right-hand or bottom end of the bar).
  31532. Once added, the component will be automatically deleted by this object when it
  31533. is no longer needed.
  31534. @see ToolbarItemFactory
  31535. */
  31536. void addItem (ToolbarItemFactory& factory,
  31537. const int itemId,
  31538. const int insertIndex = -1);
  31539. /** Deletes one of the items from the bar.
  31540. */
  31541. void removeToolbarItem (const int itemIndex);
  31542. /** Returns the number of items currently on the toolbar.
  31543. @see getItemId, getItemComponent
  31544. */
  31545. int getNumItems() const throw();
  31546. /** Returns the ID of the item with the given index.
  31547. If the index is less than zero or greater than the number of items,
  31548. this will return 0.
  31549. @see getNumItems
  31550. */
  31551. int getItemId (const int itemIndex) const throw();
  31552. /** Returns the component being used for the item with the given index.
  31553. If the index is less than zero or greater than the number of items,
  31554. this will return 0.
  31555. @see getNumItems
  31556. */
  31557. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31558. /** Clears this toolbar and adds to it the default set of items that the specified
  31559. factory creates.
  31560. @see ToolbarItemFactory::getDefaultItemSet
  31561. */
  31562. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31563. /** Options for the way items should be displayed.
  31564. @see setStyle, getStyle
  31565. */
  31566. enum ToolbarItemStyle
  31567. {
  31568. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31569. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31570. textOnly /**< Means that the toolbar only display text labels for each item. */
  31571. };
  31572. /** Returns the toolbar's current style.
  31573. @see ToolbarItemStyle, setStyle
  31574. */
  31575. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31576. /** Changes the toolbar's current style.
  31577. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31578. */
  31579. void setStyle (const ToolbarItemStyle& newStyle);
  31580. /** Flags used by the showCustomisationDialog() method. */
  31581. enum CustomisationFlags
  31582. {
  31583. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31584. show the "icons only" option on its choice of toolbar styles. */
  31585. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31586. show the "icons with text" option on its choice of toolbar styles. */
  31587. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31588. show the "text only" option on its choice of toolbar styles. */
  31589. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31590. show a button to reset the toolbar to its default set of items. */
  31591. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31592. };
  31593. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31594. The dialog contains a ToolbarItemPalette and various controls for editing other
  31595. aspects of the toolbar. This method will block and run the dialog box modally,
  31596. returning when the user closes it.
  31597. The factory is used to determine the set of items that will be shown on the
  31598. palette.
  31599. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31600. enum.
  31601. @see ToolbarItemPalette
  31602. */
  31603. void showCustomisationDialog (ToolbarItemFactory& factory,
  31604. const int optionFlags = allCustomisationOptionsEnabled);
  31605. /** Turns on or off the toolbar's editing mode, in which its items can be
  31606. rearranged by the user.
  31607. (In most cases it's easier just to use showCustomisationDialog() instead of
  31608. trying to enable editing directly).
  31609. @see ToolbarItemPalette
  31610. */
  31611. void setEditingActive (const bool editingEnabled);
  31612. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31613. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31614. methods.
  31615. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31616. */
  31617. enum ColourIds
  31618. {
  31619. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31620. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31621. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31622. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31623. over them. */
  31624. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31625. held down on them. */
  31626. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31627. when the style is set to iconsWithText or textOnly. */
  31628. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31629. the customisation dialog is active and the mouse moves over them. */
  31630. };
  31631. /** Returns a string that represents the toolbar's current set of items.
  31632. This lets you later restore the same item layout using restoreFromString().
  31633. @see restoreFromString
  31634. */
  31635. const String toString() const;
  31636. /** Restores a set of items that was previously stored in a string by the toString()
  31637. method.
  31638. The factory object is used to create any item components that are needed.
  31639. @see toString
  31640. */
  31641. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31642. const String& savedVersion);
  31643. /** @internal */
  31644. void paint (Graphics& g);
  31645. /** @internal */
  31646. void resized();
  31647. /** @internal */
  31648. void buttonClicked (Button*);
  31649. /** @internal */
  31650. void mouseDown (const MouseEvent&);
  31651. /** @internal */
  31652. bool isInterestedInDragSource (const String&, Component*);
  31653. /** @internal */
  31654. void itemDragMove (const String&, Component*, int, int);
  31655. /** @internal */
  31656. void itemDragExit (const String&, Component*);
  31657. /** @internal */
  31658. void itemDropped (const String&, Component*, int, int);
  31659. /** @internal */
  31660. void updateAllItemPositions (const bool animate);
  31661. /** @internal */
  31662. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31663. juce_UseDebuggingNewOperator
  31664. private:
  31665. Button* missingItemsButton;
  31666. bool vertical, isEditingActive;
  31667. ToolbarItemStyle toolbarStyle;
  31668. ComponentAnimator animator;
  31669. friend class MissingItemsComponent;
  31670. Array <ToolbarItemComponent*> items;
  31671. friend class ItemDragAndDropOverlayComponent;
  31672. static const tchar* const toolbarDragDescriptor;
  31673. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31674. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31675. Toolbar (const Toolbar&);
  31676. const Toolbar& operator= (const Toolbar&);
  31677. };
  31678. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31679. /********* End of inlined file: juce_Toolbar.h *********/
  31680. class ItemDragAndDropOverlayComponent;
  31681. /**
  31682. A component that can be used as one of the items in a Toolbar.
  31683. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31684. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31685. class for further info about creating them.
  31686. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31687. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31688. calling the constructor, and override contentAreaChanged(), in which you can position
  31689. any sub-components you need to add.
  31690. To add basic buttons without writing a special subclass, have a look at the
  31691. ToolbarButton class.
  31692. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31693. */
  31694. class JUCE_API ToolbarItemComponent : public Button
  31695. {
  31696. public:
  31697. /** Constructor.
  31698. @param itemId the ID of the type of toolbar item which this represents
  31699. @param labelText the text to display if the toolbar's style is set to
  31700. Toolbar::iconsWithText or Toolbar::textOnly
  31701. @param isBeingUsedAsAButton set this to false if you don't want the button
  31702. to draw itself with button over/down states when the mouse
  31703. moves over it or clicks
  31704. */
  31705. ToolbarItemComponent (const int itemId,
  31706. const String& labelText,
  31707. const bool isBeingUsedAsAButton);
  31708. /** Destructor. */
  31709. ~ToolbarItemComponent();
  31710. /** Returns the item type ID that this component represents.
  31711. This value is in the constructor.
  31712. */
  31713. int getItemId() const throw() { return itemId; }
  31714. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31715. inside one.
  31716. */
  31717. Toolbar* getToolbar() const;
  31718. /** Returns true if this component is currently inside a toolbar which is vertical.
  31719. @see Toolbar::isVertical
  31720. */
  31721. bool isToolbarVertical() const;
  31722. /** Returns the current style setting of this item.
  31723. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31724. @see setStyle, Toolbar::getStyle
  31725. */
  31726. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31727. /** Changes the current style setting of this item.
  31728. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31729. by the toolbar that holds this item.
  31730. @see setStyle, Toolbar::setStyle
  31731. */
  31732. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31733. /** Returns the area of the component that should be used to display the button image or
  31734. other contents of the item.
  31735. This content area may change when the item's style changes, and may leave a space around the
  31736. edge of the component where the text label can be shown.
  31737. @see contentAreaChanged
  31738. */
  31739. const Rectangle getContentArea() const throw() { return contentArea; }
  31740. /** This method must return the size criteria for this item, based on a given toolbar
  31741. size and orientation.
  31742. The preferredSize, minSize and maxSize values must all be set by your implementation
  31743. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31744. toolbar, they refer to the item's height.
  31745. The preferredSize is the size that the component would like to be, and this must be
  31746. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31747. the same value.
  31748. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31749. Toolbar::getThickness().
  31750. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31751. vertically.
  31752. */
  31753. virtual bool getToolbarItemSizes (int toolbarThickness,
  31754. bool isToolbarVertical,
  31755. int& preferredSize,
  31756. int& minSize,
  31757. int& maxSize) = 0;
  31758. /** Your subclass should use this method to draw its content area.
  31759. The graphics object that is passed-in will have been clipped and had its origin
  31760. moved to fit the content area as specified get getContentArea(). The width and height
  31761. parameters are the width and height of the content area.
  31762. If the component you're writing isn't a button, you can just do nothing in this method.
  31763. */
  31764. virtual void paintButtonArea (Graphics& g,
  31765. int width, int height,
  31766. bool isMouseOver, bool isMouseDown) = 0;
  31767. /** Callback to indicate that the content area of this item has changed.
  31768. This might be because the component was resized, or because the style changed and
  31769. the space needed for the text label is different.
  31770. See getContentArea() for a description of what the area is.
  31771. */
  31772. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31773. /** Editing modes.
  31774. These are used by setEditingMode(), but will be rarely needed in user code.
  31775. */
  31776. enum ToolbarEditingMode
  31777. {
  31778. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31779. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31780. customisation mode, and the items can be dragged around. */
  31781. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31782. dragged onto a toolbar to add it to that bar.*/
  31783. };
  31784. /** Changes the editing mode of this component.
  31785. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31786. and is unlikely to be of much use in end-user-code.
  31787. */
  31788. void setEditingMode (const ToolbarEditingMode newMode);
  31789. /** Returns the current editing mode of this component.
  31790. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31791. and is unlikely to be of much use in end-user-code.
  31792. */
  31793. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31794. /** @internal */
  31795. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31796. /** @internal */
  31797. void resized();
  31798. juce_UseDebuggingNewOperator
  31799. private:
  31800. friend class Toolbar;
  31801. friend class ItemDragAndDropOverlayComponent;
  31802. const int itemId;
  31803. ToolbarEditingMode mode;
  31804. Toolbar::ToolbarItemStyle toolbarStyle;
  31805. Component* overlayComp;
  31806. int dragOffsetX, dragOffsetY;
  31807. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31808. Rectangle contentArea;
  31809. ToolbarItemComponent (const ToolbarItemComponent&);
  31810. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31811. };
  31812. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31813. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31814. /**
  31815. A type of button designed to go on a toolbar.
  31816. This simple button can have two Drawable objects specified - one for normal
  31817. use and another one (optionally) for the button's "on" state if it's a
  31818. toggle button.
  31819. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31820. */
  31821. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31822. {
  31823. public:
  31824. /** Creates a ToolbarButton.
  31825. @param itemId the ID for this toolbar item type. This is passed through to the
  31826. ToolbarItemComponent constructor
  31827. @param labelText the text to display on the button (if the toolbar is using a style
  31828. that shows text labels). This is passed through to the
  31829. ToolbarItemComponent constructor
  31830. @param normalImage a drawable object that the button should use as its icon. The object
  31831. that is passed-in here will be kept by this object and will be
  31832. deleted when no longer needed or when this button is deleted.
  31833. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31834. is in a toggled-on state (see the Button::getToggleState() method). If
  31835. 0 is passed-in here, then the normal image will be used instead, regardless
  31836. of the toggle state. The object that is passed-in here will be kept by
  31837. this object and will be deleted when no longer needed or when this button
  31838. is deleted.
  31839. */
  31840. ToolbarButton (const int itemId,
  31841. const String& labelText,
  31842. Drawable* const normalImage,
  31843. Drawable* const toggledOnImage);
  31844. /** Destructor. */
  31845. ~ToolbarButton();
  31846. /** @internal */
  31847. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31848. int& minSize, int& maxSize);
  31849. /** @internal */
  31850. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31851. /** @internal */
  31852. void contentAreaChanged (const Rectangle& newBounds);
  31853. juce_UseDebuggingNewOperator
  31854. private:
  31855. Drawable* const normalImage;
  31856. Drawable* const toggledOnImage;
  31857. ToolbarButton (const ToolbarButton&);
  31858. const ToolbarButton& operator= (const ToolbarButton&);
  31859. };
  31860. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31861. /********* End of inlined file: juce_ToolbarButton.h *********/
  31862. #endif
  31863. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31864. #endif
  31865. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31866. /********* Start of inlined file: juce_GlowEffect.h *********/
  31867. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31868. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31869. /**
  31870. A component effect that adds a coloured blur around the component's contents.
  31871. (This will only work on non-opaque components).
  31872. @see Component::setComponentEffect, DropShadowEffect
  31873. */
  31874. class JUCE_API GlowEffect : public ImageEffectFilter
  31875. {
  31876. public:
  31877. /** Creates a default 'glow' effect.
  31878. To customise its appearance, use the setGlowProperties() method.
  31879. */
  31880. GlowEffect();
  31881. /** Destructor. */
  31882. ~GlowEffect();
  31883. /** Sets the glow's radius and colour.
  31884. The radius is how large the blur should be, and the colour is
  31885. used to render it (for a less intense glow, lower the colour's
  31886. opacity).
  31887. */
  31888. void setGlowProperties (const float newRadius,
  31889. const Colour& newColour);
  31890. /** @internal */
  31891. void applyEffect (Image& sourceImage, Graphics& destContext);
  31892. juce_UseDebuggingNewOperator
  31893. private:
  31894. float radius;
  31895. Colour colour;
  31896. };
  31897. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31898. /********* End of inlined file: juce_GlowEffect.h *********/
  31899. #endif
  31900. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31901. #endif
  31902. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31903. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31904. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31905. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31906. /**
  31907. An effect filter that reduces the image's opacity.
  31908. This can be used to make a component (and its child components) more
  31909. transparent.
  31910. @see Component::setComponentEffect
  31911. */
  31912. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31913. {
  31914. public:
  31915. /** Creates the effect object.
  31916. The opacity of the component to which the effect is applied will be
  31917. scaled by the given factor (in the range 0 to 1.0f).
  31918. */
  31919. ReduceOpacityEffect (const float opacity = 1.0f);
  31920. /** Destructor. */
  31921. ~ReduceOpacityEffect();
  31922. /** Sets how much to scale the component's opacity.
  31923. @param newOpacity should be between 0 and 1.0f
  31924. */
  31925. void setOpacity (const float newOpacity);
  31926. /** @internal */
  31927. void applyEffect (Image& sourceImage, Graphics& destContext);
  31928. juce_UseDebuggingNewOperator
  31929. private:
  31930. float opacity;
  31931. };
  31932. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31933. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31934. #endif
  31935. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31936. #endif
  31937. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31938. #endif
  31939. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31940. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31941. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31942. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31943. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31944. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31945. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31946. /**
  31947. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31948. command in a ApplicationCommandManager.
  31949. Normally, you won't actually create a KeyPressMappingSet directly, because
  31950. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  31951. you'd create yourself an ApplicationCommandManager, and call its
  31952. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  31953. KeyPressMappingSet.
  31954. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  31955. to the top-level component for which you want to handle keystrokes. So for example:
  31956. @code
  31957. class MyMainWindow : public Component
  31958. {
  31959. ApplicationCommandManager* myCommandManager;
  31960. public:
  31961. MyMainWindow()
  31962. {
  31963. myCommandManager = new ApplicationCommandManager();
  31964. // first, make sure the command manager has registered all the commands that its
  31965. // targets can perform..
  31966. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  31967. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  31968. // this will use the command manager to initialise the KeyPressMappingSet with
  31969. // the default keypresses that were specified when the targets added their commands
  31970. // to the manager.
  31971. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  31972. // having set up the default key-mappings, you might now want to load the last set
  31973. // of mappings that the user configured.
  31974. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  31975. // Now tell our top-level window to send any keypresses that arrive to the
  31976. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  31977. addKeyListener (myCommandManager->getKeyMappings());
  31978. }
  31979. ...
  31980. }
  31981. @endcode
  31982. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  31983. register to be told when a command or mapping is added, removed, etc.
  31984. There's also a UI component called KeyMappingEditorComponent that can be used
  31985. to easily edit the key mappings.
  31986. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  31987. */
  31988. class JUCE_API KeyPressMappingSet : public KeyListener,
  31989. public ChangeBroadcaster,
  31990. public FocusChangeListener
  31991. {
  31992. public:
  31993. /** Creates a KeyPressMappingSet for a given command manager.
  31994. Normally, you won't actually create a KeyPressMappingSet directly, because
  31995. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  31996. best thing to do is to create your ApplicationCommandManager, and use the
  31997. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  31998. When a suitable keypress happens, the manager's invoke() method will be
  31999. used to invoke the appropriate command.
  32000. @see ApplicationCommandManager
  32001. */
  32002. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  32003. /** Creates an copy of a KeyPressMappingSet. */
  32004. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  32005. /** Destructor. */
  32006. ~KeyPressMappingSet();
  32007. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  32008. /** Returns a list of keypresses that are assigned to a particular command.
  32009. @param commandID the command's ID
  32010. */
  32011. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  32012. /** Assigns a keypress to a command.
  32013. If the keypress is already assigned to a different command, it will first be
  32014. removed from that command, to avoid it triggering multiple functions.
  32015. @param commandID the ID of the command that you want to add a keypress to. If
  32016. this is 0, the keypress will be removed from anything that it
  32017. was previously assigned to, but not re-assigned
  32018. @param newKeyPress the new key-press
  32019. @param insertIndex if this is less than zero, the key will be appended to the
  32020. end of the list of keypresses; otherwise the new keypress will
  32021. be inserted into the existing list at this index
  32022. */
  32023. void addKeyPress (const CommandID commandID,
  32024. const KeyPress& newKeyPress,
  32025. int insertIndex = -1) throw();
  32026. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  32027. @see resetToDefaultMapping
  32028. */
  32029. void resetToDefaultMappings() throw();
  32030. /** Resets all key-mappings to the defaults for a particular command.
  32031. @see resetToDefaultMappings
  32032. */
  32033. void resetToDefaultMapping (const CommandID commandID) throw();
  32034. /** Removes all keypresses that are assigned to any commands. */
  32035. void clearAllKeyPresses() throw();
  32036. /** Removes all keypresses that are assigned to a particular command. */
  32037. void clearAllKeyPresses (const CommandID commandID) throw();
  32038. /** Removes one of the keypresses that are assigned to a command.
  32039. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  32040. which the keyPressIndex refers.
  32041. */
  32042. void removeKeyPress (const CommandID commandID,
  32043. const int keyPressIndex) throw();
  32044. /** Removes a keypress from any command that it may be assigned to.
  32045. */
  32046. void removeKeyPress (const KeyPress& keypress) throw();
  32047. /** Returns true if the given command is linked to this key. */
  32048. bool containsMapping (const CommandID commandID,
  32049. const KeyPress& keyPress) const throw();
  32050. /** Looks for a command that corresponds to a keypress.
  32051. @returns the UID of the command or 0 if none was found
  32052. */
  32053. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  32054. /** Tries to recreate the mappings from a previously stored state.
  32055. The XML passed in must have been created by the createXml() method.
  32056. If the stored state makes any reference to commands that aren't
  32057. currently available, these will be ignored.
  32058. If the set of mappings being loaded was a set of differences (using createXml (true)),
  32059. then this will call resetToDefaultMappings() and then merge the saved mappings
  32060. on top. If the saved set was created with createXml (false), then this method
  32061. will first clear all existing mappings and load the saved ones as a complete set.
  32062. @returns true if it manages to load the XML correctly
  32063. @see createXml
  32064. */
  32065. bool restoreFromXml (const XmlElement& xmlVersion);
  32066. /** Creates an XML representation of the current mappings.
  32067. This will produce a lump of XML that can be later reloaded using
  32068. restoreFromXml() to recreate the current mapping state.
  32069. The object that is returned must be deleted by the caller.
  32070. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  32071. will be saved into the XML. If it's true, then the XML will
  32072. only store the differences between the current mappings and
  32073. the default mappings you'd get from calling resetToDefaultMappings().
  32074. The advantage of saving a set of differences from the default is that
  32075. if you change the default mappings (in a new version of your app, for
  32076. example), then these will be merged into a user's saved preferences.
  32077. @see restoreFromXml
  32078. */
  32079. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  32080. /** @internal */
  32081. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  32082. /** @internal */
  32083. bool keyStateChanged (Component* originatingComponent);
  32084. /** @internal */
  32085. void globalFocusChanged (Component* focusedComponent);
  32086. juce_UseDebuggingNewOperator
  32087. private:
  32088. ApplicationCommandManager* commandManager;
  32089. struct CommandMapping
  32090. {
  32091. CommandID commandID;
  32092. Array <KeyPress> keypresses;
  32093. bool wantsKeyUpDownCallbacks;
  32094. };
  32095. OwnedArray <CommandMapping> mappings;
  32096. struct KeyPressTime
  32097. {
  32098. KeyPress key;
  32099. uint32 timeWhenPressed;
  32100. };
  32101. OwnedArray <KeyPressTime> keysDown;
  32102. void handleMessage (const Message& message);
  32103. void invokeCommand (const CommandID commandID,
  32104. const KeyPress& keyPress,
  32105. const bool isKeyDown,
  32106. const int millisecsSinceKeyPressed,
  32107. Component* const originatingComponent) const;
  32108. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  32109. };
  32110. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32111. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  32112. /********* Start of inlined file: juce_TreeView.h *********/
  32113. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  32114. #define __JUCE_TREEVIEW_JUCEHEADER__
  32115. class TreeView;
  32116. /**
  32117. An item in a treeview.
  32118. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  32119. own sub-items.
  32120. To implement an item that contains sub-items, override the itemOpennessChanged()
  32121. method so that when it is opened, it adds the new sub-items to itself using the
  32122. addSubItem method. Depending on the nature of the item it might choose to only
  32123. do this the first time it's opened, or it might want to refresh itself each time.
  32124. It also has the option of deleting its sub-items when it is closed, or leaving them
  32125. in place.
  32126. */
  32127. class JUCE_API TreeViewItem
  32128. {
  32129. public:
  32130. /** Constructor. */
  32131. TreeViewItem();
  32132. /** Destructor. */
  32133. virtual ~TreeViewItem();
  32134. /** Returns the number of sub-items that have been added to this item.
  32135. Note that this doesn't mean much if the node isn't open.
  32136. @see getSubItem, mightContainSubItems, addSubItem
  32137. */
  32138. int getNumSubItems() const throw();
  32139. /** Returns one of the item's sub-items.
  32140. Remember that the object returned might get deleted at any time when its parent
  32141. item is closed or refreshed, depending on the nature of the items you're using.
  32142. @see getNumSubItems
  32143. */
  32144. TreeViewItem* getSubItem (const int index) const throw();
  32145. /** Removes any sub-items. */
  32146. void clearSubItems();
  32147. /** Adds a sub-item.
  32148. @param newItem the object to add to the item's sub-item list. Once added, these can be
  32149. found using getSubItem(). When the items are later removed with
  32150. removeSubItem() (or when this item is deleted), they will be deleted.
  32151. @param insertPosition the index which the new item should have when it's added. If this
  32152. value is less than 0, the item will be added to the end of the list.
  32153. */
  32154. void addSubItem (TreeViewItem* const newItem,
  32155. const int insertPosition = -1);
  32156. /** Removes one of the sub-items.
  32157. @param index the item to remove
  32158. @param deleteItem if true, the item that is removed will also be deleted.
  32159. */
  32160. void removeSubItem (const int index,
  32161. const bool deleteItem = true);
  32162. /** Returns the TreeView to which this item belongs. */
  32163. TreeView* getOwnerView() const throw() { return ownerView; }
  32164. /** Returns the item within which this item is contained. */
  32165. TreeViewItem* getParentItem() const throw() { return parentItem; }
  32166. /** True if this item is currently open in the treeview. */
  32167. bool isOpen() const throw();
  32168. /** Opens or closes the item.
  32169. When opened or closed, the item's itemOpennessChanged() method will be called,
  32170. and a subclass should use this callback to create and add any sub-items that
  32171. it needs to.
  32172. @see itemOpennessChanged, mightContainSubItems
  32173. */
  32174. void setOpen (const bool shouldBeOpen);
  32175. /** True if this item is currently selected.
  32176. Use this when painting the node, to decide whether to draw it as selected or not.
  32177. */
  32178. bool isSelected() const throw();
  32179. /** Selects or deselects the item.
  32180. This will cause a callback to itemSelectionChanged()
  32181. */
  32182. void setSelected (const bool shouldBeSelected,
  32183. const bool deselectOtherItemsFirst);
  32184. /** Returns the rectangle that this item occupies.
  32185. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  32186. top-left of the TreeView comp, so this will depend on the scroll-position of
  32187. the tree. If false, it is relative to the top-left of the topmost item in the
  32188. tree (so this would be unaffected by scrolling the view).
  32189. */
  32190. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  32191. /** Sends a signal to the treeview to make it refresh itself.
  32192. Call this if your items have changed and you want the tree to update to reflect
  32193. this.
  32194. */
  32195. void treeHasChanged() const throw();
  32196. /** Sends a repaint message to redraw just this item.
  32197. Note that you should only call this if you want to repaint a superficial change. If
  32198. you're altering the tree's nodes, you should instead call treeHasChanged().
  32199. */
  32200. void repaintItem() const;
  32201. /** Returns the row number of this item in the tree.
  32202. The row number of an item will change according to which items are open.
  32203. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  32204. */
  32205. int getRowNumberInTree() const throw();
  32206. /** Changes whether lines are drawn to connect any sub-items to this item.
  32207. By default, line-drawing is turned on.
  32208. */
  32209. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  32210. /** Tells the tree whether this item can potentially be opened.
  32211. If your item could contain sub-items, this should return true; if it returns
  32212. false then the tree will not try to open the item. This determines whether or
  32213. not the item will be drawn with a 'plus' button next to it.
  32214. */
  32215. virtual bool mightContainSubItems() = 0;
  32216. /** Returns a string to uniquely identify this item.
  32217. If you're planning on using the TreeView::getOpennessState() method, then
  32218. these strings will be used to identify which nodes are open. The string
  32219. should be unique amongst the item's sibling items, but it's ok for there
  32220. to be duplicates at other levels of the tree.
  32221. If you're not going to store the state, then it's ok not to bother implementing
  32222. this method.
  32223. */
  32224. virtual const String getUniqueName() const;
  32225. /** Called when an item is opened or closed.
  32226. When setOpen() is called and the item has specified that it might
  32227. have sub-items with the mightContainSubItems() method, this method
  32228. is called to let the item create or manage its sub-items.
  32229. So when this is called with isNowOpen set to true (i.e. when the item is being
  32230. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  32231. refresh its sub-item list.
  32232. When this is called with isNowOpen set to false, the subclass might want
  32233. to use clearSubItems() to save on space, or it might choose to leave them,
  32234. depending on the nature of the tree.
  32235. You could also use this callback as a trigger to start a background process
  32236. which asynchronously creates sub-items and adds them, if that's more
  32237. appropriate for the task in hand.
  32238. @see mightContainSubItems
  32239. */
  32240. virtual void itemOpennessChanged (bool isNowOpen);
  32241. /** Must return the width required by this item.
  32242. If your item needs to have a particular width in pixels, return that value; if
  32243. you'd rather have it just fill whatever space is available in the treeview,
  32244. return -1.
  32245. If all your items return -1, no horizontal scrollbar will be shown, but if any
  32246. items have fixed widths and extend beyond the width of the treeview, a
  32247. scrollbar will appear.
  32248. Each item can be a different width, but if they change width, you should call
  32249. treeHasChanged() to update the tree.
  32250. */
  32251. virtual int getItemWidth() const { return -1; }
  32252. /** Must return the height required by this item.
  32253. This is the height in pixels that the item will take up. Items in the tree
  32254. can be different heights, but if they change height, you should call
  32255. treeHasChanged() to update the tree.
  32256. */
  32257. virtual int getItemHeight() const { return 20; }
  32258. /** You can override this method to return false if you don't want to allow the
  32259. user to select this item.
  32260. */
  32261. virtual bool canBeSelected() const { return true; }
  32262. /** Creates a component that will be used to represent this item.
  32263. You don't have to implement this method - if it returns 0 then no component
  32264. will be used for the item, and you can just draw it using the paintItem()
  32265. callback. But if you do return a component, it will be positioned in the
  32266. treeview so that it can be used to represent this item.
  32267. The component returned will be managed by the treeview, so always return
  32268. a new component, and don't keep a reference to it, as the treeview will
  32269. delete it later when it goes off the screen or is no longer needed. Also
  32270. bear in mind that if the component keeps a reference to the item that
  32271. created it, that item could be deleted before the component. Its position
  32272. and size will be completely managed by the tree, so don't attempt to move it
  32273. around.
  32274. Something you may want to do with your component is to give it a pointer to
  32275. the TreeView that created it. This is perfectly safe, and there's no danger
  32276. of it becoming a dangling pointer because the TreeView will always delete
  32277. the component before it is itself deleted.
  32278. As long as you stick to these rules you can return whatever kind of
  32279. component you like. It's most useful if you're doing things like drag-and-drop
  32280. of items, or want to use a Label component to edit item names, etc.
  32281. */
  32282. virtual Component* createItemComponent() { return 0; }
  32283. /** Draws the item's contents.
  32284. You can choose to either implement this method and draw each item, or you
  32285. can use createItemComponent() to create a component that will represent the
  32286. item.
  32287. If all you need in your tree is to be able to draw the items and detect when
  32288. the user selects or double-clicks one of them, it's probably enough to
  32289. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  32290. complicated interactions, you may need to use createItemComponent() instead.
  32291. @param g the graphics context to draw into
  32292. @param width the width of the area available for drawing
  32293. @param height the height of the area available for drawing
  32294. */
  32295. virtual void paintItem (Graphics& g, int width, int height);
  32296. /** Draws the item's open/close button.
  32297. If you don't implement this method, the default behaviour is to
  32298. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  32299. it for custom effects.
  32300. */
  32301. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  32302. /** Called when the user clicks on this item.
  32303. If you're using createItemComponent() to create a custom component for the
  32304. item, the mouse-clicks might not make it through to the treeview, but this
  32305. is how you find out about clicks when just drawing each item individually.
  32306. The associated mouse-event details are passed in, so you can find out about
  32307. which button, where it was, etc.
  32308. @see itemDoubleClicked
  32309. */
  32310. virtual void itemClicked (const MouseEvent& e);
  32311. /** Called when the user double-clicks on this item.
  32312. If you're using createItemComponent() to create a custom component for the
  32313. item, the mouse-clicks might not make it through to the treeview, but this
  32314. is how you find out about clicks when just drawing each item individually.
  32315. The associated mouse-event details are passed in, so you can find out about
  32316. which button, where it was, etc.
  32317. If not overridden, the base class method here will open or close the item as
  32318. if the 'plus' button had been clicked.
  32319. @see itemClicked
  32320. */
  32321. virtual void itemDoubleClicked (const MouseEvent& e);
  32322. /** Called when the item is selected or deselected.
  32323. Use this if you want to do something special when the item's selectedness
  32324. changes. By default it'll get repainted when this happens.
  32325. */
  32326. virtual void itemSelectionChanged (bool isNowSelected);
  32327. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  32328. If this returns a non-empty name then when the user drags an item, the treeview will
  32329. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32330. a drag-and-drop operation, using this string as the source description, with the treeview
  32331. itself as the source component.
  32332. If you need more complex drag-and-drop behaviour, you can use custom components for
  32333. the items, and use those to trigger the drag.
  32334. @see DragAndDropContainer::startDragging
  32335. */
  32336. virtual const String getDragSourceDescription();
  32337. /** Sets a flag to indicate that the item wants to be allowed
  32338. to draw all the way across to the left edge of the treeview.
  32339. By default this is false, which means that when the paintItem()
  32340. method is called, its graphics context is clipped to only allow
  32341. drawing within the item's rectangle. If this flag is set to true,
  32342. then the graphics context isn't clipped on its left side, so it
  32343. can draw all the way across to the left margin. Note that the
  32344. context will still have its origin in the same place though, so
  32345. the coordinates of anything to its left will be negative. It's
  32346. mostly useful if you want to draw a wider bar behind the
  32347. highlighted item.
  32348. */
  32349. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  32350. juce_UseDebuggingNewOperator
  32351. private:
  32352. TreeView* ownerView;
  32353. TreeViewItem* parentItem;
  32354. OwnedArray <TreeViewItem> subItems;
  32355. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  32356. int uid;
  32357. bool selected : 1;
  32358. bool redrawNeeded : 1;
  32359. bool drawLinesInside : 1;
  32360. bool drawsInLeftMargin : 1;
  32361. unsigned int openness : 2;
  32362. friend class TreeView;
  32363. friend class TreeViewContentComponent;
  32364. void updatePositions (int newY);
  32365. int getIndentX() const throw();
  32366. void setOwnerView (TreeView* const newOwner) throw();
  32367. void paintRecursively (Graphics& g, int width);
  32368. TreeViewItem* findItemRecursively (int y) throw();
  32369. TreeViewItem* getDeepestOpenParentItem() throw();
  32370. void restoreFromXml (const XmlElement& e);
  32371. XmlElement* createXmlOpenness() const;
  32372. bool isLastOfSiblings() const throw();
  32373. TreeViewItem* getTopLevelItem() throw();
  32374. int getNumRows() const throw();
  32375. TreeViewItem* getItemOnRow (int index) throw();
  32376. void deselectAllRecursively();
  32377. int countSelectedItemsRecursively() const throw();
  32378. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  32379. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  32380. TreeViewItem (const TreeViewItem&);
  32381. const TreeViewItem& operator= (const TreeViewItem&);
  32382. };
  32383. /**
  32384. A tree-view component.
  32385. Use one of these to hold and display a structure of TreeViewItem objects.
  32386. */
  32387. class JUCE_API TreeView : public Component,
  32388. public SettableTooltipClient,
  32389. private AsyncUpdater
  32390. {
  32391. public:
  32392. /** Creates an empty treeview.
  32393. Once you've got a treeview component, you'll need to give it something to
  32394. display, using the setRootItem() method.
  32395. */
  32396. TreeView (const String& componentName = String::empty);
  32397. /** Destructor. */
  32398. ~TreeView();
  32399. /** Sets the item that is displayed in the treeview.
  32400. A tree has a single root item which contains as many sub-items as it needs. If
  32401. you want the tree to contain a number of root items, you should still use a single
  32402. root item above these, but hide it using setRootItemVisible().
  32403. You can pass in 0 to this method to clear the tree and remove its current root item.
  32404. The object passed in will not be deleted by the treeview, it's up to the caller
  32405. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32406. this item until you've removed it from the tree, either by calling setRootItem (0),
  32407. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  32408. to delete it.
  32409. */
  32410. void setRootItem (TreeViewItem* const newRootItem);
  32411. /** Returns the tree's root item.
  32412. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32413. */
  32414. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32415. /** This will remove and delete the current root item.
  32416. It's a convenient way of deleting the item and calling setRootItem (0).
  32417. */
  32418. void deleteRootItem();
  32419. /** Changes whether the tree's root item is shown or not.
  32420. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32421. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32422. will also make sure the root item is open (otherwise the treeview would look empty).
  32423. */
  32424. void setRootItemVisible (const bool shouldBeVisible);
  32425. /** Returns true if the root item is visible.
  32426. @see setRootItemVisible
  32427. */
  32428. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32429. /** Sets whether items are open or closed by default.
  32430. Normally, items are closed until the user opens them, but you can use this
  32431. to make them default to being open until explicitly closed.
  32432. @see areItemsOpenByDefault
  32433. */
  32434. void setDefaultOpenness (const bool isOpenByDefault);
  32435. /** Returns true if the tree's items default to being open.
  32436. @see setDefaultOpenness
  32437. */
  32438. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32439. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32440. You can always select multiple items internally by calling the
  32441. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32442. is allowed to multi-select by clicking on the tree.
  32443. By default it is disabled.
  32444. @see isMultiSelectEnabled
  32445. */
  32446. void setMultiSelectEnabled (const bool canMultiSelect);
  32447. /** Returns whether multi-select has been enabled for the tree.
  32448. @see setMultiSelectEnabled
  32449. */
  32450. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32451. /** Sets a flag to indicate whether to hide the open/close buttons.
  32452. @see areOpenCloseButtonsVisible
  32453. */
  32454. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  32455. /** Returns whether open/close buttons are shown.
  32456. @see setOpenCloseButtonsVisible
  32457. */
  32458. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  32459. /** Deselects any items that are currently selected. */
  32460. void clearSelectedItems();
  32461. /** Returns the number of items that are currently selected.
  32462. @see getSelectedItem, clearSelectedItems
  32463. */
  32464. int getNumSelectedItems() const throw();
  32465. /** Returns one of the selected items in the tree.
  32466. @param index the index, 0 to (getNumSelectedItems() - 1)
  32467. */
  32468. TreeViewItem* getSelectedItem (const int index) const throw();
  32469. /** Returns the number of rows the tree is using.
  32470. This will depend on which items are open.
  32471. @see TreeViewItem::getRowNumberInTree()
  32472. */
  32473. int getNumRowsInTree() const;
  32474. /** Returns the item on a particular row of the tree.
  32475. If the index is out of range, this will return 0.
  32476. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  32477. */
  32478. TreeViewItem* getItemOnRow (int index) const;
  32479. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  32480. void scrollToKeepItemVisible (TreeViewItem* item);
  32481. /** Returns the treeview's Viewport object. */
  32482. Viewport* getViewport() const throw() { return viewport; }
  32483. /** Returns the number of pixels by which each nested level of the tree is indented.
  32484. @see setIndentSize
  32485. */
  32486. int getIndentSize() const throw() { return indentSize; }
  32487. /** Changes the distance by which each nested level of the tree is indented.
  32488. @see getIndentSize
  32489. */
  32490. void setIndentSize (const int newIndentSize);
  32491. /** Saves the current state of open/closed nodes so it can be restored later.
  32492. This takes a snapshot of which nodes have been explicitly opened or closed,
  32493. and records it as XML. To identify node objects it uses the
  32494. TreeViewItem::getUniqueName() method to create named paths. This
  32495. means that the same state of open/closed nodes can be restored to a
  32496. completely different instance of the tree, as long as it contains nodes
  32497. whose unique names are the same.
  32498. The caller is responsible for deleting the object that is returned.
  32499. @param alsoIncludeScrollPosition if this is true, the state will also
  32500. include information about where the
  32501. tree has been scrolled to vertically,
  32502. so this can also be restored
  32503. @see restoreOpennessState
  32504. */
  32505. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32506. /** Restores a previously saved arrangement of open/closed nodes.
  32507. This will try to restore a snapshot of the tree's state that was created by
  32508. the getOpennessState() method. If any of the nodes named in the original
  32509. XML aren't present in this tree, they will be ignored.
  32510. @see getOpennessState
  32511. */
  32512. void restoreOpennessState (const XmlElement& newState);
  32513. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32514. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32515. methods.
  32516. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32517. */
  32518. enum ColourIds
  32519. {
  32520. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32521. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32522. };
  32523. /** @internal */
  32524. void paint (Graphics& g);
  32525. /** @internal */
  32526. void resized();
  32527. /** @internal */
  32528. bool keyPressed (const KeyPress& key);
  32529. /** @internal */
  32530. void colourChanged();
  32531. juce_UseDebuggingNewOperator
  32532. private:
  32533. friend class TreeViewItem;
  32534. friend class TreeViewContentComponent;
  32535. Viewport* viewport;
  32536. CriticalSection nodeAlterationLock;
  32537. TreeViewItem* rootItem;
  32538. int indentSize;
  32539. bool defaultOpenness : 1;
  32540. bool needsRecalculating : 1;
  32541. bool rootItemVisible : 1;
  32542. bool multiSelectEnabled : 1;
  32543. bool openCloseButtonsVisible : 1;
  32544. void itemsChanged() throw();
  32545. void handleAsyncUpdate();
  32546. void moveSelectedRow (int delta);
  32547. void updateButtonUnderMouse (const MouseEvent& e);
  32548. TreeView (const TreeView&);
  32549. const TreeView& operator= (const TreeView&);
  32550. };
  32551. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32552. /********* End of inlined file: juce_TreeView.h *********/
  32553. /**
  32554. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32555. object.
  32556. @see KeyPressMappingSet
  32557. */
  32558. class JUCE_API KeyMappingEditorComponent : public Component,
  32559. public TreeViewItem,
  32560. public ChangeListener,
  32561. private ButtonListener
  32562. {
  32563. public:
  32564. /** Creates a KeyMappingEditorComponent.
  32565. @param mappingSet this is the set of mappings to display and
  32566. edit. Make sure the mappings object is not
  32567. deleted before this component!
  32568. @param showResetToDefaultButton if true, then at the bottom of the
  32569. list, the component will include a 'reset to
  32570. defaults' button.
  32571. */
  32572. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32573. const bool showResetToDefaultButton);
  32574. /** Destructor. */
  32575. virtual ~KeyMappingEditorComponent();
  32576. /** Sets up the colours to use for parts of the component.
  32577. @param mainBackground colour to use for most of the background
  32578. @param textColour colour to use for the text
  32579. */
  32580. void setColours (const Colour& mainBackground,
  32581. const Colour& textColour);
  32582. /** Returns the KeyPressMappingSet that this component is acting upon.
  32583. */
  32584. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32585. /** Can be overridden if some commands need to be excluded from the list.
  32586. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32587. method to decide what to return, but you can override it to handle special cases.
  32588. */
  32589. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32590. /** Can be overridden to indicate that some commands are shown as read-only.
  32591. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32592. method to decide what to return, but you can override it to handle special cases.
  32593. */
  32594. virtual bool isCommandReadOnly (const CommandID commandID);
  32595. /** This can be overridden to let you change the format of the string used
  32596. to describe a keypress.
  32597. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32598. keys that are triggered by something else externally. If you override the
  32599. method, be sure to let the base class's method handle keys you're not
  32600. interested in.
  32601. */
  32602. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32603. /** @internal */
  32604. void parentHierarchyChanged();
  32605. /** @internal */
  32606. void resized();
  32607. /** @internal */
  32608. void changeListenerCallback (void*);
  32609. /** @internal */
  32610. bool mightContainSubItems();
  32611. /** @internal */
  32612. const String getUniqueName() const;
  32613. /** @internal */
  32614. void buttonClicked (Button* button);
  32615. juce_UseDebuggingNewOperator
  32616. private:
  32617. KeyPressMappingSet* mappings;
  32618. TreeView* tree;
  32619. friend class KeyMappingTreeViewItem;
  32620. friend class KeyCategoryTreeViewItem;
  32621. friend class KeyMappingItemComponent;
  32622. friend class KeyMappingChangeButton;
  32623. Colour backgroundColour, textColour;
  32624. TextButton* resetButton;
  32625. void assignNewKey (const CommandID commandID, int index);
  32626. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32627. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32628. };
  32629. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32630. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32631. #endif
  32632. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32633. #endif
  32634. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32635. #endif
  32636. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32637. #endif
  32638. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32639. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32640. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32641. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32642. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32643. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32644. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32645. class MenuBarModel;
  32646. /**
  32647. A class to receive callbacks when a MenuBarModel changes.
  32648. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32649. */
  32650. class JUCE_API MenuBarModelListener
  32651. {
  32652. public:
  32653. /** Destructor. */
  32654. virtual ~MenuBarModelListener() {}
  32655. /** This callback is made when items are changed in the menu bar model.
  32656. */
  32657. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32658. /** This callback is made when an application command is invoked that
  32659. is represented by one of the items in the menu bar model.
  32660. */
  32661. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32662. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32663. };
  32664. /**
  32665. A class for controlling MenuBar components.
  32666. This class is used to tell a MenuBar what menus to show, and to respond
  32667. to a menu being selected.
  32668. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32669. */
  32670. class JUCE_API MenuBarModel : private AsyncUpdater,
  32671. private ApplicationCommandManagerListener
  32672. {
  32673. public:
  32674. MenuBarModel() throw();
  32675. /** Destructor. */
  32676. virtual ~MenuBarModel();
  32677. /** Call this when some of your menu items have changed.
  32678. This method will cause a callback to any MenuBarListener objects that
  32679. are registered with this model.
  32680. If this model is displaying items from an ApplicationCommandManager, you
  32681. can use the setApplicationCommandManagerToWatch() method to cause
  32682. change messages to be sent automatically when the ApplicationCommandManager
  32683. is changed.
  32684. @see addListener, removeListener, MenuBarListener
  32685. */
  32686. void menuItemsChanged();
  32687. /** Tells the menu bar to listen to the specified command manager, and to update
  32688. itself when the commands change.
  32689. This will also allow it to flash a menu name when a command from that menu
  32690. is invoked using a keystroke.
  32691. */
  32692. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32693. /** Registers a listener for callbacks when the menu items in this model change.
  32694. The listener object will get callbacks when this object's menuItemsChanged()
  32695. method is called.
  32696. @see removeListener
  32697. */
  32698. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32699. /** Removes a listener.
  32700. @see addListener
  32701. */
  32702. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32703. /** This method must return a list of the names of the menus. */
  32704. virtual const StringArray getMenuBarNames() = 0;
  32705. /** This should return the popup menu to display for a given top-level menu.
  32706. @param topLevelMenuIndex the index of the top-level menu to show
  32707. @param menuName the name of the top-level menu item to show
  32708. */
  32709. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32710. const String& menuName) = 0;
  32711. /** This is called when a menu item has been clicked on.
  32712. @param menuItemID the item ID of the PopupMenu item that was selected
  32713. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32714. chosen (just in case you've used duplicate ID numbers
  32715. on more than one of the popup menus)
  32716. */
  32717. virtual void menuItemSelected (int menuItemID,
  32718. int topLevelMenuIndex) = 0;
  32719. #if JUCE_MAC || DOXYGEN
  32720. /** MAC ONLY - Sets the model that is currently being shown as the main
  32721. menu bar at the top of the screen on the Mac.
  32722. You can pass 0 to stop the current model being displayed. Be careful
  32723. not to delete a model while it is being used.
  32724. An optional extra menu can be specified, containing items to add to the top of
  32725. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  32726. an apple, it's the one next to it, with your application's name at the top
  32727. and the services menu etc on it). When one of these items is selected, the
  32728. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  32729. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  32730. object then newMenuBarModel must be non-null.
  32731. */
  32732. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  32733. const PopupMenu* extraAppleMenuItems = 0) throw();
  32734. /** MAC ONLY - Returns the menu model that is currently being shown as
  32735. the main menu bar.
  32736. */
  32737. static MenuBarModel* getMacMainMenu() throw();
  32738. #endif
  32739. /** @internal */
  32740. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32741. /** @internal */
  32742. void applicationCommandListChanged();
  32743. /** @internal */
  32744. void handleAsyncUpdate();
  32745. juce_UseDebuggingNewOperator
  32746. private:
  32747. ApplicationCommandManager* manager;
  32748. SortedSet <void*> listeners;
  32749. MenuBarModel (const MenuBarModel&);
  32750. const MenuBarModel& operator= (const MenuBarModel&);
  32751. };
  32752. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32753. /********* End of inlined file: juce_MenuBarModel.h *********/
  32754. /**
  32755. A menu bar component.
  32756. @see MenuBarModel
  32757. */
  32758. class JUCE_API MenuBarComponent : public Component,
  32759. private MenuBarModelListener,
  32760. private Timer
  32761. {
  32762. public:
  32763. /** Creates a menu bar.
  32764. @param model the model object to use to control this bar. You can
  32765. pass 0 into this if you like, and set the model later
  32766. using the setModel() method
  32767. */
  32768. MenuBarComponent (MenuBarModel* const model);
  32769. /** Destructor. */
  32770. ~MenuBarComponent();
  32771. /** Changes the model object to use to control the bar.
  32772. This can be 0, in which case the bar will be empty. Don't delete the object
  32773. that is passed-in while it's still being used by this MenuBar.
  32774. */
  32775. void setModel (MenuBarModel* const newModel);
  32776. /** Pops up one of the menu items.
  32777. This lets you manually open one of the menus - it could be triggered by a
  32778. key shortcut, for example.
  32779. */
  32780. void showMenu (const int menuIndex);
  32781. /** @internal */
  32782. void paint (Graphics& g);
  32783. /** @internal */
  32784. void resized();
  32785. /** @internal */
  32786. void mouseEnter (const MouseEvent& e);
  32787. /** @internal */
  32788. void mouseExit (const MouseEvent& e);
  32789. /** @internal */
  32790. void mouseDown (const MouseEvent& e);
  32791. /** @internal */
  32792. void mouseDrag (const MouseEvent& e);
  32793. /** @internal */
  32794. void mouseUp (const MouseEvent& e);
  32795. /** @internal */
  32796. void mouseMove (const MouseEvent& e);
  32797. /** @internal */
  32798. void inputAttemptWhenModal();
  32799. /** @internal */
  32800. void handleCommandMessage (int commandId);
  32801. /** @internal */
  32802. bool keyPressed (const KeyPress& key);
  32803. /** @internal */
  32804. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32805. /** @internal */
  32806. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32807. const ApplicationCommandTarget::InvocationInfo& info);
  32808. juce_UseDebuggingNewOperator
  32809. private:
  32810. MenuBarModel* model;
  32811. StringArray menuNames;
  32812. Array <int> xPositions;
  32813. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32814. int lastMouseX, lastMouseY;
  32815. bool inModalState;
  32816. Component* currentPopup;
  32817. int getItemAt (int x, int y);
  32818. void updateItemUnderMouse (const int x, const int y);
  32819. void hideCurrentMenu();
  32820. void timerCallback();
  32821. void repaintMenuItem (int index);
  32822. MenuBarComponent (const MenuBarComponent&);
  32823. const MenuBarComponent& operator= (const MenuBarComponent&);
  32824. };
  32825. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32826. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32827. #endif
  32828. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32829. #endif
  32830. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32831. #endif
  32832. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32833. #endif
  32834. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32835. /********* Start of inlined file: juce_ComponentDragger.h *********/
  32836. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32837. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32838. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32839. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32840. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32841. /**
  32842. A class that imposes restrictions on a Component's size or position.
  32843. This is used by classes such as ResizableCornerComponent,
  32844. ResizableBorderComponent and ResizableWindow.
  32845. The base class can impose some basic size and position limits, but you can
  32846. also subclass this for custom uses.
  32847. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  32848. */
  32849. class JUCE_API ComponentBoundsConstrainer
  32850. {
  32851. public:
  32852. /** When first created, the object will not impose any restrictions on the components. */
  32853. ComponentBoundsConstrainer() throw();
  32854. /** Destructor. */
  32855. virtual ~ComponentBoundsConstrainer();
  32856. /** Imposes a minimum width limit. */
  32857. void setMinimumWidth (const int minimumWidth) throw();
  32858. /** Returns the current minimum width. */
  32859. int getMinimumWidth() const throw() { return minW; }
  32860. /** Imposes a maximum width limit. */
  32861. void setMaximumWidth (const int maximumWidth) throw();
  32862. /** Returns the current maximum width. */
  32863. int getMaximumWidth() const throw() { return maxW; }
  32864. /** Imposes a minimum height limit. */
  32865. void setMinimumHeight (const int minimumHeight) throw();
  32866. /** Returns the current minimum height. */
  32867. int getMinimumHeight() const throw() { return minH; }
  32868. /** Imposes a maximum height limit. */
  32869. void setMaximumHeight (const int maximumHeight) throw();
  32870. /** Returns the current maximum height. */
  32871. int getMaximumHeight() const throw() { return maxH; }
  32872. /** Imposes a minimum width and height limit. */
  32873. void setMinimumSize (const int minimumWidth,
  32874. const int minimumHeight) throw();
  32875. /** Imposes a maximum width and height limit. */
  32876. void setMaximumSize (const int maximumWidth,
  32877. const int maximumHeight) throw();
  32878. /** Set all the maximum and minimum dimensions. */
  32879. void setSizeLimits (const int minimumWidth,
  32880. const int minimumHeight,
  32881. const int maximumWidth,
  32882. const int maximumHeight) throw();
  32883. /** Sets the amount by which the component is allowed to go off-screen.
  32884. The values indicate how many pixels must remain on-screen when dragged off
  32885. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  32886. when the component goes off the top of the screen, its y-position will be
  32887. clipped so that there are always at least 10 pixels on-screen. In other words,
  32888. the lowest y-position it can take would be (10 - the component's height).
  32889. If you pass 0 or less for one of these amounts, the component is allowed
  32890. to move beyond that edge completely, with no restrictions at all.
  32891. If you pass a very large number (i.e. larger that the dimensions of the
  32892. component itself), then the component won't be allowed to overlap that
  32893. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  32894. the component will bump into the left side of the screen and go no further.
  32895. */
  32896. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  32897. const int minimumWhenOffTheLeft,
  32898. const int minimumWhenOffTheBottom,
  32899. const int minimumWhenOffTheRight) throw();
  32900. /** Specifies a width-to-height ratio that the resizer should always maintain.
  32901. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  32902. will always be maintained as this multiple of the height.
  32903. @see setResizeLimits
  32904. */
  32905. void setFixedAspectRatio (const double widthOverHeight) throw();
  32906. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  32907. If no aspect ratio is being enforced, this will return 0.
  32908. */
  32909. double getFixedAspectRatio() const throw();
  32910. /** This callback changes the given co-ordinates to impose whatever the current
  32911. constraints are set to be.
  32912. @param x the x position that should be examined and adjusted
  32913. @param y the y position that should be examined and adjusted
  32914. @param w the width that should be examined and adjusted
  32915. @param h the height that should be examined and adjusted
  32916. @param previousBounds the component's current size
  32917. @param limits the region in which the component can be positioned
  32918. @param isStretchingTop whether the top edge of the component is being resized
  32919. @param isStretchingLeft whether the left edge of the component is being resized
  32920. @param isStretchingBottom whether the bottom edge of the component is being resized
  32921. @param isStretchingRight whether the right edge of the component is being resized
  32922. */
  32923. virtual void checkBounds (int& x, int& y, int& w, int& h,
  32924. const Rectangle& previousBounds,
  32925. const Rectangle& limits,
  32926. const bool isStretchingTop,
  32927. const bool isStretchingLeft,
  32928. const bool isStretchingBottom,
  32929. const bool isStretchingRight);
  32930. /** This callback happens when the resizer is about to start dragging. */
  32931. virtual void resizeStart();
  32932. /** This callback happens when the resizer has finished dragging. */
  32933. virtual void resizeEnd();
  32934. /** Checks the given bounds, and then sets the component to the corrected size. */
  32935. void setBoundsForComponent (Component* const component,
  32936. int x, int y, int w, int h,
  32937. const bool isStretchingTop,
  32938. const bool isStretchingLeft,
  32939. const bool isStretchingBottom,
  32940. const bool isStretchingRight);
  32941. /** Performs a check on the current size of a component, and moves or resizes
  32942. it if it fails the constraints.
  32943. */
  32944. void checkComponentBounds (Component* component);
  32945. /** Called by setBoundsForComponent() to apply a new constrained size to a
  32946. component.
  32947. By default this just calls setBounds(), but it virtual in case it's needed for
  32948. extremely cunning purposes.
  32949. */
  32950. virtual void applyBoundsToComponent (Component* component,
  32951. int x, int y, int w, int h);
  32952. juce_UseDebuggingNewOperator
  32953. private:
  32954. int minW, maxW, minH, maxH;
  32955. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  32956. double aspectRatio;
  32957. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  32958. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  32959. };
  32960. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32961. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32962. /**
  32963. An object to take care of the logic for dragging components around with the mouse.
  32964. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  32965. then in your mouseDrag() callback, call dragComponent().
  32966. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  32967. to limit the component's position and keep it on-screen.
  32968. e.g. @code
  32969. class MyDraggableComp
  32970. {
  32971. ComponentDragger myDragger;
  32972. void mouseDown (const MouseEvent& e)
  32973. {
  32974. myDragger.startDraggingComponent (this, 0);
  32975. }
  32976. void mouseDrag (const MouseEvent& e)
  32977. {
  32978. myDragger.dragComponent (this, e);
  32979. }
  32980. };
  32981. @endcode
  32982. */
  32983. class JUCE_API ComponentDragger
  32984. {
  32985. public:
  32986. /** Creates a ComponentDragger. */
  32987. ComponentDragger();
  32988. /** Destructor. */
  32989. virtual ~ComponentDragger();
  32990. /** Call this from your component's mouseDown() method, to prepare for dragging.
  32991. @param componentToDrag the component that you want to drag
  32992. @param constrainer a constrainer object to use to keep the component
  32993. from going offscreen
  32994. @see dragComponent
  32995. */
  32996. void startDraggingComponent (Component* const componentToDrag,
  32997. ComponentBoundsConstrainer* constrainer);
  32998. /** Call this from your mouseDrag() callback to move the component.
  32999. This will move the component, but will first check the validity of the
  33000. component's new position using the checkPosition() method, which you
  33001. can override if you need to enforce special positioning limits on the
  33002. component.
  33003. @param componentToDrag the component that you want to drag
  33004. @param e the current mouse-drag event
  33005. @see dragComponent
  33006. */
  33007. void dragComponent (Component* const componentToDrag,
  33008. const MouseEvent& e);
  33009. juce_UseDebuggingNewOperator
  33010. private:
  33011. ComponentBoundsConstrainer* constrainer;
  33012. int originalX, originalY;
  33013. };
  33014. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33015. /********* End of inlined file: juce_ComponentDragger.h *********/
  33016. #endif
  33017. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33018. #endif
  33019. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33020. #endif
  33021. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33022. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  33023. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33024. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33025. /**
  33026. Components derived from this class can have files dropped onto them by an external application.
  33027. @see DragAndDropContainer
  33028. */
  33029. class JUCE_API FileDragAndDropTarget
  33030. {
  33031. public:
  33032. /** Destructor. */
  33033. virtual ~FileDragAndDropTarget() {}
  33034. /** Callback to check whether this target is interested in the set of files being offered.
  33035. Note that this will be called repeatedly when the user is dragging the mouse around over your
  33036. component, so don't do anything time-consuming in here, like opening the files to have a look
  33037. inside them!
  33038. @param files the set of (absolute) pathnames of the files that the user is dragging
  33039. @returns true if this component wants to receive the other callbacks regarging this
  33040. type of object; if it returns false, no other callbacks will be made.
  33041. */
  33042. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  33043. /** Callback to indicate that some files are being dragged over this component.
  33044. This gets called when the user moves the mouse into this component while dragging.
  33045. Use this callback as a trigger to make your component repaint itself to give the
  33046. user feedback about whether the files can be dropped here or not.
  33047. @param files the set of (absolute) pathnames of the files that the user is dragging
  33048. @param x the mouse x position, relative to this component
  33049. @param y the mouse y position, relative to this component
  33050. */
  33051. virtual void fileDragEnter (const StringArray& files, int x, int y);
  33052. /** Callback to indicate that the user is dragging some files over this component.
  33053. This gets called when the user moves the mouse over this component while dragging.
  33054. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33055. this lets you know what happens in-between.
  33056. @param files the set of (absolute) pathnames of the files that the user is dragging
  33057. @param x the mouse x position, relative to this component
  33058. @param y the mouse y position, relative to this component
  33059. */
  33060. virtual void fileDragMove (const StringArray& files, int x, int y);
  33061. /** Callback to indicate that the mouse has moved away from this component.
  33062. This gets called when the user moves the mouse out of this component while dragging
  33063. the files.
  33064. If you've used fileDragEnter() to repaint your component and give feedback, use this
  33065. as a signal to repaint it in its normal state.
  33066. @param files the set of (absolute) pathnames of the files that the user is dragging
  33067. */
  33068. virtual void fileDragExit (const StringArray& files);
  33069. /** Callback to indicate that the user has dropped the files onto this component.
  33070. When the user drops the files, this get called, and you can use the files in whatever
  33071. way is appropriate.
  33072. Note that after this is called, the fileDragExit method may not be called, so you should
  33073. clean up in here if there's anything you need to do when the drag finishes.
  33074. @param files the set of (absolute) pathnames of the files that the user is dragging
  33075. @param x the mouse x position, relative to this component
  33076. @param y the mouse y position, relative to this component
  33077. */
  33078. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  33079. };
  33080. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33081. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  33082. #endif
  33083. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33084. /********* Start of inlined file: juce_LassoComponent.h *********/
  33085. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33086. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33087. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  33088. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33089. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33090. /** Manages a list of selectable items.
  33091. Use one of these to keep a track of things that the user has highlighted, like
  33092. icons or things in a list.
  33093. The class is templated so that you can use it to hold either a set of pointers
  33094. to objects, or a set of ID numbers or handles, for cases where each item may
  33095. not always have a corresponding object.
  33096. To be informed when items are selected/deselected, register a ChangeListener with
  33097. this object.
  33098. @see SelectableObject
  33099. */
  33100. template <class SelectableItemType>
  33101. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  33102. {
  33103. public:
  33104. /** Creates an empty set. */
  33105. SelectedItemSet()
  33106. {
  33107. }
  33108. /** Creates a set based on an array of items. */
  33109. SelectedItemSet (const Array <SelectableItemType>& items)
  33110. : selectedItems (items)
  33111. {
  33112. }
  33113. /** Creates a copy of another set. */
  33114. SelectedItemSet (const SelectedItemSet& other)
  33115. : selectedItems (other.selectedItems)
  33116. {
  33117. }
  33118. /** Creates a copy of another set. */
  33119. const SelectedItemSet& operator= (const SelectedItemSet& other)
  33120. {
  33121. if (selectedItems != other.selectedItems)
  33122. {
  33123. selectedItems = other.selectedItems;
  33124. changed();
  33125. }
  33126. return *this;
  33127. }
  33128. /** Destructor. */
  33129. ~SelectedItemSet()
  33130. {
  33131. }
  33132. /** Clears any other currently selected items, and selects this item.
  33133. If this item is already the only thing selected, no change notification
  33134. will be sent out.
  33135. @see addToSelection, addToSelectionBasedOnModifiers
  33136. */
  33137. void selectOnly (SelectableItemType item)
  33138. {
  33139. if (isSelected (item))
  33140. {
  33141. for (int i = selectedItems.size(); --i >= 0;)
  33142. {
  33143. if (selectedItems.getUnchecked(i) != item)
  33144. {
  33145. deselect (selectedItems.getUnchecked(i));
  33146. i = jmin (i, selectedItems.size());
  33147. }
  33148. }
  33149. }
  33150. else
  33151. {
  33152. deselectAll();
  33153. changed();
  33154. selectedItems.add (item);
  33155. itemSelected (item);
  33156. }
  33157. }
  33158. /** Selects an item.
  33159. If the item is already selected, no change notification will be sent out.
  33160. @see selectOnly, addToSelectionBasedOnModifiers
  33161. */
  33162. void addToSelection (SelectableItemType item)
  33163. {
  33164. if (! isSelected (item))
  33165. {
  33166. changed();
  33167. selectedItems.add (item);
  33168. itemSelected (item);
  33169. }
  33170. }
  33171. /** Selects or deselects an item.
  33172. This will use the modifier keys to decide whether to deselect other items
  33173. first.
  33174. So if the shift key is held down, the item will be added without deselecting
  33175. anything (same as calling addToSelection() )
  33176. If no modifiers are down, the current selection will be cleared first (same
  33177. as calling selectOnly() )
  33178. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  33179. so it'll be added to the set unless it's already there, in which case it'll be
  33180. deselected.
  33181. If the items that you're selecting can also be dragged, you may need to use the
  33182. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  33183. subtleties of this kind of usage.
  33184. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  33185. */
  33186. void addToSelectionBasedOnModifiers (SelectableItemType item,
  33187. const ModifierKeys& modifiers)
  33188. {
  33189. if (modifiers.isShiftDown())
  33190. {
  33191. addToSelection (item);
  33192. }
  33193. else if (modifiers.isCommandDown())
  33194. {
  33195. if (isSelected (item))
  33196. deselect (item);
  33197. else
  33198. addToSelection (item);
  33199. }
  33200. else
  33201. {
  33202. selectOnly (item);
  33203. }
  33204. }
  33205. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  33206. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  33207. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  33208. makes it easy to handle multiple-selection of sets of objects that can also
  33209. be dragged.
  33210. For example, if you have several items already selected, and you click on
  33211. one of them (without dragging), then you'd expect this to deselect the other, and
  33212. just select the item you clicked on. But if you had clicked on this item and
  33213. dragged it, you'd have expected them all to stay selected.
  33214. When you call this method, you'll need to store the boolean result, because the
  33215. addToSelectionOnMouseUp() method will need to be know this value.
  33216. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  33217. */
  33218. bool addToSelectionOnMouseDown (SelectableItemType item,
  33219. const ModifierKeys& modifiers)
  33220. {
  33221. if (isSelected (item))
  33222. {
  33223. return ! modifiers.isPopupMenu();
  33224. }
  33225. else
  33226. {
  33227. addToSelectionBasedOnModifiers (item, modifiers);
  33228. return false;
  33229. }
  33230. }
  33231. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  33232. Call this during a mouseUp callback, when you have previously called the
  33233. addToSelectionOnMouseDown() method during your mouseDown event.
  33234. See addToSelectionOnMouseDown() for more info
  33235. @param item the item to select (or deselect)
  33236. @param modifiers the modifiers from the mouse-up event
  33237. @param wasItemDragged true if your item was dragged during the mouse click
  33238. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  33239. back from the addToSelectionOnMouseDown() call that you
  33240. should have made during the matching mouseDown event
  33241. */
  33242. void addToSelectionOnMouseUp (SelectableItemType item,
  33243. const ModifierKeys& modifiers,
  33244. const bool wasItemDragged,
  33245. const bool resultOfMouseDownSelectMethod)
  33246. {
  33247. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  33248. addToSelectionBasedOnModifiers (item, modifiers);
  33249. }
  33250. /** Deselects an item. */
  33251. void deselect (SelectableItemType item)
  33252. {
  33253. const int i = selectedItems.indexOf (item);
  33254. if (i >= 0)
  33255. {
  33256. changed();
  33257. itemDeselected (selectedItems.remove (i));
  33258. }
  33259. }
  33260. /** Deselects all items. */
  33261. void deselectAll()
  33262. {
  33263. if (selectedItems.size() > 0)
  33264. {
  33265. changed();
  33266. for (int i = selectedItems.size(); --i >= 0;)
  33267. {
  33268. itemDeselected (selectedItems.remove (i));
  33269. i = jmin (i, selectedItems.size());
  33270. }
  33271. }
  33272. }
  33273. /** Returns the number of currently selected items.
  33274. @see getSelectedItem
  33275. */
  33276. int getNumSelected() const throw()
  33277. {
  33278. return selectedItems.size();
  33279. }
  33280. /** Returns one of the currently selected items.
  33281. Returns 0 if the index is out-of-range.
  33282. @see getNumSelected
  33283. */
  33284. SelectableItemType getSelectedItem (const int index) const throw()
  33285. {
  33286. return selectedItems [index];
  33287. }
  33288. /** True if this item is currently selected. */
  33289. bool isSelected (const SelectableItemType item) const throw()
  33290. {
  33291. return selectedItems.contains (item);
  33292. }
  33293. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  33294. /** Can be overridden to do special handling when an item is selected.
  33295. For example, if the item is an object, you might want to call it and tell
  33296. it that it's being selected.
  33297. */
  33298. virtual void itemSelected (SelectableItemType item) {}
  33299. /** Can be overridden to do special handling when an item is deselected.
  33300. For example, if the item is an object, you might want to call it and tell
  33301. it that it's being deselected.
  33302. */
  33303. virtual void itemDeselected (SelectableItemType item) {}
  33304. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  33305. */
  33306. void changed (const bool synchronous = false)
  33307. {
  33308. if (synchronous)
  33309. sendSynchronousChangeMessage (this);
  33310. else
  33311. sendChangeMessage (this);
  33312. }
  33313. juce_UseDebuggingNewOperator
  33314. private:
  33315. Array <SelectableItemType> selectedItems;
  33316. };
  33317. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33318. /********* End of inlined file: juce_SelectedItemSet.h *********/
  33319. /**
  33320. A class used by the LassoComponent to manage the things that it selects.
  33321. This allows the LassoComponent to find out which items are within the lasso,
  33322. and to change the list of selected items.
  33323. @see LassoComponent, SelectedItemSet
  33324. */
  33325. template <class SelectableItemType>
  33326. class LassoSource
  33327. {
  33328. public:
  33329. /** Destructor. */
  33330. virtual ~LassoSource() {}
  33331. /** Returns the set of items that lie within a given lassoable region.
  33332. Your implementation of this method must find all the relevent items that lie
  33333. within the given rectangle. and add them to the itemsFound array.
  33334. The co-ordinates are relative to the top-left of the lasso component's parent
  33335. component. (i.e. they are the same as the size and position of the lasso
  33336. component itself).
  33337. */
  33338. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  33339. int x, int y, int width, int height) = 0;
  33340. /** Returns the SelectedItemSet that the lasso should update.
  33341. This set will be continuously updated by the LassoComponent as it gets
  33342. dragged around, so make sure that you've got a ChangeListener attached to
  33343. the set so that your UI objects will know when the selection changes and
  33344. be able to update themselves appropriately.
  33345. */
  33346. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  33347. };
  33348. /**
  33349. A component that acts as a rectangular selection region, which you drag with
  33350. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  33351. To use one of these:
  33352. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  33353. component, and call its beginLasso() method, giving it a
  33354. suitable LassoSource object that it can use to find out which items are in
  33355. the active area.
  33356. - Each time your parent component gets a mouseDrag event, call dragLasso()
  33357. to update the lasso's position - it will use its LassoSource to calculate and
  33358. update the current selection.
  33359. - After the drag has finished and you get a mouseUp callback, you should call
  33360. endLasso() to clean up. This will make the lasso component invisible, and you
  33361. can remove it from the parent component, or delete it.
  33362. The class takes into account the modifier keys that are being held down while
  33363. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  33364. be added to the original selection; if ctrl or command is pressed, they will be
  33365. xor'ed with any previously selected items.
  33366. @see LassoSource, SelectedItemSet
  33367. */
  33368. template <class SelectableItemType>
  33369. class LassoComponent : public Component
  33370. {
  33371. public:
  33372. /** Creates a Lasso component.
  33373. The fill colour is used to fill the lasso'ed rectangle, and the outline
  33374. colour is used to draw a line around its edge.
  33375. */
  33376. LassoComponent (const int outlineThickness_ = 1)
  33377. : source (0),
  33378. outlineThickness (outlineThickness_)
  33379. {
  33380. }
  33381. /** Destructor. */
  33382. ~LassoComponent()
  33383. {
  33384. }
  33385. /** Call this in your mouseDown event, to initialise a drag.
  33386. Pass in a suitable LassoSource object which the lasso will use to find
  33387. the items and change the selection.
  33388. After using this method to initialise the lasso, repeatedly call dragLasso()
  33389. in your component's mouseDrag callback.
  33390. @see dragLasso, endLasso, LassoSource
  33391. */
  33392. void beginLasso (const MouseEvent& e,
  33393. LassoSource <SelectableItemType>* const lassoSource)
  33394. {
  33395. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  33396. jassert (lassoSource != 0); // the source can't be null!
  33397. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  33398. source = lassoSource;
  33399. if (lassoSource != 0)
  33400. originalSelection = lassoSource->getLassoSelection().getItemArray();
  33401. setSize (0, 0);
  33402. }
  33403. /** Call this in your mouseDrag event, to update the lasso's position.
  33404. This must be repeatedly calling when the mouse is dragged, after you've
  33405. first initialised the lasso with beginLasso().
  33406. This method takes into account the modifier keys that are being held down, so
  33407. if shift is pressed, then the lassoed items will be added to any that were
  33408. previously selected; if ctrl or command is pressed, then they will be xor'ed
  33409. with previously selected items.
  33410. @see beginLasso, endLasso
  33411. */
  33412. void dragLasso (const MouseEvent& e)
  33413. {
  33414. if (source != 0)
  33415. {
  33416. const int x1 = e.getMouseDownX();
  33417. const int y1 = e.getMouseDownY();
  33418. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  33419. setVisible (true);
  33420. Array <SelectableItemType> itemsInLasso;
  33421. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33422. if (e.mods.isShiftDown())
  33423. {
  33424. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33425. itemsInLasso.addArray (originalSelection);
  33426. }
  33427. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33428. {
  33429. Array <SelectableItemType> originalMinusNew (originalSelection);
  33430. originalMinusNew.removeValuesIn (itemsInLasso);
  33431. itemsInLasso.removeValuesIn (originalSelection);
  33432. itemsInLasso.addArray (originalMinusNew);
  33433. }
  33434. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33435. }
  33436. }
  33437. /** Call this in your mouseUp event, after the lasso has been dragged.
  33438. @see beginLasso, dragLasso
  33439. */
  33440. void endLasso()
  33441. {
  33442. source = 0;
  33443. originalSelection.clear();
  33444. setVisible (false);
  33445. }
  33446. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33447. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33448. methods.
  33449. Note that you can also use the constants from TextEditor::ColourIds to change the
  33450. colour of the text editor that is opened when a label is editable.
  33451. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33452. */
  33453. enum ColourIds
  33454. {
  33455. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  33456. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  33457. };
  33458. /** @internal */
  33459. void paint (Graphics& g)
  33460. {
  33461. g.fillAll (findColour (lassoFillColourId));
  33462. g.setColour (findColour (lassoOutlineColourId));
  33463. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33464. // this suggests that you've left a lasso comp lying around after the
  33465. // mouse drag has finished.. Be careful to call endLasso() when you get a
  33466. // mouse-up event.
  33467. jassert (isMouseButtonDownAnywhere());
  33468. }
  33469. /** @internal */
  33470. bool hitTest (int x, int y) { return false; }
  33471. juce_UseDebuggingNewOperator
  33472. private:
  33473. Array <SelectableItemType> originalSelection;
  33474. LassoSource <SelectableItemType>* source;
  33475. int outlineThickness;
  33476. };
  33477. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33478. /********* End of inlined file: juce_LassoComponent.h *********/
  33479. #endif
  33480. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  33481. #endif
  33482. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  33483. #endif
  33484. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33485. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  33486. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33487. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33488. /**
  33489. Monitors a component for mouse activity, and triggers a callback
  33490. when the mouse hovers in one place for a specified length of time.
  33491. To use a hover-detector, just create one and call its setHoverComponent()
  33492. method to start it watching a component. You can call setHoverComponent (0)
  33493. to make it inactive.
  33494. (Be careful not to delete a component that's being monitored without first
  33495. stopping or deleting the hover detector).
  33496. */
  33497. class JUCE_API MouseHoverDetector
  33498. {
  33499. public:
  33500. /** Creates a hover detector.
  33501. Initially the object is inactive, and you need to tell it which component
  33502. to monitor, using the setHoverComponent() method.
  33503. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  33504. needs to stay still before the mouseHovered() method
  33505. is invoked. You can change this setting later with
  33506. the setHoverTimeMillisecs() method
  33507. */
  33508. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  33509. /** Destructor. */
  33510. virtual ~MouseHoverDetector();
  33511. /** Changes the time for which the mouse has to stay still before it's considered
  33512. to be hovering.
  33513. */
  33514. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  33515. /** Changes the component that's being monitored for hovering.
  33516. Be careful not to delete a component that's being monitored without first
  33517. stopping or deleting the hover detector.
  33518. */
  33519. void setHoverComponent (Component* const newSourceComponent);
  33520. protected:
  33521. /** Called back when the mouse hovers.
  33522. After the mouse has stayed still over the component for the length of time
  33523. specified by setHoverTimeMillisecs(), this method will be invoked.
  33524. When the mouse is first moved after this callback has occurred, the
  33525. mouseMovedAfterHover() method will be called.
  33526. @param mouseX the mouse's X position relative to the component being monitored
  33527. @param mouseY the mouse's Y position relative to the component being monitored
  33528. */
  33529. virtual void mouseHovered (int mouseX,
  33530. int mouseY) = 0;
  33531. /** Called when the mouse is moved away after just having hovered. */
  33532. virtual void mouseMovedAfterHover() = 0;
  33533. private:
  33534. class JUCE_API HoverDetectorInternal : public MouseListener,
  33535. public Timer
  33536. {
  33537. public:
  33538. MouseHoverDetector* owner;
  33539. int lastX, lastY;
  33540. void timerCallback();
  33541. void mouseEnter (const MouseEvent&);
  33542. void mouseExit (const MouseEvent&);
  33543. void mouseDown (const MouseEvent&);
  33544. void mouseUp (const MouseEvent&);
  33545. void mouseMove (const MouseEvent&);
  33546. void mouseWheelMove (const MouseEvent&, float, float);
  33547. } internalTimer;
  33548. friend class HoverDetectorInternal;
  33549. Component* source;
  33550. int hoverTimeMillisecs;
  33551. bool hasJustHovered;
  33552. void hoverTimerCallback();
  33553. void checkJustHoveredCallback();
  33554. };
  33555. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33556. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33557. #endif
  33558. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33559. #endif
  33560. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33561. #endif
  33562. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33563. #endif
  33564. #ifndef __JUCE_LABEL_JUCEHEADER__
  33565. #endif
  33566. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33567. #endif
  33568. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33569. /********* Start of inlined file: juce_ProgressBar.h *********/
  33570. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33571. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33572. /**
  33573. A progress bar component.
  33574. To use this, just create one and make it visible. It'll run its own timer
  33575. to keep an eye on a variable that you give it, and will automatically
  33576. redraw itself when the variable changes.
  33577. For an easy way of running a background task with a dialog box showing its
  33578. progress, see the ThreadWithProgressWindow class.
  33579. @see ThreadWithProgressWindow
  33580. */
  33581. class JUCE_API ProgressBar : public Component,
  33582. public SettableTooltipClient,
  33583. private Timer
  33584. {
  33585. public:
  33586. /** Creates a ProgressBar.
  33587. @param progress pass in a reference to a double that you're going to
  33588. update with your task's progress. The ProgressBar will
  33589. monitor the value of this variable and will redraw itself
  33590. when the value changes. The range is from 0 to 1.0. Obviously
  33591. you'd better be careful not to delete this variable while the
  33592. ProgressBar still exists!
  33593. */
  33594. ProgressBar (double& progress);
  33595. /** Destructor. */
  33596. ~ProgressBar();
  33597. /** Turns the percentage display on or off.
  33598. By default this is on, and the progress bar will display a text string showing
  33599. its current percentage.
  33600. */
  33601. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33602. /** Gives the progress bar a string to display inside it.
  33603. If you call this, it will turn off the percentage display.
  33604. @see setPercentageDisplay
  33605. */
  33606. void setTextToDisplay (const String& text);
  33607. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33608. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33609. methods.
  33610. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33611. */
  33612. enum ColourIds
  33613. {
  33614. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33615. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33616. classes will probably use variations on this colour. */
  33617. };
  33618. juce_UseDebuggingNewOperator
  33619. protected:
  33620. /** @internal */
  33621. void paint (Graphics& g);
  33622. /** @internal */
  33623. void lookAndFeelChanged();
  33624. /** @internal */
  33625. void visibilityChanged();
  33626. /** @internal */
  33627. void colourChanged();
  33628. private:
  33629. double& progress;
  33630. double currentValue;
  33631. bool displayPercentage;
  33632. String displayedMessage, currentMessage;
  33633. void timerCallback();
  33634. ProgressBar (const ProgressBar&);
  33635. const ProgressBar& operator= (const ProgressBar&);
  33636. };
  33637. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33638. /********* End of inlined file: juce_ProgressBar.h *********/
  33639. #endif
  33640. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33641. /********* Start of inlined file: juce_Slider.h *********/
  33642. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33643. #define __JUCE_SLIDER_JUCEHEADER__
  33644. /********* Start of inlined file: juce_SliderListener.h *********/
  33645. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33646. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33647. class Slider;
  33648. /**
  33649. A class for receiving callbacks from a Slider.
  33650. To be told when a slider's value changes, you can register a SliderListener
  33651. object using Slider::addListener().
  33652. @see Slider::addListener, Slider::removeListener
  33653. */
  33654. class JUCE_API SliderListener
  33655. {
  33656. public:
  33657. /** Destructor. */
  33658. virtual ~SliderListener() {}
  33659. /** Called when the slider's value is changed.
  33660. This may be caused by dragging it, or by typing in its text entry box,
  33661. or by a call to Slider::setValue().
  33662. You can find out the new value using Slider::getValue().
  33663. @see Slider::valueChanged
  33664. */
  33665. virtual void sliderValueChanged (Slider* slider) = 0;
  33666. /** Called when the slider is about to be dragged.
  33667. This is called when a drag begins, then it's followed by multiple calls
  33668. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33669. user lets go.
  33670. @see sliderDragEnded, Slider::startedDragging
  33671. */
  33672. virtual void sliderDragStarted (Slider* slider);
  33673. /** Called after a drag operation has finished.
  33674. @see sliderDragStarted, Slider::stoppedDragging
  33675. */
  33676. virtual void sliderDragEnded (Slider* slider);
  33677. };
  33678. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33679. /********* End of inlined file: juce_SliderListener.h *********/
  33680. /**
  33681. A slider control for changing a value.
  33682. The slider can be horizontal, vertical, or rotary, and can optionally have
  33683. a text-box inside it to show an editable display of the current value.
  33684. To use it, create a Slider object and use the setSliderStyle() method
  33685. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33686. To define the values that it can be set to, see the setRange() and setValue() methods.
  33687. There are also lots of custom tweaks you can do by subclassing and overriding
  33688. some of the virtual methods, such as changing the scaling, changing the format of
  33689. the text display, custom ways of limiting the values, etc.
  33690. You can register SliderListeners with a slider, which will be informed when the value
  33691. changes, or a subclass can override valueChanged() to be informed synchronously.
  33692. @see SliderListener
  33693. */
  33694. class JUCE_API Slider : public Component,
  33695. public SettableTooltipClient,
  33696. private AsyncUpdater,
  33697. private ButtonListener,
  33698. private LabelListener
  33699. {
  33700. public:
  33701. /** Creates a slider.
  33702. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33703. setRange(), etc.
  33704. */
  33705. Slider (const String& componentName);
  33706. /** Destructor. */
  33707. ~Slider();
  33708. /** The types of slider available.
  33709. @see setSliderStyle, setRotaryParameters
  33710. */
  33711. enum SliderStyle
  33712. {
  33713. LinearHorizontal, /**< A traditional horizontal slider. */
  33714. LinearVertical, /**< A traditional vertical slider. */
  33715. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33716. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33717. @see setRotaryParameters */
  33718. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33719. @see setRotaryParameters */
  33720. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33721. @see setRotaryParameters */
  33722. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33723. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33724. @see setMinValue, setMaxValue */
  33725. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33726. @see setMinValue, setMaxValue */
  33727. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33728. value, with the current value being somewhere between them.
  33729. @see setMinValue, setMaxValue */
  33730. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33731. value, with the current value being somewhere between them.
  33732. @see setMinValue, setMaxValue */
  33733. };
  33734. /** Changes the type of slider interface being used.
  33735. @param newStyle the type of interface
  33736. @see setRotaryParameters, setVelocityBasedMode,
  33737. */
  33738. void setSliderStyle (const SliderStyle newStyle);
  33739. /** Returns the slider's current style.
  33740. @see setSliderStyle
  33741. */
  33742. SliderStyle getSliderStyle() const throw() { return style; }
  33743. /** Changes the properties of a rotary slider.
  33744. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33745. the slider's minimum value is represented
  33746. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33747. the slider's maximum value is represented. This must be
  33748. greater than startAngleRadians
  33749. @param stopAtEnd if true, then when the slider is dragged around past the
  33750. minimum or maximum, it'll stop there; if false, it'll wrap
  33751. back to the opposite value
  33752. */
  33753. void setRotaryParameters (const float startAngleRadians,
  33754. const float endAngleRadians,
  33755. const bool stopAtEnd);
  33756. /** Sets the distance the mouse has to move to drag the slider across
  33757. the full extent of its range.
  33758. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33759. relative mouse movements to adjust the slider.
  33760. */
  33761. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33762. /** Changes the way the the mouse is used when dragging the slider.
  33763. If true, this will turn on velocity-sensitive dragging, so that
  33764. the faster the mouse moves, the bigger the movement to the slider. This
  33765. helps when making accurate adjustments if the slider's range is quite large.
  33766. If false, the slider will just try to snap to wherever the mouse is.
  33767. */
  33768. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33769. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33770. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33771. or if you're holding down ctrl.
  33772. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33773. @param threshold the minimum number of pixels that the mouse needs to move for it
  33774. to be treated as a movement
  33775. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33776. the threshold is reached
  33777. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33778. key to toggle velocity-sensitive mode
  33779. */
  33780. void setVelocityModeParameters (const double sensitivity = 1.0,
  33781. const int threshold = 1,
  33782. const double offset = 0.0,
  33783. const bool userCanPressKeyToSwapMode = true) throw();
  33784. /** Sets up a skew factor to alter the way values are distributed.
  33785. You may want to use a range of values on the slider where more accuracy
  33786. is required towards one end of the range, so this will logarithmically
  33787. spread the values across the length of the slider.
  33788. If the factor is < 1.0, the lower end of the range will fill more of the
  33789. slider's length; if the factor is > 1.0, the upper end of the range
  33790. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33791. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33792. method instead.
  33793. @see getSkewFactor, setSkewFactorFromMidPoint
  33794. */
  33795. void setSkewFactor (const double factor) throw();
  33796. /** Sets up a skew factor to alter the way values are distributed.
  33797. This allows you to specify the slider value that should appear in the
  33798. centre of the slider's visible range.
  33799. @see setSkewFactor, getSkewFactor
  33800. */
  33801. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33802. /** Returns the current skew factor.
  33803. See setSkewFactor for more info.
  33804. @see setSkewFactor, setSkewFactorFromMidPoint
  33805. */
  33806. double getSkewFactor() const throw() { return skewFactor; }
  33807. /** Used by setIncDecButtonsMode().
  33808. */
  33809. enum IncDecButtonMode
  33810. {
  33811. incDecButtonsNotDraggable,
  33812. incDecButtonsDraggable_AutoDirection,
  33813. incDecButtonsDraggable_Horizontal,
  33814. incDecButtonsDraggable_Vertical
  33815. };
  33816. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33817. can be dragged on the buttons to drag the values.
  33818. By default this is turned off. When enabled, clicking on the buttons still works
  33819. them as normal, but by holding down the mouse on a button and dragging it a little
  33820. distance, it flips into a mode where the value can be dragged. The drag direction can
  33821. either be set explicitly to be vertical or horizontal, or can be set to
  33822. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33823. are side-by-side or above each other.
  33824. */
  33825. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33826. /** The position of the slider's text-entry box.
  33827. @see setTextBoxStyle
  33828. */
  33829. enum TextEntryBoxPosition
  33830. {
  33831. NoTextBox, /**< Doesn't display a text box. */
  33832. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33833. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33834. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33835. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33836. };
  33837. /** Changes the location and properties of the text-entry box.
  33838. @param newPosition where it should go (or NoTextBox to not have one at all)
  33839. @param isReadOnly if true, it's a read-only display
  33840. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33841. room for the slider as well!
  33842. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33843. room for the slider as well!
  33844. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33845. */
  33846. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33847. const bool isReadOnly,
  33848. const int textEntryBoxWidth,
  33849. const int textEntryBoxHeight);
  33850. /** Returns the status of the text-box.
  33851. @see setTextBoxStyle
  33852. */
  33853. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33854. /** Returns the width used for the text-box.
  33855. @see setTextBoxStyle
  33856. */
  33857. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33858. /** Returns the height used for the text-box.
  33859. @see setTextBoxStyle
  33860. */
  33861. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33862. /** Makes the text-box editable.
  33863. By default this is true, and the user can enter values into the textbox,
  33864. but it can be turned off if that's not suitable.
  33865. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33866. */
  33867. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33868. /** Returns true if the text-box is read-only.
  33869. @see setTextBoxStyle
  33870. */
  33871. bool isTextBoxEditable() const throw() { return editableText; }
  33872. /** If the text-box is editable, this will give it the focus so that the user can
  33873. type directly into it.
  33874. This is basically the effect as the user clicking on it.
  33875. */
  33876. void showTextBox();
  33877. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33878. focus away from it.
  33879. @param discardCurrentEditorContents if true, the slider's value will be left
  33880. unchanged; if false, the current contents of the
  33881. text editor will be used to set the slider position
  33882. before it is hidden.
  33883. */
  33884. void hideTextBox (const bool discardCurrentEditorContents);
  33885. /** Changes the slider's current value.
  33886. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33887. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33888. want to handle it.
  33889. @param newValue the new value to set - this will be restricted by the
  33890. minimum and maximum range, and will be snapped to the
  33891. nearest interval if one has been set
  33892. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33893. any SliderListeners or the valueChanged() method
  33894. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33895. synchronously; if false, it will be asynchronous
  33896. */
  33897. void setValue (double newValue,
  33898. const bool sendUpdateMessage = true,
  33899. const bool sendMessageSynchronously = false);
  33900. /** Returns the slider's current value. */
  33901. double getValue() const throw();
  33902. /** Sets the limits that the slider's value can take.
  33903. @param newMinimum the lowest value allowed
  33904. @param newMaximum the highest value allowed
  33905. @param newInterval the steps in which the value is allowed to increase - if this
  33906. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33907. */
  33908. void setRange (const double newMinimum,
  33909. const double newMaximum,
  33910. const double newInterval = 0);
  33911. /** Returns the current maximum value.
  33912. @see setRange
  33913. */
  33914. double getMaximum() const throw() { return maximum; }
  33915. /** Returns the current minimum value.
  33916. @see setRange
  33917. */
  33918. double getMinimum() const throw() { return minimum; }
  33919. /** Returns the current step-size for values.
  33920. @see setRange
  33921. */
  33922. double getInterval() const throw() { return interval; }
  33923. /** For a slider with two or three thumbs, this returns the lower of its values.
  33924. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33925. A slider with three values also uses the normal getValue() and setValue() methods to
  33926. control the middle value.
  33927. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33928. */
  33929. double getMinValue() const throw();
  33930. /** For a slider with two or three thumbs, this sets the lower of its values.
  33931. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33932. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33933. want to handle it.
  33934. @param newValue the new value to set - this will be restricted by the
  33935. minimum and maximum range, and will be snapped to the nearest
  33936. interval if one has been set.
  33937. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33938. any SliderListeners or the valueChanged() method
  33939. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33940. synchronously; if false, it will be asynchronous
  33941. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  33942. max value (in a two-value slider) or the mid value (in a three-value
  33943. slider). If false, then if this value goes beyond those values,
  33944. it will push them along with it.
  33945. @see getMinValue, setMaxValue, setValue
  33946. */
  33947. void setMinValue (double newValue,
  33948. const bool sendUpdateMessage = true,
  33949. const bool sendMessageSynchronously = false,
  33950. const bool allowNudgingOfOtherValues = false);
  33951. /** For a slider with two or three thumbs, this returns the higher of its values.
  33952. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33953. A slider with three values also uses the normal getValue() and setValue() methods to
  33954. control the middle value.
  33955. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33956. */
  33957. double getMaxValue() const throw();
  33958. /** For a slider with two or three thumbs, this sets the lower of its values.
  33959. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33960. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33961. want to handle it.
  33962. @param newValue the new value to set - this will be restricted by the
  33963. minimum and maximum range, and will be snapped to the nearest
  33964. interval if one has been set.
  33965. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33966. any SliderListeners or the valueChanged() method
  33967. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33968. synchronously; if false, it will be asynchronous
  33969. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  33970. min value (in a two-value slider) or the mid value (in a three-value
  33971. slider). If false, then if this value goes beyond those values,
  33972. it will push them along with it.
  33973. @see getMaxValue, setMinValue, setValue
  33974. */
  33975. void setMaxValue (double newValue,
  33976. const bool sendUpdateMessage = true,
  33977. const bool sendMessageSynchronously = false,
  33978. const bool allowNudgingOfOtherValues = false);
  33979. /** Adds a listener to be called when this slider's value changes. */
  33980. void addListener (SliderListener* const listener) throw();
  33981. /** Removes a previously-registered listener. */
  33982. void removeListener (SliderListener* const listener) throw();
  33983. /** This lets you choose whether double-clicking moves the slider to a given position.
  33984. By default this is turned off, but it's handy if you want a double-click to act
  33985. as a quick way of resetting a slider. Just pass in the value you want it to
  33986. go to when double-clicked.
  33987. @see getDoubleClickReturnValue
  33988. */
  33989. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  33990. const double valueToSetOnDoubleClick) throw();
  33991. /** Returns the values last set by setDoubleClickReturnValue() method.
  33992. Sets isEnabled to true if double-click is enabled, and returns the value
  33993. that was set.
  33994. @see setDoubleClickReturnValue
  33995. */
  33996. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  33997. /** Tells the slider whether to keep sending change messages while the user
  33998. is dragging the slider.
  33999. If set to true, a change message will only be sent when the user has
  34000. dragged the slider and let go. If set to false (the default), then messages
  34001. will be continuously sent as they drag it while the mouse button is still
  34002. held down.
  34003. */
  34004. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  34005. /** This lets you change whether the slider thumb jumps to the mouse position
  34006. when you click.
  34007. By default, this is true. If it's false, then the slider moves with relative
  34008. motion when you drag it.
  34009. This only applies to linear bars, and won't affect two- or three- value
  34010. sliders.
  34011. */
  34012. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  34013. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34014. slider is being dragged.
  34015. This can be handy if your slider doesn't have a text-box, so that users can
  34016. see the value just when they're changing it.
  34017. If you pass a component as the parentComponentToUse parameter, the pop-up
  34018. bubble will be added as a child of that component when it's needed. If you
  34019. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34020. transparent window, so if you're using an OS that can't do transparent windows
  34021. you'll have to add it to a parent component instead).
  34022. */
  34023. void setPopupDisplayEnabled (const bool isEnabled,
  34024. Component* const parentComponentToUse) throw();
  34025. /** If this is set to true, then right-clicking on the slider will pop-up
  34026. a menu to let the user change the way it works.
  34027. By default this is turned off, but when turned on, the menu will include
  34028. things like velocity sensitivity, and for rotary sliders, whether they
  34029. use a linear or rotary mouse-drag to move them.
  34030. */
  34031. void setPopupMenuEnabled (const bool menuEnabled) throw();
  34032. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34033. By default it's enabled.
  34034. */
  34035. void setScrollWheelEnabled (const bool enabled) throw();
  34036. /** Returns a number to indicate which thumb is currently being dragged by the
  34037. mouse.
  34038. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34039. the maximum-value thumb, or -1 if none is currently down.
  34040. */
  34041. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  34042. /** Callback to indicate that the user is about to start dragging the slider.
  34043. @see SliderListener::sliderDragStarted
  34044. */
  34045. virtual void startedDragging();
  34046. /** Callback to indicate that the user has just stopped dragging the slider.
  34047. @see SliderListener::sliderDragEnded
  34048. */
  34049. virtual void stoppedDragging();
  34050. /** Callback to indicate that the user has just moved the slider.
  34051. @see SliderListener::sliderValueChanged
  34052. */
  34053. virtual void valueChanged();
  34054. /** Callback to indicate that the user has just moved the slider.
  34055. Note - the valueChanged() method has changed its format and now no longer has
  34056. any parameters. Update your code to use the new version.
  34057. This version has been left here with an int as its return value to cause
  34058. a syntax error if you've got existing code that uses the old version.
  34059. */
  34060. virtual int valueChanged (double) { jassertfalse; return 0; }
  34061. /** Subclasses can override this to convert a text string to a value.
  34062. When the user enters something into the text-entry box, this method is
  34063. called to convert it to a value.
  34064. The default routine just tries to convert it to a double.
  34065. @see getTextFromValue
  34066. */
  34067. virtual double getValueFromText (const String& text);
  34068. /** Turns the slider's current value into a text string.
  34069. Subclasses can override this to customise the formatting of the text-entry box.
  34070. The default implementation just turns the value into a string, using
  34071. a number of decimal places based on the range interval. If a suffix string
  34072. has been set using setTextValueSuffix(), this will be appended to the text.
  34073. @see getValueFromText
  34074. */
  34075. virtual const String getTextFromValue (double value);
  34076. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34077. a string.
  34078. This is used by the default implementation of getTextFromValue(), and is just
  34079. appended to the numeric value. For more advanced formatting, you can override
  34080. getTextFromValue() and do something else.
  34081. */
  34082. void setTextValueSuffix (const String& suffix);
  34083. /** Allows a user-defined mapping of distance along the slider to its value.
  34084. The default implementation for this performs the skewing operation that
  34085. can be set up in the setSkewFactor() method. Override it if you need
  34086. some kind of custom mapping instead, but make sure you also implement the
  34087. inverse function in valueToProportionOfLength().
  34088. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34089. @returns the slider value that is represented by this position
  34090. @see valueToProportionOfLength
  34091. */
  34092. virtual double proportionOfLengthToValue (double proportion);
  34093. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34094. The default implementation for this performs the skewing operation that
  34095. can be set up in the setSkewFactor() method. Override it if you need
  34096. some kind of custom mapping instead, but make sure you also implement the
  34097. inverse function in proportionOfLengthToValue().
  34098. @param value a valid slider value, between the range of values specified in
  34099. setRange()
  34100. @returns a value 0 to 1.0 indicating the distance along the slider that
  34101. represents this value
  34102. @see proportionOfLengthToValue
  34103. */
  34104. virtual double valueToProportionOfLength (double value);
  34105. /** Returns the X or Y coordinate of a value along the slider's length.
  34106. If the slider is horizontal, this will be the X coordinate of the given
  34107. value, relative to the left of the slider. If it's vertical, then this will
  34108. be the Y coordinate, relative to the top of the slider.
  34109. If the slider is rotary, this will throw an assertion and return 0. If the
  34110. value is out-of-range, it will be constrained to the length of the slider.
  34111. */
  34112. float getPositionOfValue (const double value);
  34113. /** This can be overridden to allow the slider to snap to user-definable values.
  34114. If overridden, it will be called when the user tries to move the slider to
  34115. a given position, and allows a subclass to sanity-check this value, possibly
  34116. returning a different value to use instead.
  34117. @param attemptedValue the value the user is trying to enter
  34118. @param userIsDragging true if the user is dragging with the mouse; false if
  34119. they are entering the value using the text box
  34120. @returns the value to use instead
  34121. */
  34122. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  34123. /** This can be called to force the text box to update its contents.
  34124. (Not normally needed, as this is done automatically).
  34125. */
  34126. void updateText();
  34127. /** True if the slider moves horizontally. */
  34128. bool isHorizontal() const throw();
  34129. /** True if the slider moves vertically. */
  34130. bool isVertical() const throw();
  34131. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34132. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34133. methods.
  34134. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34135. */
  34136. enum ColourIds
  34137. {
  34138. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34139. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34140. and feel class how this is used. */
  34141. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34142. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34143. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34144. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34145. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34146. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34147. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34148. };
  34149. juce_UseDebuggingNewOperator
  34150. protected:
  34151. /** @internal */
  34152. void labelTextChanged (Label*);
  34153. /** @internal */
  34154. void paint (Graphics& g);
  34155. /** @internal */
  34156. void resized();
  34157. /** @internal */
  34158. void mouseDown (const MouseEvent& e);
  34159. /** @internal */
  34160. void mouseUp (const MouseEvent& e);
  34161. /** @internal */
  34162. void mouseDrag (const MouseEvent& e);
  34163. /** @internal */
  34164. void mouseDoubleClick (const MouseEvent& e);
  34165. /** @internal */
  34166. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34167. /** @internal */
  34168. void modifierKeysChanged (const ModifierKeys& modifiers);
  34169. /** @internal */
  34170. void buttonClicked (Button* button);
  34171. /** @internal */
  34172. void lookAndFeelChanged();
  34173. /** @internal */
  34174. void enablementChanged();
  34175. /** @internal */
  34176. void focusOfChildComponentChanged (FocusChangeType cause);
  34177. /** @internal */
  34178. void handleAsyncUpdate();
  34179. /** @internal */
  34180. void colourChanged();
  34181. private:
  34182. SortedSet <void*> listeners;
  34183. double currentValue, valueMin, valueMax;
  34184. double minimum, maximum, interval, doubleClickReturnValue;
  34185. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34186. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34187. int velocityModeThreshold;
  34188. float rotaryStart, rotaryEnd;
  34189. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34190. int mouseDragStartX, mouseDragStartY;
  34191. int sliderRegionStart, sliderRegionSize;
  34192. int sliderBeingDragged;
  34193. int pixelsForFullDragExtent;
  34194. Rectangle sliderRect;
  34195. String textSuffix;
  34196. SliderStyle style;
  34197. TextEntryBoxPosition textBoxPos;
  34198. int textBoxWidth, textBoxHeight;
  34199. IncDecButtonMode incDecButtonMode;
  34200. bool editableText : 1, doubleClickToValue : 1;
  34201. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34202. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34203. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34204. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34205. Font font;
  34206. Label* valueBox;
  34207. Button* incButton;
  34208. Button* decButton;
  34209. Component* popupDisplay;
  34210. Component* parentForPopupDisplay;
  34211. float getLinearSliderPos (const double value);
  34212. void restoreMouseIfHidden();
  34213. void sendDragStart();
  34214. void sendDragEnd();
  34215. double constrainedValue (double value) const throw();
  34216. void triggerChangeMessage (const bool synchronous);
  34217. bool incDecDragDirectionIsHorizontal() const throw();
  34218. Slider (const Slider&);
  34219. const Slider& operator= (const Slider&);
  34220. };
  34221. #endif // __JUCE_SLIDER_JUCEHEADER__
  34222. /********* End of inlined file: juce_Slider.h *********/
  34223. #endif
  34224. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34225. #endif
  34226. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34227. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  34228. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34229. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34230. class TableHeaderComponent;
  34231. /**
  34232. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34233. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34234. and TableHeaderComponent::removeListener().
  34235. @see TableHeaderComponent
  34236. */
  34237. class JUCE_API TableHeaderListener
  34238. {
  34239. public:
  34240. TableHeaderListener() {}
  34241. /** Destructor. */
  34242. virtual ~TableHeaderListener() {}
  34243. /** This is called when some of the table's columns are added, removed, hidden,
  34244. or rearranged.
  34245. */
  34246. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34247. /** This is called when one or more of the table's columns are resized.
  34248. */
  34249. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34250. /** This is called when the column by which the table should be sorted is changed.
  34251. */
  34252. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34253. /** This is called when the user begins or ends dragging one of the columns around.
  34254. When the user starts dragging a column, this is called with the ID of that
  34255. column. When they finish dragging, it is called again with 0 as the ID.
  34256. */
  34257. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34258. int columnIdNowBeingDragged);
  34259. };
  34260. /**
  34261. A component that displays a strip of column headings for a table, and allows these
  34262. to be resized, dragged around, etc.
  34263. This is just the component that goes at the top of a table. You can use it
  34264. directly for custom components, or to create a simple table, use the
  34265. TableListBox class.
  34266. To use one of these, create it and use addColumn() to add all the columns that you need.
  34267. Each column must be given a unique ID number that's used to refer to it.
  34268. @see TableListBox, TableHeaderListener
  34269. */
  34270. class JUCE_API TableHeaderComponent : public Component,
  34271. private AsyncUpdater
  34272. {
  34273. public:
  34274. /** Creates an empty table header.
  34275. */
  34276. TableHeaderComponent();
  34277. /** Destructor. */
  34278. ~TableHeaderComponent();
  34279. /** A combination of these flags are passed into the addColumn() method to specify
  34280. the properties of a column.
  34281. */
  34282. enum ColumnPropertyFlags
  34283. {
  34284. 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. */
  34285. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34286. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34287. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34288. 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. */
  34289. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34290. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34291. /** This set of default flags is used as the default parameter value in addColumn(). */
  34292. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34293. /** A quick way of combining flags for a column that's not resizable. */
  34294. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34295. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34296. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34297. /** A quick way of combining flags for a column that's not sortable. */
  34298. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34299. };
  34300. /** Adds a column to the table.
  34301. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34302. registered listeners.
  34303. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34304. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34305. a unique ID. This is used to identify the column later on, after the user may have
  34306. changed the order that they appear in
  34307. @param width the initial width of the column, in pixels
  34308. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34309. if the 'resizable' flag is specified for this column
  34310. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34311. if the 'resizable' flag is specified for this column
  34312. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34313. properties of this column
  34314. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34315. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34316. all columns, not just the index amongst those that are currently visible
  34317. */
  34318. void addColumn (const String& columnName,
  34319. const int columnId,
  34320. const int width,
  34321. const int minimumWidth = 30,
  34322. const int maximumWidth = -1,
  34323. const int propertyFlags = defaultFlags,
  34324. const int insertIndex = -1);
  34325. /** Removes a column with the given ID.
  34326. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34327. registered listeners.
  34328. */
  34329. void removeColumn (const int columnIdToRemove);
  34330. /** Deletes all columns from the table.
  34331. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34332. registered listeners.
  34333. */
  34334. void removeAllColumns();
  34335. /** Returns the number of columns in the table.
  34336. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34337. return the total number of columns, including hidden ones.
  34338. @see isColumnVisible
  34339. */
  34340. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  34341. /** Returns the name for a column.
  34342. @see setColumnName
  34343. */
  34344. const String getColumnName (const int columnId) const throw();
  34345. /** Changes the name of a column. */
  34346. void setColumnName (const int columnId, const String& newName);
  34347. /** Moves a column to a different index in the table.
  34348. @param columnId the column to move
  34349. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34350. */
  34351. void moveColumn (const int columnId, int newVisibleIndex);
  34352. /** Changes the width of a column.
  34353. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34354. */
  34355. void setColumnWidth (const int columnId, const int newWidth);
  34356. /** Shows or hides a column.
  34357. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34358. @see isColumnVisible
  34359. */
  34360. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  34361. /** Returns true if this column is currently visible.
  34362. @see setColumnVisible
  34363. */
  34364. bool isColumnVisible (const int columnId) const;
  34365. /** Changes the column which is the sort column.
  34366. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34367. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34368. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34369. @see getSortColumnId, isSortedForwards, reSortTable
  34370. */
  34371. void setSortColumnId (const int columnId, const bool sortForwards);
  34372. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34373. @see setSortColumnId, isSortedForwards
  34374. */
  34375. int getSortColumnId() const throw();
  34376. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34377. @see setSortColumnId
  34378. */
  34379. bool isSortedForwards() const throw();
  34380. /** Triggers a re-sort of the table according to the current sort-column.
  34381. If you modifiy the table's contents, you can call this to signal that the table needs
  34382. to be re-sorted.
  34383. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34384. tableSortOrderChanged() method of any listeners).
  34385. */
  34386. void reSortTable();
  34387. /** Returns the total width of all the visible columns in the table.
  34388. */
  34389. int getTotalWidth() const throw();
  34390. /** Returns the index of a given column.
  34391. If there's no such column ID, this will return -1.
  34392. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34393. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34394. */
  34395. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  34396. /** Returns the ID of the column at a given index.
  34397. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34398. otherwise it'll count it amongst all the columns, including any hidden ones.
  34399. If the index is out-of-range, it'll return 0.
  34400. */
  34401. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  34402. /** Returns the rectangle containing of one of the columns.
  34403. The index is an index from 0 to the number of columns that are currently visible (hidden
  34404. ones are not counted). It returns a rectangle showing the position of the column relative
  34405. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34406. */
  34407. const Rectangle getColumnPosition (const int index) const throw();
  34408. /** Finds the column ID at a given x-position in the component.
  34409. If there is a column at this point this returns its ID, or if not, it will return 0.
  34410. */
  34411. int getColumnIdAtX (const int xToFind) const throw();
  34412. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34413. entire width of the component.
  34414. By default this is disabled. Turning it on also means that when resizing a column, those
  34415. on the right will be squashed to fit.
  34416. */
  34417. void setStretchToFitActive (const bool shouldStretchToFit);
  34418. /** Returns true if stretch-to-fit has been enabled.
  34419. @see setStretchToFitActive
  34420. */
  34421. bool isStretchToFitActive() const throw();
  34422. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34423. specified width, keeping their relative proportions the same.
  34424. If the minimum widths of the columns are too wide to fit into this space, it may
  34425. actually end up wider.
  34426. */
  34427. void resizeAllColumnsToFit (int targetTotalWidth);
  34428. /** Enables or disables the pop-up menu.
  34429. The default menu allows the user to show or hide columns. You can add custom
  34430. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34431. By default the menu is enabled.
  34432. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34433. */
  34434. void setPopupMenuActive (const bool hasMenu);
  34435. /** Returns true if the pop-up menu is enabled.
  34436. @see setPopupMenuActive
  34437. */
  34438. bool isPopupMenuActive() const throw();
  34439. /** Returns a string that encapsulates the table's current layout.
  34440. This can be restored later using restoreFromString(). It saves the order of
  34441. the columns, the currently-sorted column, and the widths.
  34442. @see restoreFromString
  34443. */
  34444. const String toString() const;
  34445. /** Restores the state of the table, based on a string previously created with
  34446. toString().
  34447. @see toString
  34448. */
  34449. void restoreFromString (const String& storedVersion);
  34450. /** Adds a listener to be informed about things that happen to the header. */
  34451. void addListener (TableHeaderListener* const newListener) throw();
  34452. /** Removes a previously-registered listener. */
  34453. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34454. /** This can be overridden to handle a mouse-click on one of the column headers.
  34455. The default implementation will use this click to call getSortColumnId() and
  34456. change the sort order.
  34457. */
  34458. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34459. /** This can be overridden to add custom items to the pop-up menu.
  34460. If you override this, you should call the superclass's method to add its
  34461. column show/hide items, if you want them on the menu as well.
  34462. Then to handle the result, override reactToMenuItem().
  34463. @see reactToMenuItem
  34464. */
  34465. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  34466. /** Override this to handle any custom items that you have added to the
  34467. pop-up menu with an addMenuItems() override.
  34468. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34469. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34470. handle the items that it had added.
  34471. @see addMenuItems
  34472. */
  34473. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  34474. /** @internal */
  34475. void paint (Graphics& g);
  34476. /** @internal */
  34477. void resized();
  34478. /** @internal */
  34479. void mouseMove (const MouseEvent&);
  34480. /** @internal */
  34481. void mouseEnter (const MouseEvent&);
  34482. /** @internal */
  34483. void mouseExit (const MouseEvent&);
  34484. /** @internal */
  34485. void mouseDown (const MouseEvent&);
  34486. /** @internal */
  34487. void mouseDrag (const MouseEvent&);
  34488. /** @internal */
  34489. void mouseUp (const MouseEvent&);
  34490. /** @internal */
  34491. const MouseCursor getMouseCursor();
  34492. /** Can be overridden for more control over the pop-up menu behaviour. */
  34493. virtual void showColumnChooserMenu (const int columnIdClicked);
  34494. juce_UseDebuggingNewOperator
  34495. private:
  34496. struct ColumnInfo
  34497. {
  34498. String name;
  34499. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34500. double lastDeliberateWidth;
  34501. bool isVisible() const throw();
  34502. };
  34503. OwnedArray <ColumnInfo> columns;
  34504. Array <TableHeaderListener*> listeners;
  34505. Component* dragOverlayComp;
  34506. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34507. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34508. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34509. ColumnInfo* getInfoForId (const int columnId) const throw();
  34510. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  34511. void sendColumnsChanged();
  34512. void handleAsyncUpdate();
  34513. void beginDrag (const MouseEvent&);
  34514. void endDrag (const int finalIndex);
  34515. int getResizeDraggerAt (const int mouseX) const throw();
  34516. void updateColumnUnderMouse (int x, int y);
  34517. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34518. TableHeaderComponent (const TableHeaderComponent&);
  34519. const TableHeaderComponent operator= (const TableHeaderComponent&);
  34520. };
  34521. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34522. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  34523. #endif
  34524. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34525. /********* Start of inlined file: juce_TableListBox.h *********/
  34526. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34527. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34528. /**
  34529. One of these is used by a TableListBox as the data model for the table's contents.
  34530. The virtual methods that you override in this class take care of drawing the
  34531. table cells, and reacting to events.
  34532. @see TableListBox
  34533. */
  34534. class JUCE_API TableListBoxModel
  34535. {
  34536. public:
  34537. TableListBoxModel() {}
  34538. /** Destructor. */
  34539. virtual ~TableListBoxModel() {}
  34540. /** This must return the number of rows currently in the table.
  34541. If the number of rows changes, you must call TableListBox::updateContent() to
  34542. cause it to refresh the list.
  34543. */
  34544. virtual int getNumRows() = 0;
  34545. /** This must draw the background behind one of the rows in the table.
  34546. The graphics context has its origin at the row's top-left, and your method
  34547. should fill the area specified by the width and height parameters.
  34548. */
  34549. virtual void paintRowBackground (Graphics& g,
  34550. int rowNumber,
  34551. int width, int height,
  34552. bool rowIsSelected) = 0;
  34553. /** This must draw one of the cells.
  34554. The graphics context's origin will already be set to the top-left of the cell,
  34555. whose size is specified by (width, height).
  34556. */
  34557. virtual void paintCell (Graphics& g,
  34558. int rowNumber,
  34559. int columnId,
  34560. int width, int height,
  34561. bool rowIsSelected) = 0;
  34562. /** This is used to create or update a custom component to go in a cell.
  34563. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34564. and handle mouse clicks with cellClicked().
  34565. This method will be called whenever a custom component might need to be updated - e.g.
  34566. when the table is changed, or TableListBox::updateContent() is called.
  34567. If you don't need a custom component for the specified cell, then return 0.
  34568. If you do want a custom component, and the existingComponentToUpdate is null, then
  34569. this method must create a new component suitable for the cell, and return it.
  34570. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34571. by this method. In this case, the method must either update it to make sure it's correctly representing
  34572. the given cell (which may be different from the one that the component was created for), or it can
  34573. delete this component and return a new one.
  34574. */
  34575. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34576. Component* existingComponentToUpdate);
  34577. /** This callback is made when the user clicks on one of the cells in the table.
  34578. The mouse event's coordinates will be relative to the entire table row.
  34579. @see cellDoubleClicked, backgroundClicked
  34580. */
  34581. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34582. /** This callback is made when the user clicks on one of the cells in the table.
  34583. The mouse event's coordinates will be relative to the entire table row.
  34584. @see cellClicked, backgroundClicked
  34585. */
  34586. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34587. /** This can be overridden to react to the user double-clicking on a part of the list where
  34588. there are no rows.
  34589. @see cellClicked
  34590. */
  34591. virtual void backgroundClicked();
  34592. /** This callback is made when the table's sort order is changed.
  34593. This could be because the user has clicked a column header, or because the
  34594. TableHeaderComponent::setSortColumnId() method was called.
  34595. If you implement this, your method should re-sort the table using the given
  34596. column as the key.
  34597. */
  34598. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34599. /** Returns the best width for one of the columns.
  34600. If you implement this method, you should measure the width of all the items
  34601. in this column, and return the best size.
  34602. Returning 0 means that the column shouldn't be changed.
  34603. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34604. */
  34605. virtual int getColumnAutoSizeWidth (int columnId);
  34606. /** Override this to be informed when rows are selected or deselected.
  34607. @see ListBox::selectedRowsChanged()
  34608. */
  34609. virtual void selectedRowsChanged (int lastRowSelected);
  34610. /** Override this to be informed when the delete key is pressed.
  34611. @see ListBox::deleteKeyPressed()
  34612. */
  34613. virtual void deleteKeyPressed (int lastRowSelected);
  34614. /** Override this to be informed when the return key is pressed.
  34615. @see ListBox::returnKeyPressed()
  34616. */
  34617. virtual void returnKeyPressed (int lastRowSelected);
  34618. /** Override this to be informed when the list is scrolled.
  34619. This might be caused by the user moving the scrollbar, or by programmatic changes
  34620. to the list position.
  34621. */
  34622. virtual void listWasScrolled();
  34623. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34624. If this returns a non-empty name then when the user drags a row, the table will try to
  34625. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34626. drag-and-drop operation, using this string as the source description, and the listbox
  34627. itself as the source component.
  34628. @see DragAndDropContainer::startDragging
  34629. */
  34630. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34631. };
  34632. /**
  34633. A table of cells, using a TableHeaderComponent as its header.
  34634. This component makes it easy to create a table by providing a TableListBoxModel as
  34635. the data source.
  34636. @see TableListBoxModel, TableHeaderComponent
  34637. */
  34638. class JUCE_API TableListBox : public ListBox,
  34639. private ListBoxModel,
  34640. private TableHeaderListener
  34641. {
  34642. public:
  34643. /** Creates a TableListBox.
  34644. The model pointer passed-in can be null, in which case you can set it later
  34645. with setModel().
  34646. */
  34647. TableListBox (const String& componentName,
  34648. TableListBoxModel* const model);
  34649. /** Destructor. */
  34650. ~TableListBox();
  34651. /** Changes the TableListBoxModel that is being used for this table.
  34652. */
  34653. void setModel (TableListBoxModel* const newModel);
  34654. /** Returns the model currently in use. */
  34655. TableListBoxModel* getModel() const throw() { return model; }
  34656. /** Returns the header component being used in this table. */
  34657. TableHeaderComponent* getHeader() const throw() { return header; }
  34658. /** Changes the height of the table header component.
  34659. @see getHeaderHeight
  34660. */
  34661. void setHeaderHeight (const int newHeight);
  34662. /** Returns the height of the table header.
  34663. @see setHeaderHeight
  34664. */
  34665. int getHeaderHeight() const throw();
  34666. /** Resizes a column to fit its contents.
  34667. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34668. and applies that to the column.
  34669. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34670. */
  34671. void autoSizeColumn (const int columnId);
  34672. /** Calls autoSizeColumn() for all columns in the table. */
  34673. void autoSizeAllColumns();
  34674. /** Enables or disables the auto size options on the popup menu.
  34675. By default, these are enabled.
  34676. */
  34677. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34678. /** True if the auto-size options should be shown on the menu.
  34679. @see setAutoSizeMenuOptionsShown
  34680. */
  34681. bool isAutoSizeMenuOptionShown() const throw();
  34682. /** Returns the position of one of the cells in the table.
  34683. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34684. the table component's top-left. The row number isn't checked to see if it's
  34685. in-range, but the column ID must exist or this will return an empty rectangle.
  34686. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34687. top-left of the table's top-left cell.
  34688. */
  34689. const Rectangle getCellPosition (const int columnId,
  34690. const int rowNumber,
  34691. const bool relativeToComponentTopLeft) const;
  34692. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34693. @see ListBox::scrollToEnsureRowIsOnscreen
  34694. */
  34695. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34696. /** @internal */
  34697. int getNumRows();
  34698. /** @internal */
  34699. void paintListBoxItem (int, Graphics&, int, int, bool);
  34700. /** @internal */
  34701. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34702. /** @internal */
  34703. void selectedRowsChanged (int lastRowSelected);
  34704. /** @internal */
  34705. void deleteKeyPressed (int currentSelectedRow);
  34706. /** @internal */
  34707. void returnKeyPressed (int currentSelectedRow);
  34708. /** @internal */
  34709. void backgroundClicked();
  34710. /** @internal */
  34711. void listWasScrolled();
  34712. /** @internal */
  34713. void tableColumnsChanged (TableHeaderComponent*);
  34714. /** @internal */
  34715. void tableColumnsResized (TableHeaderComponent*);
  34716. /** @internal */
  34717. void tableSortOrderChanged (TableHeaderComponent*);
  34718. /** @internal */
  34719. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34720. /** @internal */
  34721. void resized();
  34722. juce_UseDebuggingNewOperator
  34723. private:
  34724. TableHeaderComponent* header;
  34725. TableListBoxModel* model;
  34726. int columnIdNowBeingDragged;
  34727. bool autoSizeOptionsShown;
  34728. void updateColumnComponents() const;
  34729. TableListBox (const TableListBox&);
  34730. const TableListBox& operator= (const TableListBox&);
  34731. };
  34732. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34733. /********* End of inlined file: juce_TableListBox.h *********/
  34734. #endif
  34735. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34736. #endif
  34737. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34738. #endif
  34739. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34740. #endif
  34741. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34742. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  34743. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34744. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34745. /**
  34746. A factory object which can create ToolbarItemComponent objects.
  34747. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34748. that it can create.
  34749. Each type of item is identified by a unique ID, and multiple instances of an
  34750. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34751. bars).
  34752. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34753. */
  34754. class JUCE_API ToolbarItemFactory
  34755. {
  34756. public:
  34757. ToolbarItemFactory();
  34758. /** Destructor. */
  34759. virtual ~ToolbarItemFactory();
  34760. /** A set of reserved item ID values, used for the built-in item types.
  34761. */
  34762. enum SpecialItemIds
  34763. {
  34764. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34765. can be placed between sets of items to break them into groups. */
  34766. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34767. items.*/
  34768. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34769. either side of it, filling any available space. */
  34770. };
  34771. /** Must return a list of the IDs for all the item types that this factory can create.
  34772. The ids should be added to the array that is passed-in.
  34773. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34774. and the predefined IDs in the SpecialItemIds enum.
  34775. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34776. to this list if you want your toolbar to be able to contain those items.
  34777. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34778. of available items, and their order on the palette will reflect the order in which
  34779. they appear on this list.
  34780. @see ToolbarItemPalette
  34781. */
  34782. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34783. /** Must return the set of items that should be added to a toolbar as its default set.
  34784. This method is used by Toolbar::addDefaultItems() to determine which items to
  34785. create.
  34786. The items that your method adds to the array that is passed-in will be added to the
  34787. toolbar in the same order. Items can appear in the list more than once.
  34788. */
  34789. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34790. /** Must create an instance of one of the items that the factory lists in its
  34791. getAllToolbarItemIds() method.
  34792. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34793. method, except for the built-in item types from the SpecialItemIds enum, which
  34794. are created internally by the toolbar code.
  34795. Try not to keep a pointer to the object that is returned, as it will be deleted
  34796. automatically by the toolbar, and remember that multiple instances of the same
  34797. item type are likely to exist at the same time.
  34798. */
  34799. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  34800. };
  34801. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34802. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  34803. #endif
  34804. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34805. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  34806. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34807. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34808. /**
  34809. A component containing a list of toolbar items, which the user can drag onto
  34810. a toolbar to add them.
  34811. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34812. which automatically shows one of these in a dialog box with lots of extra controls.
  34813. @see Toolbar
  34814. */
  34815. class JUCE_API ToolbarItemPalette : public Component,
  34816. public DragAndDropContainer
  34817. {
  34818. public:
  34819. /** Creates a palette of items for a given factory, with the aim of adding them
  34820. to the specified toolbar.
  34821. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34822. set of items that are shown in this palette.
  34823. The toolbar and factory must not be deleted while this object exists.
  34824. */
  34825. ToolbarItemPalette (ToolbarItemFactory& factory,
  34826. Toolbar* const toolbar);
  34827. /** Destructor. */
  34828. ~ToolbarItemPalette();
  34829. /** @internal */
  34830. void resized();
  34831. juce_UseDebuggingNewOperator
  34832. private:
  34833. ToolbarItemFactory& factory;
  34834. Toolbar* toolbar;
  34835. Viewport* viewport;
  34836. friend class Toolbar;
  34837. void replaceComponent (ToolbarItemComponent* const comp);
  34838. ToolbarItemPalette (const ToolbarItemPalette&);
  34839. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34840. };
  34841. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34842. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  34843. #endif
  34844. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34845. #endif
  34846. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34847. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34848. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34849. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34850. /**
  34851. A PropertyComponent that contains an on/off toggle button.
  34852. This type of property component can be used if you have a boolean value to
  34853. toggle on/off.
  34854. @see PropertyComponent
  34855. */
  34856. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  34857. private ButtonListener
  34858. {
  34859. public:
  34860. /** Creates a button component.
  34861. @param propertyName the property name to be passed to the PropertyComponent
  34862. @param buttonTextWhenTrue the text shown in the button when the value is true
  34863. @param buttonTextWhenFalse the text shown in the button when the value is false
  34864. */
  34865. BooleanPropertyComponent (const String& propertyName,
  34866. const String& buttonTextWhenTrue,
  34867. const String& buttonTextWhenFalse);
  34868. /** Destructor. */
  34869. ~BooleanPropertyComponent();
  34870. /** Called to change the state of the boolean value. */
  34871. virtual void setState (const bool newState) = 0;
  34872. /** Must return the current value of the property. */
  34873. virtual bool getState() const = 0;
  34874. /** @internal */
  34875. void paint (Graphics& g);
  34876. /** @internal */
  34877. void refresh();
  34878. /** @internal */
  34879. void buttonClicked (Button*);
  34880. juce_UseDebuggingNewOperator
  34881. private:
  34882. ToggleButton* button;
  34883. String onText, offText;
  34884. };
  34885. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34886. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  34887. #endif
  34888. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34889. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  34890. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34891. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34892. /**
  34893. A PropertyComponent that contains a button.
  34894. This type of property component can be used if you need a button to trigger some
  34895. kind of action.
  34896. @see PropertyComponent
  34897. */
  34898. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  34899. private ButtonListener
  34900. {
  34901. public:
  34902. /** Creates a button component.
  34903. @param propertyName the property name to be passed to the PropertyComponent
  34904. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  34905. */
  34906. ButtonPropertyComponent (const String& propertyName,
  34907. const bool triggerOnMouseDown);
  34908. /** Destructor. */
  34909. ~ButtonPropertyComponent();
  34910. /** Called when the user clicks the button.
  34911. */
  34912. virtual void buttonClicked() = 0;
  34913. /** Returns the string that should be displayed in the button.
  34914. If you need to change this string, call refresh() to update the component.
  34915. */
  34916. virtual const String getButtonText() const = 0;
  34917. /** @internal */
  34918. void refresh();
  34919. /** @internal */
  34920. void buttonClicked (Button*);
  34921. juce_UseDebuggingNewOperator
  34922. private:
  34923. TextButton* button;
  34924. };
  34925. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34926. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  34927. #endif
  34928. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34929. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  34930. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34931. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34932. /**
  34933. A PropertyComponent that shows its value as a combo box.
  34934. This type of property component contains a list of options and has a
  34935. combo box to choose one.
  34936. Your subclass's constructor must add some strings to the choices StringArray
  34937. and these are shown in the list.
  34938. The getIndex() method will be called to find out which option is the currently
  34939. selected one. If you call refresh() it will call getIndex() to check whether
  34940. the value has changed, and will update the combo box if needed.
  34941. If the user selects a different item from the list, setIndex() will be
  34942. called to let your class process this.
  34943. @see PropertyComponent, PropertyPanel
  34944. */
  34945. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  34946. private ComboBoxListener
  34947. {
  34948. public:
  34949. /** Creates the component.
  34950. Your subclass's constructor must add a list of options to the choices
  34951. member variable.
  34952. */
  34953. ChoicePropertyComponent (const String& propertyName);
  34954. /** Destructor. */
  34955. ~ChoicePropertyComponent();
  34956. /** Called when the user selects an item from the combo box.
  34957. Your subclass must use this callback to update the value that this component
  34958. represents. The index is the index of the chosen item in the choices
  34959. StringArray.
  34960. */
  34961. virtual void setIndex (const int newIndex) = 0;
  34962. /** Returns the index of the item that should currently be shown.
  34963. This is the index of the item in the choices StringArray that will be
  34964. shown.
  34965. */
  34966. virtual int getIndex() const = 0;
  34967. /** Returns the list of options. */
  34968. const StringArray& getChoices() const throw();
  34969. /** @internal */
  34970. void refresh();
  34971. /** @internal */
  34972. void comboBoxChanged (ComboBox*);
  34973. juce_UseDebuggingNewOperator
  34974. protected:
  34975. /** The list of options that will be shown in the combo box.
  34976. Your subclass must populate this array in its constructor. If any empty
  34977. strings are added, these will be replaced with horizontal separators (see
  34978. ComboBox::addSeparator() for more info).
  34979. */
  34980. StringArray choices;
  34981. private:
  34982. ComboBox* comboBox;
  34983. };
  34984. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34985. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  34986. #endif
  34987. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  34988. #endif
  34989. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  34990. #endif
  34991. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34992. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34993. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34994. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34995. /**
  34996. A PropertyComponent that shows its value as a slider.
  34997. @see PropertyComponent, Slider
  34998. */
  34999. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  35000. private SliderListener
  35001. {
  35002. public:
  35003. /** Creates the property component.
  35004. The ranges, interval and skew factor are passed to the Slider component.
  35005. If you need to customise the slider in other ways, your constructor can
  35006. access the slider member variable and change it directly.
  35007. */
  35008. SliderPropertyComponent (const String& propertyName,
  35009. const double rangeMin,
  35010. const double rangeMax,
  35011. const double interval,
  35012. const double skewFactor = 1.0);
  35013. /** Destructor. */
  35014. ~SliderPropertyComponent();
  35015. /** Called when the user moves the slider to change its value.
  35016. Your subclass must use this method to update whatever item this property
  35017. represents.
  35018. */
  35019. virtual void setValue (const double newValue) = 0;
  35020. /** Returns the value that the slider should show. */
  35021. virtual const double getValue() const = 0;
  35022. /** @internal */
  35023. void refresh();
  35024. /** @internal */
  35025. void changeListenerCallback (void*);
  35026. /** @internal */
  35027. void sliderValueChanged (Slider*);
  35028. juce_UseDebuggingNewOperator
  35029. protected:
  35030. /** The slider component being used in this component.
  35031. Your subclass has access to this in case it needs to customise it in some way.
  35032. */
  35033. Slider* slider;
  35034. };
  35035. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35036. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  35037. #endif
  35038. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35039. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  35040. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35041. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35042. /**
  35043. A PropertyComponent that shows its value as editable text.
  35044. @see PropertyComponent
  35045. */
  35046. class JUCE_API TextPropertyComponent : public PropertyComponent
  35047. {
  35048. public:
  35049. /** Creates a text property component.
  35050. The maxNumChars is used to set the length of string allowable, and isMultiLine
  35051. sets whether the text editor allows carriage returns.
  35052. @see TextEditor
  35053. */
  35054. TextPropertyComponent (const String& propertyName,
  35055. const int maxNumChars,
  35056. const bool isMultiLine);
  35057. /** Destructor. */
  35058. ~TextPropertyComponent();
  35059. /** Called when the user edits the text.
  35060. Your subclass must use this callback to change the value of whatever item
  35061. this property component represents.
  35062. */
  35063. virtual void setText (const String& newText) = 0;
  35064. /** Returns the text that should be shown in the text editor.
  35065. */
  35066. virtual const String getText() const = 0;
  35067. /** @internal */
  35068. void refresh();
  35069. /** @internal */
  35070. void textWasEdited();
  35071. juce_UseDebuggingNewOperator
  35072. private:
  35073. Label* textEditor;
  35074. };
  35075. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35076. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  35077. #endif
  35078. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  35079. #endif
  35080. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  35081. #endif
  35082. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35083. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  35084. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35085. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35086. /** An object that watches for any movement of a component or any of its parent components.
  35087. This makes it easy to check when a component is moved relative to its top-level
  35088. peer window. The normal Component::moved() method is only called when a component
  35089. moves relative to its immediate parent, and sometimes you want to know if any of
  35090. components higher up the tree have moved (which of course will affect the overall
  35091. position of all their sub-components).
  35092. It also includes a callback that lets you know when the top-level peer is changed.
  35093. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  35094. because they need to keep their custom windows in the right place and respond to
  35095. changes in the peer.
  35096. */
  35097. class JUCE_API ComponentMovementWatcher : public ComponentListener
  35098. {
  35099. public:
  35100. /** Creates a ComponentMovementWatcher to watch a given target component. */
  35101. ComponentMovementWatcher (Component* const component);
  35102. /** Destructor. */
  35103. ~ComponentMovementWatcher();
  35104. /** This callback happens when the component that is being watched is moved
  35105. relative to its top-level peer window, or when it is resized.
  35106. */
  35107. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  35108. /** This callback happens when the component's top-level peer is changed.
  35109. */
  35110. virtual void componentPeerChanged() = 0;
  35111. juce_UseDebuggingNewOperator
  35112. /** @internal */
  35113. void componentParentHierarchyChanged (Component& component);
  35114. /** @internal */
  35115. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35116. private:
  35117. Component* const component;
  35118. ComponentPeer* lastPeer;
  35119. VoidArray registeredParentComps;
  35120. bool reentrant;
  35121. int lastX, lastY, lastWidth, lastHeight;
  35122. #ifdef JUCE_DEBUG
  35123. ComponentDeletionWatcher* deletionWatcher;
  35124. #endif
  35125. void unregister() throw();
  35126. void registerWithParentComps() throw();
  35127. ComponentMovementWatcher (const ComponentMovementWatcher&);
  35128. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  35129. };
  35130. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35131. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  35132. #endif
  35133. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35134. /********* Start of inlined file: juce_GroupComponent.h *********/
  35135. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35136. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35137. /**
  35138. A component that draws an outline around itself and has an optional title at
  35139. the top, for drawing an outline around a group of controls.
  35140. */
  35141. class JUCE_API GroupComponent : public Component
  35142. {
  35143. public:
  35144. /** Creates a GroupComponent.
  35145. @param componentName the name to give the component
  35146. @param labelText the text to show at the top of the outline
  35147. */
  35148. GroupComponent (const String& componentName,
  35149. const String& labelText);
  35150. /** Destructor. */
  35151. ~GroupComponent();
  35152. /** Changes the text that's shown at the top of the component. */
  35153. void setText (const String& newText) throw();
  35154. /** Returns the currently displayed text label. */
  35155. const String getText() const throw();
  35156. /** Sets the positioning of the text label.
  35157. (The default is Justification::left)
  35158. @see getTextLabelPosition
  35159. */
  35160. void setTextLabelPosition (const Justification& justification);
  35161. /** Returns the current text label position.
  35162. @see setTextLabelPosition
  35163. */
  35164. const Justification getTextLabelPosition() const throw() { return justification; }
  35165. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35166. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35167. methods.
  35168. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35169. */
  35170. enum ColourIds
  35171. {
  35172. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  35173. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  35174. };
  35175. /** @internal */
  35176. void paint (Graphics& g);
  35177. /** @internal */
  35178. void enablementChanged();
  35179. /** @internal */
  35180. void colourChanged();
  35181. private:
  35182. String text;
  35183. Justification justification;
  35184. GroupComponent (const GroupComponent&);
  35185. const GroupComponent& operator= (const GroupComponent&);
  35186. };
  35187. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35188. /********* End of inlined file: juce_GroupComponent.h *********/
  35189. #endif
  35190. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35191. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  35192. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35193. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35194. /********* Start of inlined file: juce_TabbedComponent.h *********/
  35195. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35196. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35197. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  35198. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35199. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35200. class TabbedButtonBar;
  35201. /** In a TabbedButtonBar, this component is used for each of the buttons.
  35202. If you want to create a TabbedButtonBar with custom tab components, derive
  35203. your component from this class, and override the TabbedButtonBar::createTabButton()
  35204. method to create it instead of the default one.
  35205. @see TabbedButtonBar
  35206. */
  35207. class JUCE_API TabBarButton : public Button
  35208. {
  35209. public:
  35210. /** Creates the tab button. */
  35211. TabBarButton (const String& name,
  35212. TabbedButtonBar* const ownerBar,
  35213. const int tabIndex);
  35214. /** Destructor. */
  35215. ~TabBarButton();
  35216. /** Chooses the best length for the tab, given the specified depth.
  35217. If the tab is horizontal, this should return its width, and the depth
  35218. specifies its height. If it's vertical, it should return the height, and
  35219. the depth is actually its width.
  35220. */
  35221. virtual int getBestTabLength (const int depth);
  35222. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35223. void clicked (const ModifierKeys& mods);
  35224. bool hitTest (int x, int y);
  35225. juce_UseDebuggingNewOperator
  35226. protected:
  35227. friend class TabbedButtonBar;
  35228. TabbedButtonBar* const owner;
  35229. int tabIndex, overlapPixels;
  35230. DropShadowEffect shadow;
  35231. /** Returns an area of the component that's safe to draw in.
  35232. This deals with the orientation of the tabs, which affects which side is
  35233. touching the tabbed box's content component.
  35234. */
  35235. void getActiveArea (int& x, int& y, int& w, int& h);
  35236. private:
  35237. TabBarButton (const TabBarButton&);
  35238. const TabBarButton& operator= (const TabBarButton&);
  35239. };
  35240. /**
  35241. A vertical or horizontal bar containing tabs that you can select.
  35242. You can use one of these to generate things like a dialog box that has
  35243. tabbed pages you can flip between. Attach a ChangeListener to the
  35244. button bar to be told when the user changes the page.
  35245. An easier method than doing this is to use a TabbedComponent, which
  35246. contains its own TabbedButtonBar and which takes care of the layout
  35247. and other housekeeping.
  35248. @see TabbedComponent
  35249. */
  35250. class JUCE_API TabbedButtonBar : public Component,
  35251. public ChangeBroadcaster,
  35252. public ButtonListener
  35253. {
  35254. public:
  35255. /** The placement of the tab-bar
  35256. @see setOrientation, getOrientation
  35257. */
  35258. enum Orientation
  35259. {
  35260. TabsAtTop,
  35261. TabsAtBottom,
  35262. TabsAtLeft,
  35263. TabsAtRight
  35264. };
  35265. /** Creates a TabbedButtonBar with a given placement.
  35266. You can change the orientation later if you need to.
  35267. */
  35268. TabbedButtonBar (const Orientation orientation);
  35269. /** Destructor. */
  35270. ~TabbedButtonBar();
  35271. /** Changes the bar's orientation.
  35272. This won't change the bar's actual size - you'll need to do that yourself,
  35273. but this determines which direction the tabs go in, and which side they're
  35274. stuck to.
  35275. */
  35276. void setOrientation (const Orientation orientation);
  35277. /** Returns the current orientation.
  35278. @see setOrientation
  35279. */
  35280. Orientation getOrientation() const throw() { return orientation; }
  35281. /** Deletes all the tabs from the bar.
  35282. @see addTab
  35283. */
  35284. void clearTabs();
  35285. /** Adds a tab to the bar.
  35286. Tabs are added in left-to-right reading order.
  35287. If this is the first tab added, it'll also be automatically selected.
  35288. */
  35289. void addTab (const String& tabName,
  35290. const Colour& tabBackgroundColour,
  35291. int insertIndex = -1);
  35292. /** Changes the name of one of the tabs. */
  35293. void setTabName (const int tabIndex,
  35294. const String& newName);
  35295. /** Gets rid of one of the tabs. */
  35296. void removeTab (const int tabIndex);
  35297. /** Moves a tab to a new index in the list.
  35298. Pass -1 as the index to move it to the end of the list.
  35299. */
  35300. void moveTab (const int currentIndex,
  35301. const int newIndex);
  35302. /** Returns the number of tabs in the bar. */
  35303. int getNumTabs() const;
  35304. /** Returns a list of all the tab names in the bar. */
  35305. const StringArray getTabNames() const;
  35306. /** Changes the currently selected tab.
  35307. This will send a change message and cause a synchronous callback to
  35308. the currentTabChanged() method. (But if the given tab is already selected,
  35309. nothing will be done).
  35310. To deselect all the tabs, use an index of -1.
  35311. */
  35312. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  35313. /** Returns the name of the currently selected tab.
  35314. This could be an empty string if none are selected.
  35315. */
  35316. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  35317. /** Returns the index of the currently selected tab.
  35318. This could return -1 if none are selected.
  35319. */
  35320. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  35321. /** Returns the button for a specific tab.
  35322. The button that is returned may be deleted later by this component, so don't hang
  35323. on to the pointer that is returned. A null pointer may be returned if the index is
  35324. out of range.
  35325. */
  35326. TabBarButton* getTabButton (const int index) const;
  35327. /** Callback method to indicate the selected tab has been changed.
  35328. @see setCurrentTabIndex
  35329. */
  35330. virtual void currentTabChanged (const int newCurrentTabIndex,
  35331. const String& newCurrentTabName);
  35332. /** Callback method to indicate that the user has right-clicked on a tab.
  35333. (Or ctrl-clicked on the Mac)
  35334. */
  35335. virtual void popupMenuClickOnTab (const int tabIndex,
  35336. const String& tabName);
  35337. /** Returns the colour of a tab.
  35338. This is the colour that was specified in addTab().
  35339. */
  35340. const Colour getTabBackgroundColour (const int tabIndex);
  35341. /** Changes the background colour of a tab.
  35342. @see addTab, getTabBackgroundColour
  35343. */
  35344. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35345. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35346. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35347. methods.
  35348. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35349. */
  35350. enum ColourIds
  35351. {
  35352. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  35353. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  35354. the look and feel will choose an appropriate colour. */
  35355. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  35356. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  35357. this isn't specified, the look and feel will choose an appropriate
  35358. colour. */
  35359. };
  35360. /** @internal */
  35361. void resized();
  35362. /** @internal */
  35363. void buttonClicked (Button* button);
  35364. /** @internal */
  35365. void lookAndFeelChanged();
  35366. juce_UseDebuggingNewOperator
  35367. protected:
  35368. /** This creates one of the tabs.
  35369. If you need to use custom tab components, you can override this method and
  35370. return your own class instead of the default.
  35371. */
  35372. virtual TabBarButton* createTabButton (const String& tabName,
  35373. const int tabIndex);
  35374. private:
  35375. Orientation orientation;
  35376. StringArray tabs;
  35377. Array <Colour> tabColours;
  35378. int currentTabIndex;
  35379. Component* behindFrontTab;
  35380. Button* extraTabsButton;
  35381. TabbedButtonBar (const TabbedButtonBar&);
  35382. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  35383. };
  35384. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35385. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  35386. /**
  35387. A component with a TabbedButtonBar along one of its sides.
  35388. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  35389. with addTab(), and this will take care of showing the pages for you when the
  35390. user clicks on a different tab.
  35391. @see TabbedButtonBar
  35392. */
  35393. class JUCE_API TabbedComponent : public Component
  35394. {
  35395. public:
  35396. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  35397. Once created, add some tabs with the addTab() method.
  35398. */
  35399. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  35400. /** Destructor. */
  35401. ~TabbedComponent();
  35402. /** Changes the placement of the tabs.
  35403. This will rearrange the layout to place the tabs along the appropriate
  35404. side of this component, and will shift the content component accordingly.
  35405. @see TabbedButtonBar::setOrientation
  35406. */
  35407. void setOrientation (const TabbedButtonBar::Orientation orientation);
  35408. /** Returns the current tab placement.
  35409. @see setOrientation, TabbedButtonBar::getOrientation
  35410. */
  35411. TabbedButtonBar::Orientation getOrientation() const throw();
  35412. /** Specifies how many pixels wide or high the tab-bar should be.
  35413. If the tabs are placed along the top or bottom, this specified the height
  35414. of the bar; if they're along the left or right edges, it'll be the width
  35415. of the bar.
  35416. */
  35417. void setTabBarDepth (const int newDepth);
  35418. /** Returns the current thickness of the tab bar.
  35419. @see setTabBarDepth
  35420. */
  35421. int getTabBarDepth() const throw() { return tabDepth; }
  35422. /** Specifies the thickness of an outline that should be drawn around the content component.
  35423. If this thickness is > 0, a line will be drawn around the three sides of the content
  35424. component which don't touch the tab-bar, and the content component will be inset by this amount.
  35425. To set the colour of the line, use setColour (outlineColourId, ...).
  35426. */
  35427. void setOutline (const int newThickness);
  35428. /** Specifies a gap to leave around the edge of the content component.
  35429. Each edge of the content component will be indented by the given number of pixels.
  35430. */
  35431. void setIndent (const int indentThickness);
  35432. /** Removes all the tabs from the bar.
  35433. @see TabbedButtonBar::clearTabs
  35434. */
  35435. void clearTabs();
  35436. /** Adds a tab to the tab-bar.
  35437. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  35438. is true, it will be deleted when the tab is removed or when this object is
  35439. deleted.
  35440. @see TabbedButtonBar::addTab
  35441. */
  35442. void addTab (const String& tabName,
  35443. const Colour& tabBackgroundColour,
  35444. Component* const contentComponent,
  35445. const bool deleteComponentWhenNotNeeded,
  35446. const int insertIndex = -1);
  35447. /** Changes the name of one of the tabs. */
  35448. void setTabName (const int tabIndex,
  35449. const String& newName);
  35450. /** Gets rid of one of the tabs. */
  35451. void removeTab (const int tabIndex);
  35452. /** Returns the number of tabs in the bar. */
  35453. int getNumTabs() const;
  35454. /** Returns a list of all the tab names in the bar. */
  35455. const StringArray getTabNames() const;
  35456. /** Returns the content component that was added for the given index.
  35457. Be sure not to use or delete the components that are returned, as this may interfere
  35458. with the TabbedComponent's use of them.
  35459. */
  35460. Component* getTabContentComponent (const int tabIndex) const throw();
  35461. /** Returns the colour of one of the tabs. */
  35462. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  35463. /** Changes the background colour of one of the tabs. */
  35464. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35465. /** Changes the currently-selected tab.
  35466. To deselect all the tabs, pass -1 as the index.
  35467. @see TabbedButtonBar::setCurrentTabIndex
  35468. */
  35469. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  35470. /** Returns the index of the currently selected tab.
  35471. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  35472. */
  35473. int getCurrentTabIndex() const;
  35474. /** Returns the name of the currently selected tab.
  35475. @see addTab, TabbedButtonBar::getCurrentTabName()
  35476. */
  35477. const String& getCurrentTabName() const;
  35478. /** Returns the current component that's filling the panel.
  35479. This will return 0 if there isn't one.
  35480. */
  35481. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  35482. /** Callback method to indicate the selected tab has been changed.
  35483. @see setCurrentTabIndex
  35484. */
  35485. virtual void currentTabChanged (const int newCurrentTabIndex,
  35486. const String& newCurrentTabName);
  35487. /** Callback method to indicate that the user has right-clicked on a tab.
  35488. (Or ctrl-clicked on the Mac)
  35489. */
  35490. virtual void popupMenuClickOnTab (const int tabIndex,
  35491. const String& tabName);
  35492. /** Returns the tab button bar component that is being used.
  35493. */
  35494. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  35495. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35496. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35497. methods.
  35498. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35499. */
  35500. enum ColourIds
  35501. {
  35502. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  35503. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  35504. (See setOutline) */
  35505. };
  35506. /** @internal */
  35507. void paint (Graphics& g);
  35508. /** @internal */
  35509. void resized();
  35510. /** @internal */
  35511. void lookAndFeelChanged();
  35512. juce_UseDebuggingNewOperator
  35513. protected:
  35514. TabbedButtonBar* tabs;
  35515. /** This creates one of the tab buttons.
  35516. If you need to use custom tab components, you can override this method and
  35517. return your own class instead of the default.
  35518. */
  35519. virtual TabBarButton* createTabButton (const String& tabName,
  35520. const int tabIndex);
  35521. private:
  35522. Array <Component*> contentComponents;
  35523. Component* panelComponent;
  35524. int tabDepth;
  35525. int outlineThickness, edgeIndent;
  35526. friend class TabCompButtonBar;
  35527. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  35528. TabbedComponent (const TabbedComponent&);
  35529. const TabbedComponent& operator= (const TabbedComponent&);
  35530. };
  35531. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35532. /********* End of inlined file: juce_TabbedComponent.h *********/
  35533. /********* Start of inlined file: juce_DocumentWindow.h *********/
  35534. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35535. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35536. /********* Start of inlined file: juce_ResizableWindow.h *********/
  35537. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35538. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35539. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  35540. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35541. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35542. /********* Start of inlined file: juce_DropShadower.h *********/
  35543. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  35544. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  35545. /**
  35546. Adds a drop-shadow to a component.
  35547. This object creates and manages a set of components which sit around a
  35548. component, creating a gaussian shadow around it. The components will track
  35549. the position of the component and if it's brought to the front they'll also
  35550. follow this.
  35551. For desktop windows you don't need to use this class directly - just
  35552. set the Component::windowHasDropShadow flag when calling
  35553. Component::addToDesktop(), and the system will create one of these if it's
  35554. needed (which it obviously isn't on the Mac, for example).
  35555. */
  35556. class JUCE_API DropShadower : public ComponentListener
  35557. {
  35558. public:
  35559. /** Creates a DropShadower.
  35560. @param alpha the opacity of the shadows, from 0 to 1.0
  35561. @param xOffset the horizontal displacement of the shadow, in pixels
  35562. @param yOffset the vertical displacement of the shadow, in pixels
  35563. @param blurRadius the radius of the blur to use for creating the shadow
  35564. */
  35565. DropShadower (const float alpha = 0.5f,
  35566. const int xOffset = 1,
  35567. const int yOffset = 5,
  35568. const float blurRadius = 10.0f);
  35569. /** Destructor. */
  35570. virtual ~DropShadower();
  35571. /** Attaches the DropShadower to the component you want to shadow. */
  35572. void setOwner (Component* componentToFollow);
  35573. /** @internal */
  35574. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35575. /** @internal */
  35576. void componentBroughtToFront (Component& component);
  35577. /** @internal */
  35578. void componentChildrenChanged (Component& component);
  35579. /** @internal */
  35580. void componentParentHierarchyChanged (Component& component);
  35581. /** @internal */
  35582. void componentVisibilityChanged (Component& component);
  35583. juce_UseDebuggingNewOperator
  35584. private:
  35585. Component* owner;
  35586. int numShadows;
  35587. Component* shadowWindows[4];
  35588. Image* shadowImageSections[12];
  35589. const int shadowEdge, xOffset, yOffset;
  35590. const float alpha, blurRadius;
  35591. bool inDestructor, reentrant;
  35592. void updateShadows();
  35593. void setShadowImage (Image* const src,
  35594. const int num,
  35595. const int w, const int h,
  35596. const int sx, const int sy) throw();
  35597. void bringShadowWindowsToFront();
  35598. void deleteShadowWindows();
  35599. DropShadower (const DropShadower&);
  35600. const DropShadower& operator= (const DropShadower&);
  35601. };
  35602. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35603. /********* End of inlined file: juce_DropShadower.h *********/
  35604. /**
  35605. A base class for top-level windows.
  35606. This class is used for components that are considered a major part of your
  35607. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35608. etc. Things like menus that pop up briefly aren't derived from it.
  35609. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35610. could itself be the child of another component.
  35611. The class manages a list of all instances of top-level windows that are in use,
  35612. and each one is also given the concept of being "active". The active window is
  35613. one that is actively being used by the user. This isn't quite the same as the
  35614. component with the keyboard focus, because there may be a popup menu or other
  35615. temporary window which gets keyboard focus while the active top level window is
  35616. unchanged.
  35617. A top-level window also has an optional drop-shadow.
  35618. @see ResizableWindow, DocumentWindow, DialogWindow
  35619. */
  35620. class JUCE_API TopLevelWindow : public Component
  35621. {
  35622. public:
  35623. /** Creates a TopLevelWindow.
  35624. @param name the name to give the component
  35625. @param addToDesktop if true, the window will be automatically added to the
  35626. desktop; if false, you can use it as a child component
  35627. */
  35628. TopLevelWindow (const String& name,
  35629. const bool addToDesktop);
  35630. /** Destructor. */
  35631. ~TopLevelWindow();
  35632. /** True if this is currently the TopLevelWindow that is actively being used.
  35633. This isn't quite the same as having keyboard focus, because the focus may be
  35634. on a child component or a temporary pop-up menu, etc, while this window is
  35635. still considered to be active.
  35636. @see activeWindowStatusChanged
  35637. */
  35638. bool isActiveWindow() const throw() { return windowIsActive_; }
  35639. /** This will set the bounds of the window so that it's centred in front of another
  35640. window.
  35641. If your app has a few windows open and want to pop up a dialog box for one of
  35642. them, you can use this to show it in front of the relevent parent window, which
  35643. is a bit neater than just having it appear in the middle of the screen.
  35644. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35645. be used instead. If no window is focused, it'll just default to the middle of the
  35646. screen.
  35647. */
  35648. void centreAroundComponent (Component* componentToCentreAround,
  35649. const int width, const int height);
  35650. /** Turns the drop-shadow on and off. */
  35651. void setDropShadowEnabled (const bool useShadow);
  35652. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35653. @see isUsingNativeTitleBar
  35654. */
  35655. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35656. /** Returns true if the window is currently using an OS-native title bar.
  35657. @see setUsingNativeTitleBar
  35658. */
  35659. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35660. /** Returns the number of TopLevelWindow objects currently in use.
  35661. @see getTopLevelWindow
  35662. */
  35663. static int getNumTopLevelWindows() throw();
  35664. /** Returns one of the TopLevelWindow objects currently in use.
  35665. The index is 0 to (getNumTopLevelWindows() - 1).
  35666. */
  35667. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35668. /** Returns the currently-active top level window.
  35669. There might not be one, of course, so this can return 0.
  35670. */
  35671. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35672. juce_UseDebuggingNewOperator
  35673. /** @internal */
  35674. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35675. protected:
  35676. /** This callback happens when this window becomes active or inactive.
  35677. @see isActiveWindow
  35678. */
  35679. virtual void activeWindowStatusChanged();
  35680. /** @internal */
  35681. void focusOfChildComponentChanged (FocusChangeType cause);
  35682. /** @internal */
  35683. void parentHierarchyChanged();
  35684. /** @internal */
  35685. void visibilityChanged();
  35686. /** @internal */
  35687. virtual int getDesktopWindowStyleFlags() const;
  35688. /** @internal */
  35689. void recreateDesktopWindow();
  35690. private:
  35691. friend class TopLevelWindowManager;
  35692. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35693. DropShadower* shadower;
  35694. void setWindowActive (const bool isNowActive) throw();
  35695. TopLevelWindow (const TopLevelWindow&);
  35696. const TopLevelWindow& operator= (const TopLevelWindow&);
  35697. };
  35698. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35699. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35700. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35701. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35702. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35703. /**
  35704. A component that resizes its parent window when dragged.
  35705. This component forms a frame around the edge of a component, allowing it to
  35706. be dragged by the edges or corners to resize it - like the way windows are
  35707. resized in MSWindows or Linux.
  35708. To use it, just add it to your component, making it fill the entire parent component
  35709. (there's a mouse hit-test that only traps mouse-events which land around the
  35710. edge of the component, so it's even ok to put it on top of any other components
  35711. you're using). Make sure you rescale the resizer component to fill the parent
  35712. each time the parent's size changes.
  35713. @see ResizableCornerComponent
  35714. */
  35715. class JUCE_API ResizableBorderComponent : public Component
  35716. {
  35717. public:
  35718. /** Creates a resizer.
  35719. Pass in the target component which you want to be resized when this one is
  35720. dragged.
  35721. The target component will usually be a parent of the resizer component, but this
  35722. isn't mandatory.
  35723. Remember that when the target component is resized, it'll need to move and
  35724. resize this component to keep it in place, as this won't happen automatically.
  35725. If the constrainer parameter is non-zero, then this object will be used to enforce
  35726. limits on the size and position that the component can be stretched to. Make sure
  35727. that the constrainer isn't deleted while still in use by this object.
  35728. @see ComponentBoundsConstrainer
  35729. */
  35730. ResizableBorderComponent (Component* const componentToResize,
  35731. ComponentBoundsConstrainer* const constrainer);
  35732. /** Destructor. */
  35733. ~ResizableBorderComponent();
  35734. /** Specifies how many pixels wide the draggable edges of this component are.
  35735. @see getBorderThickness
  35736. */
  35737. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35738. /** Returns the number of pixels wide that the draggable edges of this component are.
  35739. @see setBorderThickness
  35740. */
  35741. const BorderSize getBorderThickness() const throw();
  35742. juce_UseDebuggingNewOperator
  35743. protected:
  35744. /** @internal */
  35745. void paint (Graphics& g);
  35746. /** @internal */
  35747. void mouseEnter (const MouseEvent& e);
  35748. /** @internal */
  35749. void mouseMove (const MouseEvent& e);
  35750. /** @internal */
  35751. void mouseDown (const MouseEvent& e);
  35752. /** @internal */
  35753. void mouseDrag (const MouseEvent& e);
  35754. /** @internal */
  35755. void mouseUp (const MouseEvent& e);
  35756. /** @internal */
  35757. bool hitTest (int x, int y);
  35758. private:
  35759. Component* const component;
  35760. ComponentBoundsConstrainer* constrainer;
  35761. BorderSize borderSize;
  35762. int originalX, originalY, originalW, originalH;
  35763. int mouseZone;
  35764. void updateMouseZone (const MouseEvent& e) throw();
  35765. ResizableBorderComponent (const ResizableBorderComponent&);
  35766. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35767. };
  35768. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35769. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35770. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35771. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35772. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35773. /** A component that resizes a parent window when dragged.
  35774. This is the small triangular stripey resizer component you get in the bottom-right
  35775. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35776. a larger component and it will automatically resize its parent when it gets dragged
  35777. around.
  35778. @see ResizableFrameComponent
  35779. */
  35780. class JUCE_API ResizableCornerComponent : public Component
  35781. {
  35782. public:
  35783. /** Creates a resizer.
  35784. Pass in the target component which you want to be resized when this one is
  35785. dragged.
  35786. The target component will usually be a parent of the resizer component, but this
  35787. isn't mandatory.
  35788. Remember that when the target component is resized, it'll need to move and
  35789. resize this component to keep it in place, as this won't happen automatically.
  35790. If the constrainer parameter is non-zero, then this object will be used to enforce
  35791. limits on the size and position that the component can be stretched to. Make sure
  35792. that the constrainer isn't deleted while still in use by this object. If you
  35793. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35794. @see ComponentBoundsConstrainer
  35795. */
  35796. ResizableCornerComponent (Component* const componentToResize,
  35797. ComponentBoundsConstrainer* const constrainer);
  35798. /** Destructor. */
  35799. ~ResizableCornerComponent();
  35800. juce_UseDebuggingNewOperator
  35801. protected:
  35802. /** @internal */
  35803. void paint (Graphics& g);
  35804. /** @internal */
  35805. void mouseDown (const MouseEvent& e);
  35806. /** @internal */
  35807. void mouseDrag (const MouseEvent& e);
  35808. /** @internal */
  35809. void mouseUp (const MouseEvent& e);
  35810. /** @internal */
  35811. bool hitTest (int x, int y);
  35812. private:
  35813. Component* const component;
  35814. ComponentBoundsConstrainer* constrainer;
  35815. int originalX, originalY, originalW, originalH;
  35816. ResizableCornerComponent (const ResizableCornerComponent&);
  35817. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35818. };
  35819. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35820. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35821. /**
  35822. A base class for top-level windows that can be dragged around and resized.
  35823. To add content to the window, use its setContentComponent() method to
  35824. give it a component that will remain positioned inside it (leaving a gap around
  35825. the edges for a border).
  35826. It's not advisable to add child components directly to a ResizableWindow: put them
  35827. inside your content component instead. And overriding methods like resized(), moved(), etc
  35828. is also not recommended - instead override these methods for your content component.
  35829. (If for some obscure reason you do need to override these methods, always remember to
  35830. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35831. decorations correctly).
  35832. By default resizing isn't enabled - use the setResizable() method to enable it and
  35833. to choose the style of resizing to use.
  35834. @see TopLevelWindow
  35835. */
  35836. class JUCE_API ResizableWindow : public TopLevelWindow
  35837. {
  35838. public:
  35839. /** Creates a ResizableWindow.
  35840. This constructor doesn't specify a background colour, so the LookAndFeel's default
  35841. background colour will be used.
  35842. @param name the name to give the component
  35843. @param addToDesktop if true, the window will be automatically added to the
  35844. desktop; if false, you can use it as a child component
  35845. */
  35846. ResizableWindow (const String& name,
  35847. const bool addToDesktop);
  35848. /** Creates a ResizableWindow.
  35849. @param name the name to give the component
  35850. @param backgroundColour the colour to use for filling the window's background.
  35851. @param addToDesktop if true, the window will be automatically added to the
  35852. desktop; if false, you can use it as a child component
  35853. */
  35854. ResizableWindow (const String& name,
  35855. const Colour& backgroundColour,
  35856. const bool addToDesktop);
  35857. /** Destructor.
  35858. If a content component has been set with setContentComponent(), it
  35859. will be deleted.
  35860. */
  35861. ~ResizableWindow();
  35862. /** Returns the colour currently being used for the window's background.
  35863. As a convenience the window will fill itself with this colour, but you
  35864. can override the paint() method if you need more customised behaviour.
  35865. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  35866. @see setBackgroundColour
  35867. */
  35868. const Colour getBackgroundColour() const throw();
  35869. /** Changes the colour currently being used for the window's background.
  35870. As a convenience the window will fill itself with this colour, but you
  35871. can override the paint() method if you need more customised behaviour.
  35872. Note that the opaque state of this window is altered by this call to reflect
  35873. the opacity of the colour passed-in. On window systems which can't support
  35874. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35875. be using this class as a base for a semi-transparent component anyway).
  35876. You can also use the ResizableWindow::backgroundColourId colour id to set
  35877. this colour.
  35878. @see getBackgroundColour
  35879. */
  35880. void setBackgroundColour (const Colour& newColour);
  35881. /** Make the window resizable or fixed.
  35882. @param shouldBeResizable whether it's resizable at all
  35883. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35884. bottom-right; if false, it'll use a ResizableBorderComponent
  35885. around the edge
  35886. @see setResizeLimits, isResizable
  35887. */
  35888. void setResizable (const bool shouldBeResizable,
  35889. const bool useBottomRightCornerResizer);
  35890. /** True if resizing is enabled.
  35891. @see setResizable
  35892. */
  35893. bool isResizable() const throw();
  35894. /** This sets the maximum and minimum sizes for the window.
  35895. If the window's current size is outside these limits, it will be resized to
  35896. make sure it's within them.
  35897. Calling setBounds() on the component will bypass any size checking - it's only when
  35898. the window is being resized by the user that these values are enforced.
  35899. @see setResizable, setFixedAspectRatio
  35900. */
  35901. void setResizeLimits (const int newMinimumWidth,
  35902. const int newMinimumHeight,
  35903. const int newMaximumWidth,
  35904. const int newMaximumHeight) throw();
  35905. /** Returns the bounds constrainer object that this window is using.
  35906. You can access this to change its properties.
  35907. */
  35908. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35909. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35910. A pointer to the object you pass in will be kept, but it won't be deleted
  35911. by this object, so it's the caller's responsiblity to manage it.
  35912. If you pass 0, then no contraints will be placed on the positioning of the window.
  35913. */
  35914. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35915. /** Calls the window's setBounds method, after first checking these bounds
  35916. with the current constrainer.
  35917. @see setConstrainer
  35918. */
  35919. void setBoundsConstrained (int x, int y, int width, int height);
  35920. /** Returns true if the window is currently in full-screen mode.
  35921. @see setFullScreen
  35922. */
  35923. bool isFullScreen() const;
  35924. /** Puts the window into full-screen mode, or restores it to its normal size.
  35925. If true, the window will become full-screen; if false, it will return to the
  35926. last size it was before being made full-screen.
  35927. @see isFullScreen
  35928. */
  35929. void setFullScreen (const bool shouldBeFullScreen);
  35930. /** Returns true if the window is currently minimised.
  35931. @see setMinimised
  35932. */
  35933. bool isMinimised() const;
  35934. /** Minimises the window, or restores it to its previous position and size.
  35935. When being un-minimised, it'll return to the last position and size it
  35936. was in before being minimised.
  35937. @see isMinimised
  35938. */
  35939. void setMinimised (const bool shouldMinimise);
  35940. /** Returns a string which encodes the window's current size and position.
  35941. This string will encapsulate the window's size, position, and whether it's
  35942. in full-screen mode. It's intended for letting your application save and
  35943. restore a window's position.
  35944. Use the restoreWindowStateFromString() to restore from a saved state.
  35945. @see restoreWindowStateFromString
  35946. */
  35947. const String getWindowStateAsString();
  35948. /** Restores the window to a previously-saved size and position.
  35949. This restores the window's size, positon and full-screen status from an
  35950. string that was previously created with the getWindowStateAsString()
  35951. method.
  35952. @returns false if the string wasn't a valid window state
  35953. @see getWindowStateAsString
  35954. */
  35955. bool restoreWindowStateFromString (const String& previousState);
  35956. /** Returns the current content component.
  35957. This will be the component set by setContentComponent(), or 0 if none
  35958. has yet been specified.
  35959. @see setContentComponent
  35960. */
  35961. Component* getContentComponent() const throw() { return contentComponent; }
  35962. /** Changes the current content component.
  35963. This sets a component that will be placed in the centre of the ResizableWindow,
  35964. (leaving a space around the edge for the border).
  35965. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35966. with addChildComponent(). Instead, add them to the content component.
  35967. @param newContentComponent the new component to use (or null to not use one) - this
  35968. component will be deleted either when replaced by another call
  35969. to this method, or when the ResizableWindow is deleted.
  35970. To remove a content component without deleting it, use
  35971. setContentComponent (0, false).
  35972. @param deleteOldOne if true, the previous content component will be deleted; if
  35973. false, the previous component will just be removed without
  35974. deleting it.
  35975. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35976. it always fits around the size of the content component. If false, the
  35977. new content will be resized to fit the current space available.
  35978. */
  35979. void setContentComponent (Component* const newContentComponent,
  35980. const bool deleteOldOne = true,
  35981. const bool resizeToFit = false);
  35982. /** Changes the window so that the content component ends up with the specified size.
  35983. This is basically a setSize call on the window, but which adds on the borders,
  35984. so you can specify the content component's target size.
  35985. */
  35986. void setContentComponentSize (int width, int height);
  35987. /** A set of colour IDs to use to change the colour of various aspects of the window.
  35988. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35989. methods.
  35990. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35991. */
  35992. enum ColourIds
  35993. {
  35994. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  35995. };
  35996. juce_UseDebuggingNewOperator
  35997. protected:
  35998. /** @internal */
  35999. void paint (Graphics& g);
  36000. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  36001. void moved();
  36002. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  36003. void resized();
  36004. /** @internal */
  36005. void mouseDown (const MouseEvent& e);
  36006. /** @internal */
  36007. void mouseDrag (const MouseEvent& e);
  36008. /** @internal */
  36009. void lookAndFeelChanged();
  36010. /** @internal */
  36011. void childBoundsChanged (Component* child);
  36012. /** @internal */
  36013. void parentSizeChanged();
  36014. /** @internal */
  36015. void visibilityChanged();
  36016. /** @internal */
  36017. void activeWindowStatusChanged();
  36018. /** @internal */
  36019. int getDesktopWindowStyleFlags() const;
  36020. /** Returns the width of the border to use around the window.
  36021. @see getContentComponentBorder
  36022. */
  36023. virtual const BorderSize getBorderThickness();
  36024. /** Returns the insets to use when positioning the content component.
  36025. @see getBorderThickness
  36026. */
  36027. virtual const BorderSize getContentComponentBorder();
  36028. #ifdef JUCE_DEBUG
  36029. /** Overridden to warn people about adding components directly to this component
  36030. instead of using setContentComponent().
  36031. If you know what you're doing and are sure you really want to add a component, specify
  36032. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  36033. */
  36034. void addChildComponent (Component* const child, int zOrder = -1);
  36035. /** Overridden to warn people about adding components directly to this component
  36036. instead of using setContentComponent().
  36037. If you know what you're doing and are sure you really want to add a component, specify
  36038. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  36039. */
  36040. void addAndMakeVisible (Component* const child, int zOrder = -1);
  36041. #endif
  36042. ResizableCornerComponent* resizableCorner;
  36043. ResizableBorderComponent* resizableBorder;
  36044. private:
  36045. Component* contentComponent;
  36046. bool resizeToFitContent, fullscreen;
  36047. ComponentDragger dragger;
  36048. Rectangle lastNonFullScreenPos;
  36049. ComponentBoundsConstrainer defaultConstrainer;
  36050. ComponentBoundsConstrainer* constrainer;
  36051. #ifdef JUCE_DEBUG
  36052. bool hasBeenResized;
  36053. #endif
  36054. void updateLastPos();
  36055. ResizableWindow (const ResizableWindow&);
  36056. const ResizableWindow& operator= (const ResizableWindow&);
  36057. // (xxx remove these eventually)
  36058. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36059. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  36060. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36061. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  36062. };
  36063. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36064. /********* End of inlined file: juce_ResizableWindow.h *********/
  36065. /**
  36066. A resizable window with a title bar and maximise, minimise and close buttons.
  36067. This subclass of ResizableWindow creates a fairly standard type of window with
  36068. a title bar and various buttons. The name of the component is shown in the
  36069. title bar, and an icon can optionally be specified with setIcon().
  36070. All the methods available to a ResizableWindow are also available to this,
  36071. so it can easily be made resizable, minimised, maximised, etc.
  36072. It's not advisable to add child components directly to a DocumentWindow: put them
  36073. inside your content component instead. And overriding methods like resized(), moved(), etc
  36074. is also not recommended - instead override these methods for your content component.
  36075. (If for some obscure reason you do need to override these methods, always remember to
  36076. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36077. decorations correctly).
  36078. You can also automatically add a menu bar to the window, using the setMenuBar()
  36079. method.
  36080. @see ResizableWindow, DialogWindow
  36081. */
  36082. class JUCE_API DocumentWindow : public ResizableWindow
  36083. {
  36084. public:
  36085. /** The set of available button-types that can be put on the title bar.
  36086. @see setTitleBarButtonsRequired
  36087. */
  36088. enum TitleBarButtons
  36089. {
  36090. minimiseButton = 1,
  36091. maximiseButton = 2,
  36092. closeButton = 4,
  36093. /** A combination of all the buttons above. */
  36094. allButtons = 7
  36095. };
  36096. /** Creates a DocumentWindow.
  36097. @param name the name to give the component - this is also
  36098. the title shown at the top of the window. To change
  36099. this later, use setName()
  36100. @param backgroundColour the colour to use for filling the window's background.
  36101. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36102. should be shown on the title bar. This value is a bitwise
  36103. combination of values from the TitleBarButtons enum. Note
  36104. that it can be "allButtons" to get them all. You
  36105. can change this later with the setTitleBarButtonsRequired()
  36106. method, which can also specify where they are positioned.
  36107. @param addToDesktop if true, the window will be automatically added to the
  36108. desktop; if false, you can use it as a child component
  36109. @see TitleBarButtons
  36110. */
  36111. DocumentWindow (const String& name,
  36112. const Colour& backgroundColour,
  36113. const int requiredButtons,
  36114. const bool addToDesktop = true);
  36115. /** Destructor.
  36116. If a content component has been set with setContentComponent(), it
  36117. will be deleted.
  36118. */
  36119. ~DocumentWindow();
  36120. /** Changes the component's name.
  36121. (This is overridden from Component::setName() to cause a repaint, as
  36122. the name is what gets drawn across the window's title bar).
  36123. */
  36124. void setName (const String& newName);
  36125. /** Sets an icon to show in the title bar, next to the title.
  36126. A copy is made internally of the image, so the caller can delete the
  36127. image after calling this. If 0 is passed-in, any existing icon will be
  36128. removed.
  36129. */
  36130. void setIcon (const Image* imageToUse);
  36131. /** Changes the height of the title-bar. */
  36132. void setTitleBarHeight (const int newHeight);
  36133. /** Returns the current title bar height. */
  36134. int getTitleBarHeight() const;
  36135. /** Changes the set of title-bar buttons being shown.
  36136. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36137. should be shown on the title bar. This value is a bitwise
  36138. combination of values from the TitleBarButtons enum. Note
  36139. that it can be "allButtons" to get them all.
  36140. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  36141. left side of the bar; if false, they'll be placed at the right
  36142. */
  36143. void setTitleBarButtonsRequired (const int requiredButtons,
  36144. const bool positionTitleBarButtonsOnLeft);
  36145. /** Sets whether the title should be centred within the window.
  36146. If true, the title text is shown in the middle of the title-bar; if false,
  36147. it'll be shown at the left of the bar.
  36148. */
  36149. void setTitleBarTextCentred (const bool textShouldBeCentred);
  36150. /** Creates a menu inside this window.
  36151. @param menuBarModel this specifies a MenuBarModel that should be used to
  36152. generate the contents of a menu bar that will be placed
  36153. just below the title bar, and just above any content
  36154. component. If this value is zero, any existing menu bar
  36155. will be removed from the component; if non-zero, one will
  36156. be added if it's required.
  36157. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  36158. or less to use the look-and-feel's default size.
  36159. */
  36160. void setMenuBar (MenuBarModel* menuBarModel,
  36161. const int menuBarHeight = 0);
  36162. /** This method is called when the user tries to close the window.
  36163. This is triggered by the user clicking the close button, or using some other
  36164. OS-specific key shortcut or OS menu for getting rid of a window.
  36165. If the window is just a pop-up, you should override this closeButtonPressed()
  36166. method and make it delete the window in whatever way is appropriate for your
  36167. app. E.g. you might just want to call "delete this".
  36168. If your app is centred around this window such that the whole app should quit when
  36169. the window is closed, then you will probably want to use this method as an opportunity
  36170. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  36171. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  36172. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  36173. or closing it via the taskbar icon on Windows).
  36174. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  36175. redirects it to call this method, so any methods of closing the window that are
  36176. caught by userTriedToCloseWindow() will also end up here).
  36177. */
  36178. virtual void closeButtonPressed();
  36179. /** Callback that is triggered when the minimise button is pressed.
  36180. The default implementation of this calls ResizableWindow::setMinimised(), but
  36181. you can override it to do more customised behaviour.
  36182. */
  36183. virtual void minimiseButtonPressed();
  36184. /** Callback that is triggered when the maximise button is pressed, or when the
  36185. title-bar is double-clicked.
  36186. The default implementation of this calls ResizableWindow::setFullScreen(), but
  36187. you can override it to do more customised behaviour.
  36188. */
  36189. virtual void maximiseButtonPressed();
  36190. /** Returns the close button, (or 0 if there isn't one). */
  36191. Button* getCloseButton() const throw();
  36192. /** Returns the minimise button, (or 0 if there isn't one). */
  36193. Button* getMinimiseButton() const throw();
  36194. /** Returns the maximise button, (or 0 if there isn't one). */
  36195. Button* getMaximiseButton() const throw();
  36196. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36197. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36198. methods.
  36199. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36200. */
  36201. enum ColourIds
  36202. {
  36203. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  36204. and feel class how this is used. */
  36205. };
  36206. /** @internal */
  36207. void paint (Graphics& g);
  36208. /** @internal */
  36209. void resized();
  36210. /** @internal */
  36211. void lookAndFeelChanged();
  36212. /** @internal */
  36213. const BorderSize getBorderThickness();
  36214. /** @internal */
  36215. const BorderSize getContentComponentBorder();
  36216. /** @internal */
  36217. void mouseDoubleClick (const MouseEvent& e);
  36218. /** @internal */
  36219. void userTriedToCloseWindow();
  36220. /** @internal */
  36221. void activeWindowStatusChanged();
  36222. /** @internal */
  36223. int getDesktopWindowStyleFlags() const;
  36224. /** @internal */
  36225. void parentHierarchyChanged();
  36226. juce_UseDebuggingNewOperator
  36227. private:
  36228. int titleBarHeight, menuBarHeight, requiredButtons;
  36229. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  36230. Button* titleBarButtons [3];
  36231. Image* titleBarIcon;
  36232. MenuBarComponent* menuBar;
  36233. MenuBarModel* menuBarModel;
  36234. class ButtonListenerProxy : public ButtonListener
  36235. {
  36236. public:
  36237. ButtonListenerProxy();
  36238. void buttonClicked (Button* button);
  36239. DocumentWindow* owner;
  36240. } buttonListener;
  36241. int getBorderSize() const;
  36242. void repaintTitleBar();
  36243. DocumentWindow (const DocumentWindow&);
  36244. const DocumentWindow& operator= (const DocumentWindow&);
  36245. };
  36246. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36247. /********* End of inlined file: juce_DocumentWindow.h *********/
  36248. class MultiDocumentPanel;
  36249. class MDITabbedComponentInternal;
  36250. /**
  36251. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  36252. component.
  36253. It's like a normal DocumentWindow but has some extra functionality to make sure
  36254. everything works nicely inside a MultiDocumentPanel.
  36255. @see MultiDocumentPanel
  36256. */
  36257. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  36258. {
  36259. public:
  36260. /**
  36261. */
  36262. MultiDocumentPanelWindow (const Colour& backgroundColour);
  36263. /** Destructor. */
  36264. ~MultiDocumentPanelWindow();
  36265. /** @internal */
  36266. void maximiseButtonPressed();
  36267. /** @internal */
  36268. void closeButtonPressed();
  36269. /** @internal */
  36270. void activeWindowStatusChanged();
  36271. /** @internal */
  36272. void broughtToFront();
  36273. juce_UseDebuggingNewOperator
  36274. private:
  36275. void updateOrder();
  36276. MultiDocumentPanel* getOwner() const throw();
  36277. };
  36278. /**
  36279. A component that contains a set of other components either in floating windows
  36280. or tabs.
  36281. This acts as a panel that can be used to hold a set of open document windows, with
  36282. different layout modes.
  36283. Use addDocument() and closeDocument() to add or remove components from the
  36284. panel - never use any of the Component methods to access the panel's child
  36285. components directly, as these are managed internally.
  36286. */
  36287. class JUCE_API MultiDocumentPanel : public Component,
  36288. private ComponentListener
  36289. {
  36290. public:
  36291. /** Creates an empty panel.
  36292. Use addDocument() and closeDocument() to add or remove components from the
  36293. panel - never use any of the Component methods to access the panel's child
  36294. components directly, as these are managed internally.
  36295. */
  36296. MultiDocumentPanel();
  36297. /** Destructor.
  36298. When deleted, this will call closeAllDocuments (false) to make sure all its
  36299. components are deleted. If you need to make sure all documents are saved
  36300. before closing, then you should call closeAllDocuments (true) and check that
  36301. it returns true before deleting the panel.
  36302. */
  36303. ~MultiDocumentPanel();
  36304. /** Tries to close all the documents.
  36305. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36306. be called for each open document, and any of these calls fails, this method
  36307. will stop and return false, leaving some documents still open.
  36308. If checkItsOkToCloseFirst is false, then all documents will be closed
  36309. unconditionally.
  36310. @see closeDocument
  36311. */
  36312. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  36313. /** Adds a document component to the panel.
  36314. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  36315. this will fail and return false. (If it does fail, the component passed-in will not be
  36316. deleted, even if deleteWhenRemoved was set to true).
  36317. The MultiDocumentPanel will deal with creating a window border to go around your component,
  36318. so just pass in the bare content component here, no need to give it a ResizableWindow
  36319. or DocumentWindow.
  36320. @param component the component to add
  36321. @param backgroundColour the background colour to use to fill the component's
  36322. window or tab
  36323. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  36324. or closeAllDocuments(), then it will be deleted. If false, then
  36325. the caller must handle the component's deletion
  36326. */
  36327. bool addDocument (Component* const component,
  36328. const Colour& backgroundColour,
  36329. const bool deleteWhenRemoved);
  36330. /** Closes one of the documents.
  36331. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36332. be called, and if it fails, this method will return false without closing the
  36333. document.
  36334. If checkItsOkToCloseFirst is false, then the documents will be closed
  36335. unconditionally.
  36336. The component will be deleted if the deleteWhenRemoved parameter was set to
  36337. true when it was added with addDocument.
  36338. @see addDocument, closeAllDocuments
  36339. */
  36340. bool closeDocument (Component* component,
  36341. const bool checkItsOkToCloseFirst);
  36342. /** Returns the number of open document windows.
  36343. @see getDocument
  36344. */
  36345. int getNumDocuments() const throw();
  36346. /** Returns one of the open documents.
  36347. The order of the documents in this array may change when they are added, removed
  36348. or moved around.
  36349. @see getNumDocuments
  36350. */
  36351. Component* getDocument (const int index) const throw();
  36352. /** Returns the document component that is currently focused or on top.
  36353. If currently using floating windows, then this will be the component in the currently
  36354. active window, or the top component if none are active.
  36355. If it's currently in tabbed mode, then it'll return the component in the active tab.
  36356. @see setActiveDocument
  36357. */
  36358. Component* getActiveDocument() const throw();
  36359. /** Makes one of the components active and brings it to the top.
  36360. @see getActiveDocument
  36361. */
  36362. void setActiveDocument (Component* component);
  36363. /** Callback which gets invoked when the currently-active document changes. */
  36364. virtual void activeDocumentChanged();
  36365. /** Sets a limit on how many windows can be open at once.
  36366. If this is zero or less there's no limit (the default). addDocument() will fail
  36367. if this number is exceeded.
  36368. */
  36369. void setMaximumNumDocuments (const int maximumNumDocuments);
  36370. /** Sets an option to make the document fullscreen if there's only one document open.
  36371. If set to true, then if there's only one document, it'll fill the whole of this
  36372. component without tabs or a window border. If false, then tabs or a window
  36373. will always be shown, even if there's only one document. If there's more than
  36374. one document open, then this option makes no difference.
  36375. */
  36376. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  36377. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  36378. */
  36379. bool isFullscreenWhenOneDocument() const throw();
  36380. /** The different layout modes available. */
  36381. enum LayoutMode
  36382. {
  36383. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  36384. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  36385. };
  36386. /** Changes the panel's mode.
  36387. @see LayoutMode, getLayoutMode
  36388. */
  36389. void setLayoutMode (const LayoutMode newLayoutMode);
  36390. /** Returns the current layout mode. */
  36391. LayoutMode getLayoutMode() const throw() { return mode; }
  36392. /** Sets the background colour for the whole panel.
  36393. Each document has its own background colour, but this is the one used to fill the areas
  36394. behind them.
  36395. */
  36396. void setBackgroundColour (const Colour& newBackgroundColour);
  36397. /** Returns the current background colour.
  36398. @see setBackgroundColour
  36399. */
  36400. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  36401. /** A subclass must override this to say whether its currently ok for a document
  36402. to be closed.
  36403. This method is called by closeDocument() and closeAllDocuments() to indicate that
  36404. a document should be saved if possible, ready for it to be closed.
  36405. If this method returns true, then it means the document is ok and can be closed.
  36406. If it returns false, then it means that the closeDocument() method should stop
  36407. and not close.
  36408. Normally, you'd use this method to ask the user if they want to save any changes,
  36409. then return true if the save operation went ok. If the user cancelled the save
  36410. operation you could return false here to abort the close operation.
  36411. If your component is based on the FileBasedDocument class, then you'd probably want
  36412. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  36413. FileBasedDocument::savedOk
  36414. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  36415. */
  36416. virtual bool tryToCloseDocument (Component* component) = 0;
  36417. /** Creates a new window to be used for a document.
  36418. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  36419. but you might want to override it to return a custom component.
  36420. */
  36421. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  36422. /** @internal */
  36423. void paint (Graphics& g);
  36424. /** @internal */
  36425. void resized();
  36426. /** @internal */
  36427. void componentNameChanged (Component&);
  36428. juce_UseDebuggingNewOperator
  36429. private:
  36430. LayoutMode mode;
  36431. Array <Component*> components;
  36432. TabbedComponent* tabComponent;
  36433. Colour backgroundColour;
  36434. int maximumNumDocuments, numDocsBeforeTabsUsed;
  36435. friend class MultiDocumentPanelWindow;
  36436. friend class MDITabbedComponentInternal;
  36437. Component* getContainerComp (Component* c) const;
  36438. void updateOrder();
  36439. void addWindow (Component* component);
  36440. };
  36441. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36442. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  36443. #endif
  36444. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36445. #endif
  36446. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36447. #endif
  36448. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  36449. #endif
  36450. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36451. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  36452. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36453. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36454. /**
  36455. For laying out a set of components, where the components have preferred sizes
  36456. and size limits, but where they are allowed to stretch to fill the available
  36457. space.
  36458. For example, if you have a component containing several other components, and
  36459. each one should be given a share of the total size, you could use one of these
  36460. to resize the child components when the parent component is resized. Then
  36461. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  36462. A StretchableLayoutManager operates only in one dimension, so if you have a set
  36463. of components stacked vertically on top of each other, you'd use one to manage their
  36464. heights. To build up complex arrangements of components, e.g. for applications
  36465. with multiple nested panels, you would use more than one StretchableLayoutManager.
  36466. E.g. by using two (one vertical, one horizontal), you could create a resizable
  36467. spreadsheet-style table.
  36468. E.g.
  36469. @code
  36470. class MyComp : public Component
  36471. {
  36472. StretchableLayoutManager myLayout;
  36473. MyComp()
  36474. {
  36475. myLayout.setItemLayout (0, // for item 0
  36476. 50, 100, // must be between 50 and 100 pixels in size
  36477. -0.6); // and its preferred size is 60% of the total available space
  36478. myLayout.setItemLayout (1, // for item 1
  36479. -0.2, -0.6, // size must be between 20% and 60% of the available space
  36480. 50); // and its preferred size is 50 pixels
  36481. }
  36482. void resized()
  36483. {
  36484. // make a list of two of our child components that we want to reposition
  36485. Component* comps[] = { myComp1, myComp2 };
  36486. // this will position the 2 components, one above the other, to fit
  36487. // vertically into the rectangle provided.
  36488. myLayout.layOutComponents (comps, 2,
  36489. 0, 0, getWidth(), getHeight(),
  36490. true);
  36491. }
  36492. };
  36493. @endcode
  36494. @see StretchableLayoutResizerBar
  36495. */
  36496. class JUCE_API StretchableLayoutManager
  36497. {
  36498. public:
  36499. /** Creates an empty layout.
  36500. You'll need to add some item properties to the layout before it can be used
  36501. to resize things - see setItemLayout().
  36502. */
  36503. StretchableLayoutManager();
  36504. /** Destructor. */
  36505. ~StretchableLayoutManager();
  36506. /** For a numbered item, this sets its size limits and preferred size.
  36507. @param itemIndex the index of the item to change.
  36508. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36509. indicates an absolute size in pixels. A negative number indicates a
  36510. proportion of the available space (e.g -0.5 is 50%)
  36511. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36512. indicates an absolute size in pixels. A negative number indicates a
  36513. proportion of the available space
  36514. @param preferredSize the size that this item would like to be, if there's enough room. A
  36515. positive number indicates an absolute size in pixels. A negative number
  36516. indicates a proportion of the available space
  36517. @see getItemLayout
  36518. */
  36519. void setItemLayout (const int itemIndex,
  36520. const double minimumSize,
  36521. const double maximumSize,
  36522. const double preferredSize);
  36523. /** For a numbered item, this returns its size limits and preferred size.
  36524. @param itemIndex the index of the item.
  36525. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36526. indicates an absolute size in pixels. A negative number indicates a
  36527. proportion of the available space (e.g -0.5 is 50%)
  36528. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36529. indicates an absolute size in pixels. A negative number indicates a
  36530. proportion of the available space
  36531. @param preferredSize the size that this item would like to be, if there's enough room. A
  36532. positive number indicates an absolute size in pixels. A negative number
  36533. indicates a proportion of the available space
  36534. @returns false if the item's properties hadn't been set
  36535. @see setItemLayout
  36536. */
  36537. bool getItemLayout (const int itemIndex,
  36538. double& minimumSize,
  36539. double& maximumSize,
  36540. double& preferredSize) const;
  36541. /** Clears all the properties that have been set with setItemLayout() and resets
  36542. this object to its initial state.
  36543. */
  36544. void clearAllItems();
  36545. /** Takes a set of components that correspond to the layout's items, and positions
  36546. them to fill a space.
  36547. This will try to give each item its preferred size, whether that's a relative size
  36548. or an absolute one.
  36549. @param components an array of components that correspond to each of the
  36550. numbered items that the StretchableLayoutManager object
  36551. has been told about with setItemLayout()
  36552. @param numComponents the number of components in the array that is passed-in. This
  36553. should be the same as the number of items this object has been
  36554. told about.
  36555. @param x the left of the rectangle in which the components should
  36556. be laid out
  36557. @param y the top of the rectangle in which the components should
  36558. be laid out
  36559. @param width the width of the rectangle in which the components should
  36560. be laid out
  36561. @param height the height of the rectangle in which the components should
  36562. be laid out
  36563. @param vertically if true, the components will be positioned in a vertical stack,
  36564. so that they fill the height of the rectangle. If false, they
  36565. will be placed side-by-side in a horizontal line, filling the
  36566. available width
  36567. @param resizeOtherDimension if true, this means that the components will have their
  36568. other dimension resized to fit the space - i.e. if the 'vertically'
  36569. parameter is true, their x-positions and widths are adjusted to fit
  36570. the x and width parameters; if 'vertically' is false, their y-positions
  36571. and heights are adjusted to fit the y and height parameters.
  36572. */
  36573. void layOutComponents (Component** const components,
  36574. int numComponents,
  36575. int x, int y, int width, int height,
  36576. const bool vertically,
  36577. const bool resizeOtherDimension);
  36578. /** Returns the current position of one of the items.
  36579. This is only a valid call after layOutComponents() has been called, as it
  36580. returns the last position that this item was placed at. If the layout was
  36581. vertical, the value returned will be the y position of the top of the item,
  36582. relative to the top of the rectangle in which the items were placed (so for
  36583. example, item 0 will always have position of 0, even in the rectangle passed
  36584. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  36585. the position returned is the item's left-hand position, again relative to the
  36586. x position of the rectangle used.
  36587. @see getItemCurrentSize, setItemPosition
  36588. */
  36589. int getItemCurrentPosition (const int itemIndex) const;
  36590. /** Returns the current size of one of the items.
  36591. This is only meaningful after layOutComponents() has been called, as it
  36592. returns the last size that this item was given. If the layout was done
  36593. vertically, it'll return the item's height in pixels; if it was horizontal,
  36594. it'll return its width.
  36595. @see getItemCurrentRelativeSize
  36596. */
  36597. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36598. /** Returns the current size of one of the items.
  36599. This is only meaningful after layOutComponents() has been called, as it
  36600. returns the last size that this item was given. If the layout was done
  36601. vertically, it'll return a negative value representing the item's height relative
  36602. to the last size used for laying the components out; if the layout was done
  36603. horizontally it'll be the proportion of its width.
  36604. @see getItemCurrentAbsoluteSize
  36605. */
  36606. double getItemCurrentRelativeSize (const int itemIndex) const;
  36607. /** Moves one of the items, shifting along any other items as necessary in
  36608. order to get it to the desired position.
  36609. Calling this method will also update the preferred sizes of the items it
  36610. shuffles along, so that they reflect their new positions.
  36611. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36612. about when it's dragged).
  36613. @param itemIndex the item to move
  36614. @param newPosition the absolute position that you'd like this item to move
  36615. to. The item might not be able to always reach exactly this position,
  36616. because other items may have minimum sizes that constrain how
  36617. far it can go
  36618. */
  36619. void setItemPosition (const int itemIndex,
  36620. int newPosition);
  36621. juce_UseDebuggingNewOperator
  36622. private:
  36623. struct ItemLayoutProperties
  36624. {
  36625. int itemIndex;
  36626. int currentSize;
  36627. double minSize, maxSize, preferredSize;
  36628. };
  36629. OwnedArray <ItemLayoutProperties> items;
  36630. int totalSize;
  36631. static int sizeToRealSize (double size, int totalSpace);
  36632. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36633. void setTotalSize (const int newTotalSize);
  36634. int fitComponentsIntoSpace (const int startIndex,
  36635. const int endIndex,
  36636. const int availableSpace,
  36637. int startPos);
  36638. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36639. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36640. void updatePrefSizesToMatchCurrentPositions();
  36641. StretchableLayoutManager (const StretchableLayoutManager&);
  36642. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36643. };
  36644. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36645. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36646. #endif
  36647. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36648. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36649. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36650. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36651. /**
  36652. A component that acts as one of the vertical or horizontal bars you see being
  36653. used to resize panels in a window.
  36654. One of these acts with a StretchableLayoutManager to resize the other components.
  36655. @see StretchableLayoutManager
  36656. */
  36657. class JUCE_API StretchableLayoutResizerBar : public Component
  36658. {
  36659. public:
  36660. /** Creates a resizer bar for use on a specified layout.
  36661. @param layoutToUse the layout that will be affected when this bar
  36662. is dragged
  36663. @param itemIndexInLayout the item index in the layout that corresponds to
  36664. this bar component. You'll need to set up the item
  36665. properties in a suitable way for a divider bar, e.g.
  36666. for an 8-pixel wide bar which, you could call
  36667. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36668. @param isBarVertical true if it's an upright bar that you drag left and
  36669. right; false for a horizontal one that you drag up and
  36670. down
  36671. */
  36672. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36673. const int itemIndexInLayout,
  36674. const bool isBarVertical);
  36675. /** Destructor. */
  36676. ~StretchableLayoutResizerBar();
  36677. /** This is called when the bar is dragged.
  36678. This method must update the positions of any components whose position is
  36679. determined by the StretchableLayoutManager, because they might have just
  36680. moved.
  36681. The default implementation calls the resized() method of this component's
  36682. parent component, because that's often where you're likely to apply the
  36683. layout, but it can be overridden for more specific needs.
  36684. */
  36685. virtual void hasBeenMoved();
  36686. /** @internal */
  36687. void paint (Graphics& g);
  36688. /** @internal */
  36689. void mouseDown (const MouseEvent& e);
  36690. /** @internal */
  36691. void mouseDrag (const MouseEvent& e);
  36692. juce_UseDebuggingNewOperator
  36693. private:
  36694. StretchableLayoutManager* layout;
  36695. int itemIndex, mouseDownPos;
  36696. bool isVertical;
  36697. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36698. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36699. };
  36700. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36701. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36702. #endif
  36703. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36704. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36705. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36706. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36707. /**
  36708. A utility class for fitting a set of objects whose sizes can vary between
  36709. a minimum and maximum size, into a space.
  36710. This is a trickier algorithm than it would first seem, so I've put it in this
  36711. class to allow it to be shared by various bits of code.
  36712. To use it, create one of these objects, call addItem() to add the list of items
  36713. you need, then call resizeToFit(), which will change all their sizes. You can
  36714. then retrieve the new sizes with getItemSize() and getNumItems().
  36715. It's currently used by the TableHeaderComponent for stretching out the table
  36716. headings to fill the table's width.
  36717. */
  36718. class StretchableObjectResizer
  36719. {
  36720. public:
  36721. /** Creates an empty object resizer. */
  36722. StretchableObjectResizer();
  36723. /** Destructor. */
  36724. ~StretchableObjectResizer();
  36725. /** Adds an item to the list.
  36726. The order parameter lets you specify groups of items that are resized first when some
  36727. space needs to be found. Those items with an order of 0 will be the first ones to be
  36728. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36729. will then try resizing the items with an order of 1, then 2, and so on.
  36730. */
  36731. void addItem (const double currentSize,
  36732. const double minSize,
  36733. const double maxSize,
  36734. const int order = 0);
  36735. /** Resizes all the items to fit this amount of space.
  36736. This will attempt to fit them in without exceeding each item's miniumum and
  36737. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36738. further, the final size may be greater or less than the size passed in.
  36739. After calling this method, you can retrieve the new sizes with the getItemSize()
  36740. method.
  36741. */
  36742. void resizeToFit (const double targetSize);
  36743. /** Returns the number of items that have been added. */
  36744. int getNumItems() const throw() { return items.size(); }
  36745. /** Returns the size of one of the items. */
  36746. double getItemSize (const int index) const throw();
  36747. juce_UseDebuggingNewOperator
  36748. private:
  36749. struct Item
  36750. {
  36751. double size;
  36752. double minSize;
  36753. double maxSize;
  36754. int order;
  36755. };
  36756. OwnedArray <Item> items;
  36757. StretchableObjectResizer (const StretchableObjectResizer&);
  36758. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36759. };
  36760. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36761. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36762. #endif
  36763. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36764. #endif
  36765. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36766. #endif
  36767. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36768. #endif
  36769. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36770. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36771. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36772. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36773. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  36774. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36775. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36776. /********* Start of inlined file: juce_FileFilter.h *********/
  36777. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36778. #define __JUCE_FILEFILTER_JUCEHEADER__
  36779. /**
  36780. Interface for deciding which files are suitable for something.
  36781. For example, this is used by DirectoryContentsList to select which files
  36782. go into the list.
  36783. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36784. */
  36785. class JUCE_API FileFilter
  36786. {
  36787. public:
  36788. /** Creates a filter with the given description.
  36789. The description can be returned later with the getDescription() method.
  36790. */
  36791. FileFilter (const String& filterDescription);
  36792. /** Destructor. */
  36793. virtual ~FileFilter();
  36794. /** Returns the description that the filter was created with. */
  36795. const String& getDescription() const throw();
  36796. /** Should return true if this file is suitable for inclusion in whatever context
  36797. the object is being used.
  36798. */
  36799. virtual bool isFileSuitable (const File& file) const = 0;
  36800. /** Should return true if this directory is suitable for inclusion in whatever context
  36801. the object is being used.
  36802. */
  36803. virtual bool isDirectorySuitable (const File& file) const = 0;
  36804. protected:
  36805. String description;
  36806. };
  36807. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36808. /********* End of inlined file: juce_FileFilter.h *********/
  36809. /**
  36810. A class to asynchronously scan for details about the files in a directory.
  36811. This keeps a list of files and some information about them, using a background
  36812. thread to scan for more files. As files are found, it broadcasts change messages
  36813. to tell any listeners.
  36814. @see FileListComponent, FileBrowserComponent
  36815. */
  36816. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36817. public TimeSliceClient
  36818. {
  36819. public:
  36820. /** Creates a directory list.
  36821. To set the directory it should point to, use setDirectory(), which will
  36822. also start it scanning for files on the background thread.
  36823. When the background thread finds and adds new files to this list, the
  36824. ChangeBroadcaster class will send a change message, so you can register
  36825. listeners and update them when the list changes.
  36826. @param fileFilter an optional filter to select which files are
  36827. included in the list. If this is 0, then all files
  36828. and directories are included. Make sure that the
  36829. filter doesn't get deleted during the lifetime of this
  36830. object
  36831. @param threadToUse a thread object that this list can use
  36832. to scan for files as a background task. Make sure
  36833. that the thread you give it has been started, or you
  36834. won't get any files!
  36835. */
  36836. DirectoryContentsList (const FileFilter* const fileFilter,
  36837. TimeSliceThread& threadToUse);
  36838. /** Destructor. */
  36839. ~DirectoryContentsList();
  36840. /** Sets the directory to look in for files.
  36841. If the directory that's passed in is different to the current one, this will
  36842. also start the background thread scanning it for files.
  36843. */
  36844. void setDirectory (const File& directory,
  36845. const bool includeDirectories,
  36846. const bool includeFiles);
  36847. /** Returns the directory that's currently being used. */
  36848. const File& getDirectory() const throw();
  36849. /** Clears the list, and stops the thread scanning for files. */
  36850. void clear();
  36851. /** Clears the list and restarts scanning the directory for files. */
  36852. void refresh();
  36853. /** True if the background thread hasn't yet finished scanning for files. */
  36854. bool isStillLoading() const;
  36855. /** Tells the list whether or not to ignore hidden files.
  36856. By default these are ignored.
  36857. */
  36858. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  36859. /** Contains cached information about one of the files in a DirectoryContentsList.
  36860. */
  36861. struct FileInfo
  36862. {
  36863. /** The filename.
  36864. This isn't a full pathname, it's just the last part of the path, same as you'd
  36865. get from File::getFileName().
  36866. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36867. */
  36868. String filename;
  36869. /** File size in bytes. */
  36870. int64 fileSize;
  36871. /** File modification time.
  36872. As supplied by File::getLastModificationTime().
  36873. */
  36874. Time modificationTime;
  36875. /** File creation time.
  36876. As supplied by File::getCreationTime().
  36877. */
  36878. Time creationTime;
  36879. /** True if the file is a directory. */
  36880. bool isDirectory;
  36881. /** True if the file is read-only. */
  36882. bool isReadOnly;
  36883. };
  36884. /** Returns the number of files currently available in the list.
  36885. The info about one of these files can be retrieved with getFileInfo() or
  36886. getFile().
  36887. Obviously as the background thread runs and scans the directory for files, this
  36888. number will change.
  36889. @see getFileInfo, getFile
  36890. */
  36891. int getNumFiles() const;
  36892. /** Returns the cached information about one of the files in the list.
  36893. If the index is in-range, this will return true and will copy the file's details
  36894. to the structure that is passed-in.
  36895. If it returns false, then the index wasn't in range, and the structure won't
  36896. be affected.
  36897. @see getNumFiles, getFile
  36898. */
  36899. bool getFileInfo (const int index,
  36900. FileInfo& resultInfo) const;
  36901. /** Returns one of the files in the list.
  36902. @param index should be less than getNumFiles(). If this is out-of-range, the
  36903. return value will be File::nonexistent
  36904. @see getNumFiles, getFileInfo
  36905. */
  36906. const File getFile (const int index) const;
  36907. /** Returns the file filter being used.
  36908. The filter is specified in the constructor.
  36909. */
  36910. const FileFilter* getFilter() const throw() { return fileFilter; }
  36911. /** @internal */
  36912. bool useTimeSlice();
  36913. /** @internal */
  36914. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  36915. /** @internal */
  36916. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  36917. const DirectoryContentsList::FileInfo* const second) throw();
  36918. juce_UseDebuggingNewOperator
  36919. private:
  36920. File root;
  36921. const FileFilter* fileFilter;
  36922. TimeSliceThread& thread;
  36923. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  36924. CriticalSection fileListLock;
  36925. OwnedArray <FileInfo> files;
  36926. void* volatile fileFindHandle;
  36927. bool volatile shouldStop;
  36928. void changed();
  36929. bool checkNextFile (bool& hasChanged);
  36930. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  36931. const int64 fileSize, const Time& modTime,
  36932. const Time& creationTime, const bool isReadOnly);
  36933. DirectoryContentsList (const DirectoryContentsList&);
  36934. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  36935. };
  36936. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36937. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  36938. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  36939. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36940. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36941. /**
  36942. A listener for user selection events in a file browser.
  36943. This is used by a FileBrowserComponent or FileListComponent.
  36944. */
  36945. class JUCE_API FileBrowserListener
  36946. {
  36947. public:
  36948. /** Destructor. */
  36949. virtual ~FileBrowserListener();
  36950. /** Callback when the user selects a different file in the browser. */
  36951. virtual void selectionChanged() = 0;
  36952. /** Callback when the user clicks on a file in the browser. */
  36953. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36954. /** Callback when the user double-clicks on a file in the browser. */
  36955. virtual void fileDoubleClicked (const File& file) = 0;
  36956. };
  36957. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36958. /********* End of inlined file: juce_FileBrowserListener.h *********/
  36959. /**
  36960. A base class for components that display a list of the files in a directory.
  36961. @see DirectoryContentsList
  36962. */
  36963. class JUCE_API DirectoryContentsDisplayComponent
  36964. {
  36965. public:
  36966. /**
  36967. */
  36968. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36969. /** Destructor. */
  36970. virtual ~DirectoryContentsDisplayComponent();
  36971. /** Returns the file that the user has currently selected.
  36972. Returns File::nonexistent if none is selected.
  36973. */
  36974. virtual const File getSelectedFile() const = 0;
  36975. /** Scrolls this view to the top. */
  36976. virtual void scrollToTop() = 0;
  36977. /** Adds a listener to be told when files are selected or clicked.
  36978. @see removeListener
  36979. */
  36980. void addListener (FileBrowserListener* const listener) throw();
  36981. /** Removes a listener.
  36982. @see addListener
  36983. */
  36984. void removeListener (FileBrowserListener* const listener) throw();
  36985. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36986. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36987. methods.
  36988. Note that you can also use the constants from TextEditor::ColourIds to change the
  36989. colour of the text editor that is opened when a label is editable.
  36990. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36991. */
  36992. enum ColourIds
  36993. {
  36994. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36995. textColourId = 0x1000541, /**< The colour for the text. */
  36996. };
  36997. /** @internal */
  36998. void sendSelectionChangeMessage();
  36999. /** @internal */
  37000. void sendDoubleClickMessage (const File& file);
  37001. /** @internal */
  37002. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  37003. juce_UseDebuggingNewOperator
  37004. protected:
  37005. DirectoryContentsList& fileList;
  37006. SortedSet <void*> listeners;
  37007. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  37008. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  37009. };
  37010. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37011. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37012. #endif
  37013. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37014. #endif
  37015. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37016. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  37017. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37018. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37019. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  37020. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37021. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37022. /**
  37023. Base class for components that live inside a file chooser dialog box and
  37024. show previews of the files that get selected.
  37025. One of these allows special extra information to be displayed for files
  37026. in a dialog box as the user selects them. Each time the current file or
  37027. directory is changed, the selectedFileChanged() method will be called
  37028. to allow it to update itself appropriately.
  37029. @see FileChooser, ImagePreviewComponent
  37030. */
  37031. class JUCE_API FilePreviewComponent : public Component
  37032. {
  37033. public:
  37034. /** Creates a FilePreviewComponent. */
  37035. FilePreviewComponent();
  37036. /** Destructor. */
  37037. ~FilePreviewComponent();
  37038. /** Called to indicate that the user's currently selected file has changed.
  37039. @param newSelectedFile the newly selected file or directory, which may be
  37040. File::nonexistent if none is selected.
  37041. */
  37042. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  37043. juce_UseDebuggingNewOperator
  37044. private:
  37045. FilePreviewComponent (const FilePreviewComponent&);
  37046. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  37047. };
  37048. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37049. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  37050. /**
  37051. A component for browsing and selecting a file or directory to open or save.
  37052. This contains a FileListComponent and adds various boxes and controls for
  37053. navigating and selecting a file. It can work in different modes so that it can
  37054. be used for loading or saving a file, or for choosing a directory.
  37055. @see FileChooserDialogBox, FileChooser, FileListComponent
  37056. */
  37057. class JUCE_API FileBrowserComponent : public Component,
  37058. public ChangeBroadcaster,
  37059. private FileBrowserListener,
  37060. private TextEditorListener,
  37061. private ButtonListener,
  37062. private ComboBoxListener
  37063. {
  37064. public:
  37065. /** Various modes that the browser can be used in.
  37066. One of these is passed into the constructor.
  37067. */
  37068. enum FileChooserMode
  37069. {
  37070. loadFileMode, /**< the component should allow the user to choose an existing
  37071. file with the intention of opening it. */
  37072. saveFileMode, /**< the component should allow the user to specify the name of
  37073. a file that will be used to save something. */
  37074. chooseDirectoryMode /**< the component should allow the user to select an existing
  37075. directory. */
  37076. };
  37077. /** Creates a FileBrowserComponent.
  37078. @param browserMode The intended purpose for the browser - see the
  37079. FileChooserMode enum for the various options
  37080. @param initialFileOrDirectory The file or directory that should be selected when
  37081. the component begins. If this is File::nonexistent,
  37082. a default directory will be chosen.
  37083. @param fileFilter an optional filter to use to determine which files
  37084. are shown. If this is 0 then all files are displayed. Note
  37085. that a pointer is kept internally to this object, so
  37086. make sure that it is not deleted before the browser object
  37087. is deleted.
  37088. @param previewComp an optional preview component that will be used to
  37089. show previews of files that the user selects
  37090. @param useTreeView if this is false, the files are shown in a list; if true,
  37091. they are shown in a treeview
  37092. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  37093. text into the filename box.
  37094. */
  37095. FileBrowserComponent (FileChooserMode browserMode,
  37096. const File& initialFileOrDirectory,
  37097. const FileFilter* fileFilter,
  37098. FilePreviewComponent* previewComp,
  37099. const bool useTreeView = false,
  37100. const bool filenameTextBoxIsReadOnly = false);
  37101. /** Destructor. */
  37102. ~FileBrowserComponent();
  37103. /**
  37104. */
  37105. const File getCurrentFile() const throw();
  37106. /** Returns true if the current file is usable.
  37107. This can be used to decide whether the user can press "ok" for the
  37108. current file. What it does depends on the mode, so for example in an "open"
  37109. mode, the current file is only valid if one has been selected and if the file
  37110. exists. In a "save" mode, a non-existent file would also be valid.
  37111. */
  37112. bool currentFileIsValid() const;
  37113. /** Returns the directory whose contents are currently being shown in the listbox. */
  37114. const File getRoot() const;
  37115. /** Changes the directory that's being shown in the listbox. */
  37116. void setRoot (const File& newRootDirectory);
  37117. /** Equivalent to pressing the "up" button to browse the parent directory. */
  37118. void goUp();
  37119. /** Refreshes the directory that's currently being listed. */
  37120. void refresh();
  37121. /** Returns the browser's current mode. */
  37122. FileChooserMode getMode() const throw() { return mode; }
  37123. /** Returns a verb to describe what should happen when the file is accepted.
  37124. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  37125. mode, it'll be "Save", etc.
  37126. */
  37127. virtual const String getActionVerb() const;
  37128. /** Adds a listener to be told when the user selects and clicks on files.
  37129. @see removeListener
  37130. */
  37131. void addListener (FileBrowserListener* const listener) throw();
  37132. /** Removes a listener.
  37133. @see addListener
  37134. */
  37135. void removeListener (FileBrowserListener* const listener) throw();
  37136. /** @internal */
  37137. void resized();
  37138. /** @internal */
  37139. void buttonClicked (Button* b);
  37140. /** @internal */
  37141. void comboBoxChanged (ComboBox*);
  37142. /** @internal */
  37143. void textEditorTextChanged (TextEditor& editor);
  37144. /** @internal */
  37145. void textEditorReturnKeyPressed (TextEditor& editor);
  37146. /** @internal */
  37147. void textEditorEscapeKeyPressed (TextEditor& editor);
  37148. /** @internal */
  37149. void textEditorFocusLost (TextEditor& editor);
  37150. /** @internal */
  37151. void selectionChanged();
  37152. /** @internal */
  37153. void fileClicked (const File& f, const MouseEvent& e);
  37154. /** @internal */
  37155. void fileDoubleClicked (const File& f);
  37156. /** @internal */
  37157. FilePreviewComponent* getPreviewComponent() const throw();
  37158. juce_UseDebuggingNewOperator
  37159. protected:
  37160. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  37161. private:
  37162. DirectoryContentsList* fileList;
  37163. FileFilter* directoriesOnlyFilter;
  37164. FileChooserMode mode;
  37165. File currentRoot;
  37166. SortedSet <void*> listeners;
  37167. DirectoryContentsDisplayComponent* fileListComponent;
  37168. FilePreviewComponent* previewComp;
  37169. ComboBox* currentPathBox;
  37170. TextEditor* filenameBox;
  37171. Button* goUpButton;
  37172. TimeSliceThread thread;
  37173. void sendListenerChangeMessage();
  37174. FileBrowserComponent (const FileBrowserComponent&);
  37175. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  37176. };
  37177. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37178. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  37179. #endif
  37180. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37181. #endif
  37182. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37183. /********* Start of inlined file: juce_FileChooser.h *********/
  37184. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37185. #define __JUCE_FILECHOOSER_JUCEHEADER__
  37186. /**
  37187. Creates a dialog box to choose a file or directory to load or save.
  37188. To use a FileChooser:
  37189. - create one (as a local stack variable is the neatest way)
  37190. - call one of its browseFor.. methods
  37191. - if this returns true, the user has selected a file, so you can retrieve it
  37192. with the getResult() method.
  37193. e.g. @code
  37194. void loadMooseFile()
  37195. {
  37196. FileChooser myChooser ("Please select the moose you want to load...",
  37197. File::getSpecialLocation (File::userHomeDirectory),
  37198. "*.moose");
  37199. if (myChooser.browseForFileToOpen())
  37200. {
  37201. File mooseFile (myChooser.getResult());
  37202. loadMoose (mooseFile);
  37203. }
  37204. }
  37205. @endcode
  37206. */
  37207. class JUCE_API FileChooser
  37208. {
  37209. public:
  37210. /** Creates a FileChooser.
  37211. After creating one of these, use one of the browseFor... methods to display it.
  37212. @param dialogBoxTitle a text string to display in the dialog box to
  37213. tell the user what's going on
  37214. @param initialFileOrDirectory the file or directory that should be selected when
  37215. the dialog box opens. If this parameter is set to
  37216. File::nonexistent, a sensible default directory
  37217. will be used instead.
  37218. @param filePatternsAllowed a set of file patterns to specify which files can be
  37219. selected - each pattern should be separated by a
  37220. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  37221. empty string means that all files are allowed
  37222. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  37223. possible; if false, then a Juce-based browser dialog
  37224. box will always be used
  37225. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  37226. */
  37227. FileChooser (const String& dialogBoxTitle,
  37228. const File& initialFileOrDirectory = File::nonexistent,
  37229. const String& filePatternsAllowed = String::empty,
  37230. const bool useOSNativeDialogBox = true);
  37231. /** Destructor. */
  37232. ~FileChooser();
  37233. /** Shows a dialog box to choose a file to open.
  37234. This will display the dialog box modally, using an "open file" mode, so that
  37235. it won't allow non-existent files or directories to be chosen.
  37236. @param previewComponent an optional component to display inside the dialog
  37237. box to show special info about the files that the user
  37238. is browsing. The component will not be deleted by this
  37239. object, so the caller must take care of it.
  37240. @returns true if the user selected a file, in which case, use the getResult()
  37241. method to find out what it was. Returns false if they cancelled instead.
  37242. @see browseForFileToSave, browseForDirectory
  37243. */
  37244. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  37245. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  37246. The files that are returned can be obtained by calling getResults(). See
  37247. browseForFileToOpen() for more info about the behaviour of this method.
  37248. */
  37249. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  37250. /** Shows a dialog box to choose a file to save.
  37251. This will display the dialog box modally, using an "save file" mode, so it
  37252. will allow non-existent files to be chosen, but not directories.
  37253. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  37254. the user if they're sure they want to overwrite a file that already
  37255. exists
  37256. @returns true if the user chose a file and pressed 'ok', in which case, use
  37257. the getResult() method to find out what the file was. Returns false
  37258. if they cancelled instead.
  37259. @see browseForFileToOpen, browseForDirectory
  37260. */
  37261. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  37262. /** Shows a dialog box to choose a directory.
  37263. This will display the dialog box modally, using an "open directory" mode, so it
  37264. will only allow directories to be returned, not files.
  37265. @returns true if the user chose a directory and pressed 'ok', in which case, use
  37266. the getResult() method to find out what they chose. Returns false
  37267. if they cancelled instead.
  37268. @see browseForFileToOpen, browseForFileToSave
  37269. */
  37270. bool browseForDirectory();
  37271. /** Returns the last file that was chosen by one of the browseFor methods.
  37272. After calling the appropriate browseFor... method, this method lets you
  37273. find out what file or directory they chose.
  37274. Note that the file returned is only valid if the browse method returned true (i.e.
  37275. if the user pressed 'ok' rather than cancelling).
  37276. If you're using a multiple-file select, then use the getResults() method instead,
  37277. to obtain the list of all files chosen.
  37278. @see getResults
  37279. */
  37280. const File getResult() const;
  37281. /** Returns a list of all the files that were chosen during the last call to a
  37282. browse method.
  37283. This array may be empty if no files were chosen, or can contain multiple entries
  37284. if multiple files were chosen.
  37285. @see getResult
  37286. */
  37287. const OwnedArray <File>& getResults() const;
  37288. juce_UseDebuggingNewOperator
  37289. private:
  37290. String title, filters;
  37291. File startingFile;
  37292. OwnedArray <File> results;
  37293. bool useNativeDialogBox;
  37294. bool showDialog (const bool isDirectory,
  37295. const bool isSave,
  37296. const bool warnAboutOverwritingExistingFiles,
  37297. const bool selectMultipleFiles,
  37298. FilePreviewComponent* const previewComponent);
  37299. static void showPlatformDialog (OwnedArray<File>& results,
  37300. const String& title,
  37301. const File& file,
  37302. const String& filters,
  37303. bool isDirectory,
  37304. bool isSave,
  37305. bool warnAboutOverwritingExistingFiles,
  37306. bool selectMultipleFiles,
  37307. FilePreviewComponent* previewComponent);
  37308. };
  37309. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  37310. /********* End of inlined file: juce_FileChooser.h *********/
  37311. #endif
  37312. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37313. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  37314. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37315. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37316. /**
  37317. A file open/save dialog box.
  37318. This is a Juce-based file dialog box; to use a native file chooser, see the
  37319. FileChooser class.
  37320. To use one of these, create it and call its show() method. e.g.
  37321. @code
  37322. {
  37323. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  37324. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37325. File::nonexistent,
  37326. &wildcardFilter,
  37327. 0);
  37328. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  37329. T("Please choose some kind of file that you want to open..."),
  37330. browser,
  37331. getLookAndFeel().alertWindowBackground);
  37332. if (dialogBox.show())
  37333. {
  37334. File selectedFile = browser.getCurrentFile();
  37335. ...
  37336. }
  37337. }
  37338. @endcode
  37339. @see FileChooser
  37340. */
  37341. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37342. public ButtonListener,
  37343. public FileBrowserListener
  37344. {
  37345. public:
  37346. /** Creates a file chooser box.
  37347. @param title the main title to show at the top of the box
  37348. @param instructions an optional longer piece of text to show below the title in
  37349. a smaller font, describing in more detail what's required.
  37350. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37351. box. Make sure you delete this after (but not before!) the
  37352. dialog box has been deleted.
  37353. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37354. if they try to select a file that already exists. (This
  37355. flag is only used when saving files)
  37356. @param backgroundColour the background colour for the top level window
  37357. @see FileBrowserComponent, FilePreviewComponent
  37358. */
  37359. FileChooserDialogBox (const String& title,
  37360. const String& instructions,
  37361. FileBrowserComponent& browserComponent,
  37362. const bool warnAboutOverwritingExistingFiles,
  37363. const Colour& backgroundColour);
  37364. /** Destructor. */
  37365. ~FileChooserDialogBox();
  37366. /** Displays and runs the dialog box modally.
  37367. This will show the box with the specified size, returning true if the user
  37368. pressed 'ok', or false if they cancelled.
  37369. Leave the width or height as 0 to use the default size
  37370. */
  37371. bool show (int width = 0,int height = 0);
  37372. /** @internal */
  37373. void buttonClicked (Button* button);
  37374. /** @internal */
  37375. void closeButtonPressed();
  37376. /** @internal */
  37377. void selectionChanged();
  37378. /** @internal */
  37379. void fileClicked (const File& file, const MouseEvent& e);
  37380. /** @internal */
  37381. void fileDoubleClicked (const File& file);
  37382. juce_UseDebuggingNewOperator
  37383. private:
  37384. class ContentComponent : public Component
  37385. {
  37386. public:
  37387. ContentComponent();
  37388. ~ContentComponent();
  37389. void paint (Graphics& g);
  37390. void resized();
  37391. String instructions;
  37392. GlyphArrangement text;
  37393. FileBrowserComponent* chooserComponent;
  37394. FilePreviewComponent* previewComponent;
  37395. TextButton* okButton;
  37396. TextButton* cancelButton;
  37397. };
  37398. ContentComponent* content;
  37399. const bool warnAboutOverwritingExistingFiles;
  37400. FileChooserDialogBox (const FileChooserDialogBox&);
  37401. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37402. };
  37403. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37404. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  37405. #endif
  37406. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37407. #endif
  37408. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37409. /********* Start of inlined file: juce_FileListComponent.h *********/
  37410. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37411. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37412. /**
  37413. A component that displays the files in a directory as a listbox.
  37414. This implements the DirectoryContentsDisplayComponent base class so that
  37415. it can be used in a FileBrowserComponent.
  37416. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37417. class and the FileBrowserListener class.
  37418. @see DirectoryContentsList, FileTreeComponent
  37419. */
  37420. class JUCE_API FileListComponent : public ListBox,
  37421. public DirectoryContentsDisplayComponent,
  37422. private ListBoxModel,
  37423. private ChangeListener
  37424. {
  37425. public:
  37426. /** Creates a listbox to show the contents of a specified directory.
  37427. */
  37428. FileListComponent (DirectoryContentsList& listToShow);
  37429. /** Destructor. */
  37430. ~FileListComponent();
  37431. /** Returns the file that the user has currently selected.
  37432. Returns File::nonexistent if none is selected.
  37433. */
  37434. const File getSelectedFile() const;
  37435. /** Scrolls to the top of the list. */
  37436. void scrollToTop();
  37437. /** @internal */
  37438. void changeListenerCallback (void*);
  37439. /** @internal */
  37440. int getNumRows();
  37441. /** @internal */
  37442. void paintListBoxItem (int, Graphics&, int, int, bool);
  37443. /** @internal */
  37444. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37445. /** @internal */
  37446. void selectedRowsChanged (int lastRowSelected);
  37447. /** @internal */
  37448. void deleteKeyPressed (int currentSelectedRow);
  37449. /** @internal */
  37450. void returnKeyPressed (int currentSelectedRow);
  37451. juce_UseDebuggingNewOperator
  37452. private:
  37453. FileListComponent (const FileListComponent&);
  37454. const FileListComponent& operator= (const FileListComponent&);
  37455. File lastDirectory;
  37456. };
  37457. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37458. /********* End of inlined file: juce_FileListComponent.h *********/
  37459. #endif
  37460. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37461. /********* Start of inlined file: juce_FilenameComponent.h *********/
  37462. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37463. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37464. class FilenameComponent;
  37465. /**
  37466. Listens for events happening to a FilenameComponent.
  37467. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  37468. register one of these objects for event callbacks when the filename is changed.
  37469. @See FilenameComponent
  37470. */
  37471. class JUCE_API FilenameComponentListener
  37472. {
  37473. public:
  37474. /** Destructor. */
  37475. virtual ~FilenameComponentListener() {}
  37476. /** This method is called after the FilenameComponent's file has been changed. */
  37477. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37478. };
  37479. /**
  37480. Shows a filename as an editable text box, with a 'browse' button and a
  37481. drop-down list for recently selected files.
  37482. A handy component for dialogue boxes where you want the user to be able to
  37483. select a file or directory.
  37484. Attach an FilenameComponentListener using the addListener() method, and it will
  37485. get called each time the user changes the filename, either by browsing for a file
  37486. and clicking 'ok', or by typing a new filename into the box and pressing return.
  37487. @see FileChooser, ComboBox
  37488. */
  37489. class JUCE_API FilenameComponent : public Component,
  37490. public SettableTooltipClient,
  37491. public FileDragAndDropTarget,
  37492. private AsyncUpdater,
  37493. private ButtonListener,
  37494. private ComboBoxListener
  37495. {
  37496. public:
  37497. /** Creates a FilenameComponent.
  37498. @param name the name for this component.
  37499. @param currentFile the file to initially show in the box
  37500. @param canEditFilename if true, the user can manually edit the filename; if false,
  37501. they can only change it by browsing for a new file
  37502. @param isDirectory if true, the file will be treated as a directory, and
  37503. an appropriate directory browser used
  37504. @param isForSaving if true, the file browser will allow non-existent files to
  37505. be picked, as the file is assumed to be used for saving rather
  37506. than loading
  37507. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37508. If an empty string is passed in, then the pattern is assumed to be "*"
  37509. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37510. to any filenames that are entered or chosen
  37511. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37512. will only appear if the initial file isn't valid)
  37513. */
  37514. FilenameComponent (const String& name,
  37515. const File& currentFile,
  37516. const bool canEditFilename,
  37517. const bool isDirectory,
  37518. const bool isForSaving,
  37519. const String& fileBrowserWildcard,
  37520. const String& enforcedSuffix,
  37521. const String& textWhenNothingSelected);
  37522. /** Destructor. */
  37523. ~FilenameComponent();
  37524. /** Returns the currently displayed filename. */
  37525. const File getCurrentFile() const;
  37526. /** Changes the current filename.
  37527. If addToRecentlyUsedList is true, the filename will also be added to the
  37528. drop-down list of recent files.
  37529. If sendChangeNotification is false, then the listeners won't be told of the
  37530. change.
  37531. */
  37532. void setCurrentFile (File newFile,
  37533. const bool addToRecentlyUsedList,
  37534. const bool sendChangeNotification = true);
  37535. /** Changes whether the use can type into the filename box.
  37536. */
  37537. void setFilenameIsEditable (const bool shouldBeEditable);
  37538. /** Sets a file or directory to be the default starting point for the browser to show.
  37539. This is only used if the current file hasn't been set.
  37540. */
  37541. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37542. /** Returns all the entries on the recent files list.
  37543. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37544. state of this list.
  37545. @see setRecentlyUsedFilenames
  37546. */
  37547. const StringArray getRecentlyUsedFilenames() const;
  37548. /** Sets all the entries on the recent files list.
  37549. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37550. state of this list.
  37551. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37552. */
  37553. void setRecentlyUsedFilenames (const StringArray& filenames);
  37554. /** Adds an entry to the recently-used files dropdown list.
  37555. If the file is already in the list, it will be moved to the top. A limit
  37556. is also placed on the number of items that are kept in the list.
  37557. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37558. */
  37559. void addRecentlyUsedFile (const File& file);
  37560. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37561. */
  37562. void setMaxNumberOfRecentFiles (const int newMaximum);
  37563. /** Changes the text shown on the 'browse' button.
  37564. By default this button just says "..." but you can change it. The button itself
  37565. can be changed using the look-and-feel classes, so it might not actually have any
  37566. text on it.
  37567. */
  37568. void setBrowseButtonText (const String& browseButtonText);
  37569. /** Adds a listener that will be called when the selected file is changed. */
  37570. void addListener (FilenameComponentListener* const listener) throw();
  37571. /** Removes a previously-registered listener. */
  37572. void removeListener (FilenameComponentListener* const listener) throw();
  37573. /** Gives the component a tooltip. */
  37574. void setTooltip (const String& newTooltip);
  37575. /** @internal */
  37576. void paintOverChildren (Graphics& g);
  37577. /** @internal */
  37578. void resized();
  37579. /** @internal */
  37580. void lookAndFeelChanged();
  37581. /** @internal */
  37582. bool isInterestedInFileDrag (const StringArray& files);
  37583. /** @internal */
  37584. void filesDropped (const StringArray& files, int, int);
  37585. /** @internal */
  37586. void fileDragEnter (const StringArray& files, int, int);
  37587. /** @internal */
  37588. void fileDragExit (const StringArray& files);
  37589. juce_UseDebuggingNewOperator
  37590. private:
  37591. ComboBox* filenameBox;
  37592. String lastFilename;
  37593. Button* browseButton;
  37594. int maxRecentFiles;
  37595. bool isDir, isSaving, isFileDragOver;
  37596. String wildcard, enforcedSuffix, browseButtonText;
  37597. SortedSet <void*> listeners;
  37598. File defaultBrowseFile;
  37599. void comboBoxChanged (ComboBox*);
  37600. void buttonClicked (Button* button);
  37601. void handleAsyncUpdate();
  37602. FilenameComponent (const FilenameComponent&);
  37603. const FilenameComponent& operator= (const FilenameComponent&);
  37604. };
  37605. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37606. /********* End of inlined file: juce_FilenameComponent.h *********/
  37607. #endif
  37608. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37609. #endif
  37610. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37611. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37612. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37613. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37614. /**
  37615. Shows a set of file paths in a list, allowing them to be added, removed or
  37616. re-ordered.
  37617. @see FileSearchPath
  37618. */
  37619. class JUCE_API FileSearchPathListComponent : public Component,
  37620. public SettableTooltipClient,
  37621. public FileDragAndDropTarget,
  37622. private ButtonListener,
  37623. private ListBoxModel
  37624. {
  37625. public:
  37626. /** Creates an empty FileSearchPathListComponent.
  37627. */
  37628. FileSearchPathListComponent();
  37629. /** Destructor. */
  37630. ~FileSearchPathListComponent();
  37631. /** Returns the path as it is currently shown. */
  37632. const FileSearchPath& getPath() const throw() { return path; }
  37633. /** Changes the current path. */
  37634. void setPath (const FileSearchPath& newPath);
  37635. /** Sets a file or directory to be the default starting point for the browser to show.
  37636. This is only used if the current file hasn't been set.
  37637. */
  37638. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37639. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37640. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37641. methods.
  37642. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37643. */
  37644. enum ColourIds
  37645. {
  37646. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37647. Make this transparent if you don't want the background to be filled. */
  37648. };
  37649. /** @internal */
  37650. int getNumRows();
  37651. /** @internal */
  37652. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37653. /** @internal */
  37654. void deleteKeyPressed (int lastRowSelected);
  37655. /** @internal */
  37656. void returnKeyPressed (int lastRowSelected);
  37657. /** @internal */
  37658. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37659. /** @internal */
  37660. void selectedRowsChanged (int lastRowSelected);
  37661. /** @internal */
  37662. void resized();
  37663. /** @internal */
  37664. void paint (Graphics& g);
  37665. /** @internal */
  37666. bool isInterestedInFileDrag (const StringArray& files);
  37667. /** @internal */
  37668. void filesDropped (const StringArray& files, int, int);
  37669. /** @internal */
  37670. void buttonClicked (Button* button);
  37671. juce_UseDebuggingNewOperator
  37672. private:
  37673. FileSearchPath path;
  37674. File defaultBrowseTarget;
  37675. ListBox* listBox;
  37676. Button* addButton;
  37677. Button* removeButton;
  37678. Button* changeButton;
  37679. Button* upButton;
  37680. Button* downButton;
  37681. void changed() throw();
  37682. void updateButtons() throw();
  37683. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37684. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37685. };
  37686. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37687. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37688. #endif
  37689. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37690. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37691. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37692. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37693. /**
  37694. A component that displays the files in a directory as a treeview.
  37695. This implements the DirectoryContentsDisplayComponent base class so that
  37696. it can be used in a FileBrowserComponent.
  37697. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37698. class and the FileBrowserListener class.
  37699. @see DirectoryContentsList, FileListComponent
  37700. */
  37701. class JUCE_API FileTreeComponent : public TreeView,
  37702. public DirectoryContentsDisplayComponent
  37703. {
  37704. public:
  37705. /** Creates a listbox to show the contents of a specified directory.
  37706. */
  37707. FileTreeComponent (DirectoryContentsList& listToShow);
  37708. /** Destructor. */
  37709. ~FileTreeComponent();
  37710. /** Returns the number of selected files in the tree.
  37711. */
  37712. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37713. /** Returns one of the files that the user has currently selected.
  37714. Returns File::nonexistent if none is selected.
  37715. */
  37716. const File getSelectedFile (int index) const throw();
  37717. /** Returns the first of the files that the user has currently selected.
  37718. Returns File::nonexistent if none is selected.
  37719. */
  37720. const File getSelectedFile() const;
  37721. /** Scrolls the list to the top. */
  37722. void scrollToTop();
  37723. /** Setting a name for this allows tree items to be dragged.
  37724. The string that you pass in here will be returned by the getDragSourceDescription()
  37725. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37726. */
  37727. void setDragAndDropDescription (const String& description) throw();
  37728. /** Returns the last value that was set by setDragAndDropDescription().
  37729. */
  37730. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37731. juce_UseDebuggingNewOperator
  37732. private:
  37733. String dragAndDropDescription;
  37734. FileTreeComponent (const FileTreeComponent&);
  37735. const FileTreeComponent& operator= (const FileTreeComponent&);
  37736. };
  37737. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37738. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37739. #endif
  37740. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37741. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37742. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37743. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37744. /**
  37745. A simple preview component that shows thumbnails of image files.
  37746. @see FileChooserDialogBox, FilePreviewComponent
  37747. */
  37748. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37749. private Timer
  37750. {
  37751. public:
  37752. /** Creates an ImagePreviewComponent. */
  37753. ImagePreviewComponent();
  37754. /** Destructor. */
  37755. ~ImagePreviewComponent();
  37756. /** @internal */
  37757. void selectedFileChanged (const File& newSelectedFile);
  37758. /** @internal */
  37759. void paint (Graphics& g);
  37760. /** @internal */
  37761. void timerCallback();
  37762. juce_UseDebuggingNewOperator
  37763. private:
  37764. File fileToLoad;
  37765. Image* currentThumbnail;
  37766. String currentDetails;
  37767. void getThumbSize (int& w, int& h) const;
  37768. ImagePreviewComponent (const ImagePreviewComponent&);
  37769. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37770. };
  37771. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37772. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37773. #endif
  37774. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37775. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37776. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37777. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37778. /**
  37779. A type of FileFilter that works by wildcard pattern matching.
  37780. This filter only allows files that match one of the specified patterns, but
  37781. allows all directories through.
  37782. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37783. */
  37784. class JUCE_API WildcardFileFilter : public FileFilter
  37785. {
  37786. public:
  37787. /**
  37788. Creates a wildcard filter for one or more patterns.
  37789. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37790. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37791. or .aiff.
  37792. The description is a name to show the user in a list of possible patterns, so
  37793. for the wav/aiff example, your description might be "audio files".
  37794. */
  37795. WildcardFileFilter (const String& wildcardPatterns,
  37796. const String& description);
  37797. /** Destructor. */
  37798. ~WildcardFileFilter();
  37799. /** Returns true if the filename matches one of the patterns specified. */
  37800. bool isFileSuitable (const File& file) const;
  37801. /** This always returns true. */
  37802. bool isDirectorySuitable (const File& file) const;
  37803. juce_UseDebuggingNewOperator
  37804. private:
  37805. StringArray wildcards;
  37806. };
  37807. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37808. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37809. #endif
  37810. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37811. /********* Start of inlined file: juce_AlertWindow.h *********/
  37812. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37813. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37814. /** A window that displays a message and has buttons for the user to react to it.
  37815. For simple dialog boxes with just a couple of buttons on them, there are
  37816. some static methods for running these.
  37817. For more complex dialogs, an AlertWindow can be created, then it can have some
  37818. buttons and components added to it, and its runModalLoop() method is then used to
  37819. show it. The value returned by runModalLoop() shows which button the
  37820. user pressed to dismiss the box.
  37821. @see ThreadWithProgressWindow
  37822. */
  37823. class JUCE_API AlertWindow : public TopLevelWindow,
  37824. private ButtonListener
  37825. {
  37826. public:
  37827. /** The type of icon to show in the dialog box. */
  37828. enum AlertIconType
  37829. {
  37830. NoIcon, /**< No icon will be shown on the dialog box. */
  37831. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37832. user to answer a question. */
  37833. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37834. warning about something and shouldn't be ignored. */
  37835. InfoIcon /**< An icon that indicates that the dialog box is just
  37836. giving the user some information, which doesn't require
  37837. a response from them. */
  37838. };
  37839. /** Creates an AlertWindow.
  37840. @param title the headline to show at the top of the dialog box
  37841. @param message a longer, more descriptive message to show underneath the
  37842. headline
  37843. @param iconType the type of icon to display
  37844. @param associatedComponent if this is non-zero, it specifies the component that the
  37845. alert window should be associated with. Depending on the look
  37846. and feel, this might be used for positioning of the alert window.
  37847. */
  37848. AlertWindow (const String& title,
  37849. const String& message,
  37850. AlertIconType iconType,
  37851. Component* associatedComponent = 0);
  37852. /** Destroys the AlertWindow */
  37853. ~AlertWindow();
  37854. /** Returns the type of alert icon that was specified when the window
  37855. was created. */
  37856. AlertIconType getAlertType() const throw() { return alertIconType; }
  37857. /** Changes the dialog box's message.
  37858. This will also resize the window to fit the new message if required.
  37859. */
  37860. void setMessage (const String& message);
  37861. /** Adds a button to the window.
  37862. @param name the text to show on the button
  37863. @param returnValue the value that should be returned from runModalLoop()
  37864. if this is the button that the user presses.
  37865. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37866. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37867. */
  37868. void addButton (const String& name,
  37869. const int returnValue,
  37870. const KeyPress& shortcutKey1 = KeyPress(),
  37871. const KeyPress& shortcutKey2 = KeyPress());
  37872. /** Returns the number of buttons that the window currently has. */
  37873. int getNumButtons() const;
  37874. /** Adds a textbox to the window for entering strings.
  37875. @param name an internal name for the text-box. This is the name to pass to
  37876. the getTextEditorContents() method to find out what the
  37877. user typed-in.
  37878. @param initialContents a string to show in the text box when it's first shown
  37879. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37880. text-box to label it.
  37881. @param isPasswordBox if true, the text editor will display asterisks instead of
  37882. the actual text
  37883. @see getTextEditorContents
  37884. */
  37885. void addTextEditor (const String& name,
  37886. const String& initialContents,
  37887. const String& onScreenLabel = String::empty,
  37888. const bool isPasswordBox = false);
  37889. /** Returns the contents of a named textbox.
  37890. After showing an AlertWindow that contains a text editor, this can be
  37891. used to find out what the user has typed into it.
  37892. @param nameOfTextEditor the name of the text box that you're interested in
  37893. @see addTextEditor
  37894. */
  37895. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37896. /** Adds a drop-down list of choices to the box.
  37897. After the box has been shown, the getComboBoxComponent() method can
  37898. be used to find out which item the user picked.
  37899. @param name the label to use for the drop-down list
  37900. @param items the list of items to show in it
  37901. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37902. combo-box to label it.
  37903. @see getComboBoxComponent
  37904. */
  37905. void addComboBox (const String& name,
  37906. const StringArray& items,
  37907. const String& onScreenLabel = String::empty);
  37908. /** Returns a drop-down list that was added to the AlertWindow.
  37909. @param nameOfList the name that was passed into the addComboBox() method
  37910. when creating the drop-down
  37911. @returns the ComboBox component, or 0 if none was found for the given name.
  37912. */
  37913. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37914. /** Adds a block of text.
  37915. This is handy for adding a multi-line note next to a textbox or combo-box,
  37916. to provide more details about what's going on.
  37917. */
  37918. void addTextBlock (const String& text);
  37919. /** Adds a progress-bar to the window.
  37920. @param progressValue a variable that will be repeatedly checked while the
  37921. dialog box is visible, to see how far the process has
  37922. got. The value should be in the range 0 to 1.0
  37923. */
  37924. void addProgressBarComponent (double& progressValue);
  37925. /** Adds a user-defined component to the dialog box.
  37926. @param component the component to add - its size should be set up correctly
  37927. before it is passed in. The caller is responsible for deleting
  37928. the component later on - the AlertWindow won't delete it.
  37929. */
  37930. void addCustomComponent (Component* const component);
  37931. /** Returns the number of custom components in the dialog box.
  37932. @see getCustomComponent, addCustomComponent
  37933. */
  37934. int getNumCustomComponents() const;
  37935. /** Returns one of the custom components in the dialog box.
  37936. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37937. will return 0
  37938. @see getNumCustomComponents, addCustomComponent
  37939. */
  37940. Component* getCustomComponent (const int index) const;
  37941. /** Removes one of the custom components in the dialog box.
  37942. Note that this won't delete it, it just removes the component from the window
  37943. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37944. will return 0
  37945. @returns the component that was removed (or zero)
  37946. @see getNumCustomComponents, addCustomComponent
  37947. */
  37948. Component* removeCustomComponent (const int index);
  37949. /** Returns true if the window contains any components other than just buttons.*/
  37950. bool containsAnyExtraComponents() const;
  37951. // easy-to-use message box functions:
  37952. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37953. The box is shown modally, and the method returns after the user
  37954. has clicked the button (or pressed the escape or return keys).
  37955. @param iconType the type of icon to show
  37956. @param title the headline to show at the top of the box
  37957. @param message a longer, more descriptive message to show underneath the
  37958. headline
  37959. @param buttonText the text to show in the button - if this string is empty, the
  37960. default string "ok" (or a localised version) will be used.
  37961. @param associatedComponent if this is non-zero, it specifies the component that the
  37962. alert window should be associated with. Depending on the look
  37963. and feel, this might be used for positioning of the alert window.
  37964. */
  37965. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37966. const String& title,
  37967. const String& message,
  37968. const String& buttonText = String::empty,
  37969. Component* associatedComponent = 0);
  37970. /** Shows a dialog box with two buttons.
  37971. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37972. to trigger the first button, and the escape key for the second button.
  37973. @param iconType the type of icon to show
  37974. @param title the headline to show at the top of the box
  37975. @param message a longer, more descriptive message to show underneath the
  37976. headline
  37977. @param button1Text the text to show in the first button - if this string is
  37978. empty, the default string "ok" (or a localised version of it)
  37979. will be used.
  37980. @param button2Text the text to show in the second button - if this string is
  37981. empty, the default string "cancel" (or a localised version of it)
  37982. will be used.
  37983. @param associatedComponent if this is non-zero, it specifies the component that the
  37984. alert window should be associated with. Depending on the look
  37985. and feel, this might be used for positioning of the alert window.
  37986. @returns true if button 1 was clicked, false if it was button 2
  37987. */
  37988. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37989. const String& title,
  37990. const String& message,
  37991. const String& button1Text = String::empty,
  37992. const String& button2Text = String::empty,
  37993. Component* associatedComponent = 0);
  37994. /** Shows a dialog box with three buttons.
  37995. Ideal for yes/no/cancel boxes.
  37996. The escape key can be used to trigger the third button.
  37997. @param iconType the type of icon to show
  37998. @param title the headline to show at the top of the box
  37999. @param message a longer, more descriptive message to show underneath the
  38000. headline
  38001. @param button1Text the text to show in the first button - if an empty string, then
  38002. "yes" will be used (or a localised version of it)
  38003. @param button2Text the text to show in the first button - if an empty string, then
  38004. "no" will be used (or a localised version of it)
  38005. @param button3Text the text to show in the first button - if an empty string, then
  38006. "cancel" will be used (or a localised version of it)
  38007. @param associatedComponent if this is non-zero, it specifies the component that the
  38008. alert window should be associated with. Depending on the look
  38009. and feel, this might be used for positioning of the alert window.
  38010. @returns one of the following values:
  38011. - 0 if the third button was pressed (normally used for 'cancel')
  38012. - 1 if the first button was pressed (normally used for 'yes')
  38013. - 2 if the middle button was pressed (normally used for 'no')
  38014. */
  38015. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  38016. const String& title,
  38017. const String& message,
  38018. const String& button1Text = String::empty,
  38019. const String& button2Text = String::empty,
  38020. const String& button3Text = String::empty,
  38021. Component* associatedComponent = 0);
  38022. /** Shows an operating-system native dialog box.
  38023. @param title the title to use at the top
  38024. @param bodyText the longer message to show
  38025. @param isOkCancel if true, this will show an ok/cancel box, if false,
  38026. it'll show a box with just an ok button
  38027. @returns true if the ok button was pressed, false if they pressed cancel.
  38028. */
  38029. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  38030. const String& bodyText,
  38031. bool isOkCancel);
  38032. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  38033. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38034. methods.
  38035. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38036. */
  38037. enum ColourIds
  38038. {
  38039. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  38040. textColourId = 0x1001810, /**< The colour for the text. */
  38041. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  38042. };
  38043. juce_UseDebuggingNewOperator
  38044. protected:
  38045. /** @internal */
  38046. void paint (Graphics& g);
  38047. /** @internal */
  38048. void mouseDown (const MouseEvent& e);
  38049. /** @internal */
  38050. void mouseDrag (const MouseEvent& e);
  38051. /** @internal */
  38052. bool keyPressed (const KeyPress& key);
  38053. /** @internal */
  38054. void buttonClicked (Button* button);
  38055. /** @internal */
  38056. void lookAndFeelChanged();
  38057. /** @internal */
  38058. void userTriedToCloseWindow();
  38059. /** @internal */
  38060. int getDesktopWindowStyleFlags() const;
  38061. private:
  38062. String text;
  38063. TextLayout textLayout;
  38064. AlertIconType alertIconType;
  38065. ComponentBoundsConstrainer constrainer;
  38066. ComponentDragger dragger;
  38067. Rectangle textArea;
  38068. VoidArray buttons, textBoxes, comboBoxes;
  38069. VoidArray progressBars, customComps, textBlocks, allComps;
  38070. StringArray textboxNames, comboBoxNames;
  38071. Font font;
  38072. Component* associatedComponent;
  38073. void updateLayout (const bool onlyIncreaseSize);
  38074. // disable copy constructor
  38075. AlertWindow (const AlertWindow&);
  38076. const AlertWindow& operator= (const AlertWindow&);
  38077. };
  38078. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  38079. /********* End of inlined file: juce_AlertWindow.h *********/
  38080. #endif
  38081. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  38082. #endif
  38083. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38084. /********* Start of inlined file: juce_DialogWindow.h *********/
  38085. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38086. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  38087. /**
  38088. A dialog-box style window.
  38089. This class is a convenient way of creating a DocumentWindow with a close button
  38090. that can be triggered by pressing the escape key.
  38091. Any of the methods available to a DocumentWindow or ResizableWindow are also
  38092. available to this, so it can be made resizable, have a menu bar, etc.
  38093. To add items to the box, see the ResizableWindow::setContentComponent() method.
  38094. Don't add components directly to this class - always put them in a content component!
  38095. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  38096. the user clicking the close button - for more info, see the DocumentWindow
  38097. help.
  38098. @see DocumentWindow, ResizableWindow
  38099. */
  38100. class JUCE_API DialogWindow : public DocumentWindow
  38101. {
  38102. public:
  38103. /** Creates a DialogWindow.
  38104. @param name the name to give the component - this is also
  38105. the title shown at the top of the window. To change
  38106. this later, use setName()
  38107. @param backgroundColour the colour to use for filling the window's background.
  38108. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38109. close button to be triggered
  38110. @param addToDesktop if true, the window will be automatically added to the
  38111. desktop; if false, you can use it as a child component
  38112. */
  38113. DialogWindow (const String& name,
  38114. const Colour& backgroundColour,
  38115. const bool escapeKeyTriggersCloseButton,
  38116. const bool addToDesktop = true);
  38117. /** Destructor.
  38118. If a content component has been set with setContentComponent(), it
  38119. will be deleted.
  38120. */
  38121. ~DialogWindow();
  38122. /** Easy way of quickly showing a dialog box containing a given component.
  38123. This will open and display a DialogWindow containing a given component, returning
  38124. when the user clicks its close button.
  38125. It returns the value that was returned by the dialog box's runModalLoop() call.
  38126. To close the dialog programatically, you should call exitModalState (returnValue) on
  38127. the DialogWindow that is created. To find a pointer to this window from your
  38128. contentComponent, you can do something like this:
  38129. @code
  38130. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  38131. if (dw != 0)
  38132. dw->exitModalState (1234);
  38133. @endcode
  38134. @param dialogTitle the dialog box's title
  38135. @param contentComponent the content component for the dialog box. Make sure
  38136. that this has been set to the size you want it to
  38137. be before calling this method. The component won't
  38138. be deleted by this call, so you can re-use it or delete
  38139. it afterwards
  38140. @param componentToCentreAround if this is non-zero, it indicates a component that
  38141. you'd like to show this dialog box in front of. See the
  38142. DocumentWindow::centreAroundComponent() method for more
  38143. info on this parameter
  38144. @param backgroundColour a colour to use for the dialog box's background colour
  38145. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38146. close button to be triggered
  38147. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  38148. a corner resizer
  38149. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  38150. to use a border or corner resizer component. See ResizableWindow::setResizable()
  38151. */
  38152. static int showModalDialog (const String& dialogTitle,
  38153. Component* contentComponent,
  38154. Component* componentToCentreAround,
  38155. const Colour& backgroundColour,
  38156. const bool escapeKeyTriggersCloseButton,
  38157. const bool shouldBeResizable = false,
  38158. const bool useBottomRightCornerResizer = false);
  38159. juce_UseDebuggingNewOperator
  38160. protected:
  38161. /** @internal */
  38162. void resized();
  38163. private:
  38164. bool escapeKeyTriggersCloseButton;
  38165. DialogWindow (const DialogWindow&);
  38166. const DialogWindow& operator= (const DialogWindow&);
  38167. };
  38168. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  38169. /********* End of inlined file: juce_DialogWindow.h *********/
  38170. #endif
  38171. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38172. #endif
  38173. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  38174. #endif
  38175. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38176. /********* Start of inlined file: juce_SplashScreen.h *********/
  38177. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38178. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  38179. /** A component for showing a splash screen while your app starts up.
  38180. This will automatically position itself, and delete itself when the app has
  38181. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  38182. this).
  38183. To use it, just create one of these in your JUCEApplication::initialise() method,
  38184. call its show() method and let the object delete itself later.
  38185. E.g. @code
  38186. void MyApp::initialise (const String& commandLine)
  38187. {
  38188. SplashScreen* splash = new SplashScreen();
  38189. splash->show (T("welcome to my app"),
  38190. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  38191. 4000, false);
  38192. .. no need to delete the splash screen - it'll do that itself.
  38193. }
  38194. @endcode
  38195. */
  38196. class JUCE_API SplashScreen : public Component,
  38197. public Timer,
  38198. private DeletedAtShutdown
  38199. {
  38200. public:
  38201. /** Creates a SplashScreen object.
  38202. After creating one of these (or your subclass of it), call one of the show()
  38203. methods to display it.
  38204. */
  38205. SplashScreen();
  38206. /** Destructor. */
  38207. ~SplashScreen();
  38208. /** Creates a SplashScreen object that will display an image.
  38209. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38210. screen. This method will also dispatch any pending messages to make sure that when
  38211. it returns, the splash screen has been completely drawn, and your initialisation
  38212. code can carry on.
  38213. @param title the name to give the component
  38214. @param backgroundImage an image to draw on the component. The component's size
  38215. will be set to the size of this image, and if the image is
  38216. semi-transparent, the component will be made semi-transparent
  38217. too. This image will be deleted (or released from the ImageCache
  38218. if that's how it was created) by the splash screen object when
  38219. it is itself deleted.
  38220. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38221. should stay visible for. If the initialisation takes longer than
  38222. this time, the splash screen will wait for it to finish before
  38223. disappearing, but if initialisation is very quick, this lets
  38224. you make sure that people get a good look at your splash.
  38225. @param useDropShadow if true, the window will have a drop shadow
  38226. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38227. the mouse (anywhere)
  38228. */
  38229. void show (const String& title,
  38230. Image* const backgroundImage,
  38231. const int minimumTimeToDisplayFor,
  38232. const bool useDropShadow,
  38233. const bool removeOnMouseClick = true);
  38234. /** Creates a SplashScreen object with a specified size.
  38235. For a custom splash screen, you can use this method to display it at a certain size
  38236. and then override the paint() method yourself to do whatever's necessary.
  38237. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38238. screen. This method will also dispatch any pending messages to make sure that when
  38239. it returns, the splash screen has been completely drawn, and your initialisation
  38240. code can carry on.
  38241. @param title the name to give the component
  38242. @param width the width to use
  38243. @param height the height to use
  38244. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38245. should stay visible for. If the initialisation takes longer than
  38246. this time, the splash screen will wait for it to finish before
  38247. disappearing, but if initialisation is very quick, this lets
  38248. you make sure that people get a good look at your splash.
  38249. @param useDropShadow if true, the window will have a drop shadow
  38250. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38251. the mouse (anywhere)
  38252. */
  38253. void show (const String& title,
  38254. const int width,
  38255. const int height,
  38256. const int minimumTimeToDisplayFor,
  38257. const bool useDropShadow,
  38258. const bool removeOnMouseClick = true);
  38259. /** @internal */
  38260. void paint (Graphics& g);
  38261. /** @internal */
  38262. void timerCallback();
  38263. juce_UseDebuggingNewOperator
  38264. private:
  38265. Image* backgroundImage;
  38266. Time earliestTimeToDelete;
  38267. int originalClickCounter;
  38268. bool isImageInCache;
  38269. SplashScreen (const SplashScreen&);
  38270. const SplashScreen& operator= (const SplashScreen&);
  38271. };
  38272. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  38273. /********* End of inlined file: juce_SplashScreen.h *********/
  38274. #endif
  38275. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38276. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  38277. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38278. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38279. /**
  38280. A thread that automatically pops up a modal dialog box with a progress bar
  38281. and cancel button while it's busy running.
  38282. These are handy for performing some sort of task while giving the user feedback
  38283. about how long there is to go, etc.
  38284. E.g. @code
  38285. class MyTask : public ThreadWithProgressWindow
  38286. {
  38287. public:
  38288. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  38289. {
  38290. }
  38291. ~MyTask()
  38292. {
  38293. }
  38294. void run()
  38295. {
  38296. for (int i = 0; i < thingsToDo; ++i)
  38297. {
  38298. // must check this as often as possible, because this is
  38299. // how we know if the user's pressed 'cancel'
  38300. if (threadShouldExit())
  38301. break;
  38302. // this will update the progress bar on the dialog box
  38303. setProgress (i / (double) thingsToDo);
  38304. // ... do the business here...
  38305. }
  38306. }
  38307. };
  38308. void doTheTask()
  38309. {
  38310. MyTask m;
  38311. if (m.runThread())
  38312. {
  38313. // thread finished normally..
  38314. }
  38315. else
  38316. {
  38317. // user pressed the cancel button..
  38318. }
  38319. }
  38320. @endcode
  38321. @see Thread, AlertWindow
  38322. */
  38323. class JUCE_API ThreadWithProgressWindow : public Thread,
  38324. private Timer
  38325. {
  38326. public:
  38327. /** Creates the thread.
  38328. Initially, the dialog box won't be visible, it'll only appear when the
  38329. runThread() method is called.
  38330. @param windowTitle the title to go at the top of the dialog box
  38331. @param hasProgressBar whether the dialog box should have a progress bar (see
  38332. setProgress() )
  38333. @param hasCancelButton whether the dialog box should have a cancel button
  38334. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  38335. the thread to stop before killing it forcibly (see
  38336. Thread::stopThread() )
  38337. @param cancelButtonText the text that should be shown in the cancel button
  38338. (if it has one)
  38339. */
  38340. ThreadWithProgressWindow (const String& windowTitle,
  38341. const bool hasProgressBar,
  38342. const bool hasCancelButton,
  38343. const int timeOutMsWhenCancelling = 10000,
  38344. const String& cancelButtonText = JUCE_T("Cancel"));
  38345. /** Destructor. */
  38346. ~ThreadWithProgressWindow();
  38347. /** Starts the thread and waits for it to finish.
  38348. This will start the thread, make the dialog box appear, and wait until either
  38349. the thread finishes normally, or until the cancel button is pressed.
  38350. Before returning, the dialog box will be hidden.
  38351. @param threadPriority the priority to use when starting the thread - see
  38352. Thread::startThread() for values
  38353. @returns true if the thread finished normally; false if the user pressed cancel
  38354. */
  38355. bool runThread (const int threadPriority = 5);
  38356. /** The thread should call this periodically to update the position of the progress bar.
  38357. @param newProgress the progress, from 0.0 to 1.0
  38358. @see setStatusMessage
  38359. */
  38360. void setProgress (const double newProgress);
  38361. /** The thread can call this to change the message that's displayed in the dialog box.
  38362. */
  38363. void setStatusMessage (const String& newStatusMessage);
  38364. juce_UseDebuggingNewOperator
  38365. private:
  38366. void timerCallback();
  38367. double progress;
  38368. AlertWindow* alertWindow;
  38369. String message;
  38370. CriticalSection messageLock;
  38371. const int timeOutMsWhenCancelling;
  38372. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  38373. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  38374. };
  38375. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38376. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  38377. #endif
  38378. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  38379. #endif
  38380. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  38381. #endif
  38382. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38383. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  38384. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38385. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38386. #if JUCE_WIN32 || DOXYGEN
  38387. /**
  38388. A Windows-specific class that can create and embed an ActiveX control inside
  38389. itself.
  38390. To use it, create one of these, put it in place and make sure it's visible in a
  38391. window, then use createControl() to instantiate an ActiveX control. The control
  38392. will then be moved and resized to follow the movements of this component.
  38393. Of course, since the control is a heavyweight window, it'll obliterate any
  38394. juce components that may overlap this component, but that's life.
  38395. */
  38396. class JUCE_API ActiveXControlComponent : public Component
  38397. {
  38398. public:
  38399. /** Create an initially-empty container. */
  38400. ActiveXControlComponent();
  38401. /** Destructor. */
  38402. ~ActiveXControlComponent();
  38403. /** Tries to create an ActiveX control and embed it in this peer.
  38404. The peer controlIID is a pointer to an IID structure - it's treated
  38405. as a void* because when including the Juce headers, you might not always
  38406. have included windows.h first, in which case IID wouldn't be defined.
  38407. e.g. @code
  38408. const IID myIID = __uuidof (QTControl);
  38409. myControlComp->createControl (&myIID);
  38410. @endcode
  38411. */
  38412. bool createControl (const void* controlIID);
  38413. /** Deletes the ActiveX control, if one has been created.
  38414. */
  38415. void deleteControl();
  38416. /** Returns true if a control is currently in use. */
  38417. bool isControlOpen() const throw() { return control != 0; }
  38418. /** Does a QueryInterface call on the embedded control object.
  38419. This allows you to cast the control to whatever type of COM object you need.
  38420. The iid parameter is a pointer to an IID structure - it's treated
  38421. as a void* because when including the Juce headers, you might not always
  38422. have included windows.h first, in which case IID wouldn't be defined, but
  38423. you should just pass a pointer to an IID.
  38424. e.g. @code
  38425. const IID iid = __uuidof (IOleWindow);
  38426. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  38427. if (oleWindow != 0)
  38428. {
  38429. HWND hwnd;
  38430. oleWindow->GetWindow (&hwnd);
  38431. ...
  38432. oleWindow->Release();
  38433. }
  38434. @endcode
  38435. */
  38436. void* queryInterface (const void* iid) const;
  38437. /** Set this to false to stop mouse events being allowed through to the control.
  38438. */
  38439. void setMouseEventsAllowed (const bool eventsCanReachControl);
  38440. /** Returns true if mouse events are allowed to get through to the control.
  38441. */
  38442. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  38443. /** @internal */
  38444. void paint (Graphics& g);
  38445. /** @internal */
  38446. void* originalWndProc;
  38447. juce_UseDebuggingNewOperator
  38448. private:
  38449. friend class ActiveXControlData;
  38450. void* control;
  38451. bool mouseEventsAllowed;
  38452. ActiveXControlComponent (const ActiveXControlComponent&);
  38453. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  38454. void setControlBounds (const Rectangle& bounds) const;
  38455. void setControlVisible (const bool b) const;
  38456. };
  38457. #endif
  38458. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38459. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  38460. #endif
  38461. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38462. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38463. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38464. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38465. class MidiInputSelectorComponentListBox;
  38466. /**
  38467. A component containing controls to let the user change the audio settings of
  38468. an AudioDeviceManager object.
  38469. Very easy to use - just create one of these and show it to the user.
  38470. @see AudioDeviceManager
  38471. */
  38472. class JUCE_API AudioDeviceSelectorComponent : public Component,
  38473. public ComboBoxListener,
  38474. public ButtonListener,
  38475. public ChangeListener
  38476. {
  38477. public:
  38478. /** Creates the component.
  38479. If your app needs only output channels, you might ask for a maximum of 0 input
  38480. channels, and the component won't display any options for choosing the input
  38481. channels. And likewise if you're doing an input-only app.
  38482. @param deviceManager the device manager that this component should control
  38483. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  38484. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  38485. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  38486. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  38487. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  38488. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  38489. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  38490. treated as a set of separate mono channels.
  38491. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  38492. are shown, with an "advanced" button that shows the rest of them
  38493. */
  38494. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  38495. const int minAudioInputChannels,
  38496. const int maxAudioInputChannels,
  38497. const int minAudioOutputChannels,
  38498. const int maxAudioOutputChannels,
  38499. const bool showMidiInputOptions,
  38500. const bool showMidiOutputSelector,
  38501. const bool showChannelsAsStereoPairs,
  38502. const bool hideAdvancedOptionsWithButton);
  38503. /** Destructor */
  38504. ~AudioDeviceSelectorComponent();
  38505. /** @internal */
  38506. void resized();
  38507. /** @internal */
  38508. void comboBoxChanged (ComboBox*);
  38509. /** @internal */
  38510. void buttonClicked (Button*);
  38511. /** @internal */
  38512. void changeListenerCallback (void*);
  38513. juce_UseDebuggingNewOperator
  38514. private:
  38515. AudioDeviceManager& deviceManager;
  38516. ComboBox* deviceTypeDropDown;
  38517. Label* deviceTypeDropDownLabel;
  38518. Component* audioDeviceSettingsComp;
  38519. String audioDeviceSettingsCompType;
  38520. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  38521. const bool showChannelsAsStereoPairs;
  38522. const bool hideAdvancedOptionsWithButton;
  38523. MidiInputSelectorComponentListBox* midiInputsList;
  38524. Label* midiInputsLabel;
  38525. ComboBox* midiOutputSelector;
  38526. Label* midiOutputLabel;
  38527. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  38528. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  38529. };
  38530. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38531. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38532. #endif
  38533. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38534. /********* Start of inlined file: juce_BubbleComponent.h *********/
  38535. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38536. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38537. /**
  38538. A component for showing a message or other graphics inside a speech-bubble-shaped
  38539. outline, pointing at a location on the screen.
  38540. This is a base class that just draws and positions the bubble shape, but leaves
  38541. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  38542. that draws a text message.
  38543. To use it, create your subclass, then either add it to a parent component or
  38544. put it on the desktop with addToDesktop (0), use setPosition() to
  38545. resize and position it, then make it visible.
  38546. @see BubbleMessageComponent
  38547. */
  38548. class JUCE_API BubbleComponent : public Component
  38549. {
  38550. protected:
  38551. /** Creates a BubbleComponent.
  38552. Your subclass will need to implement the getContentSize() and paintContent()
  38553. methods to draw the bubble's contents.
  38554. */
  38555. BubbleComponent();
  38556. public:
  38557. /** Destructor. */
  38558. ~BubbleComponent();
  38559. /** A list of permitted placements for the bubble, relative to the co-ordinates
  38560. at which it should be pointing.
  38561. @see setAllowedPlacement
  38562. */
  38563. enum BubblePlacement
  38564. {
  38565. above = 1,
  38566. below = 2,
  38567. left = 4,
  38568. right = 8
  38569. };
  38570. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  38571. point at which it's pointing.
  38572. By default when setPosition() is called, the bubble will place itself either
  38573. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  38574. the values in BubblePlacement to restrict this choice.
  38575. E.g. if you only want your bubble to appear above or below the target area,
  38576. use setAllowedPlacement (above | below);
  38577. @see BubblePlacement
  38578. */
  38579. void setAllowedPlacement (const int newPlacement);
  38580. /** Moves and resizes the bubble to point at a given component.
  38581. This will resize the bubble to fit its content, then find a position for it
  38582. so that it's next to, but doesn't overlap the given component.
  38583. It'll put itself either above, below, or to the side of the component depending
  38584. on where there's the most space, honouring any restrictions that were set
  38585. with setAllowedPlacement().
  38586. */
  38587. void setPosition (Component* componentToPointTo);
  38588. /** Moves and resizes the bubble to point at a given point.
  38589. This will resize the bubble to fit its content, then position it
  38590. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  38591. are relative to either the bubble component's parent component if it has one, or
  38592. they are screen co-ordinates if not.
  38593. It'll put itself either above, below, or to the side of this point, depending
  38594. on where there's the most space, honouring any restrictions that were set
  38595. with setAllowedPlacement().
  38596. */
  38597. void setPosition (const int arrowTipX,
  38598. const int arrowTipY);
  38599. /** Moves and resizes the bubble to point at a given rectangle.
  38600. This will resize the bubble to fit its content, then find a position for it
  38601. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  38602. co-ordinates are relative to either the bubble component's parent component
  38603. if it has one, or they are screen co-ordinates if not.
  38604. It'll put itself either above, below, or to the side of the component depending
  38605. on where there's the most space, honouring any restrictions that were set
  38606. with setAllowedPlacement().
  38607. */
  38608. void setPosition (const Rectangle& rectangleToPointTo);
  38609. protected:
  38610. /** Subclasses should override this to return the size of the content they
  38611. want to draw inside the bubble.
  38612. */
  38613. virtual void getContentSize (int& width, int& height) = 0;
  38614. /** Subclasses should override this to draw their bubble's contents.
  38615. The graphics object's clip region and the dimensions passed in here are
  38616. set up to paint just the rectangle inside the bubble.
  38617. */
  38618. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38619. public:
  38620. /** @internal */
  38621. void paint (Graphics& g);
  38622. juce_UseDebuggingNewOperator
  38623. private:
  38624. Rectangle content;
  38625. int side, allowablePlacements;
  38626. float arrowTipX, arrowTipY;
  38627. DropShadowEffect shadow;
  38628. BubbleComponent (const BubbleComponent&);
  38629. const BubbleComponent& operator= (const BubbleComponent&);
  38630. };
  38631. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38632. /********* End of inlined file: juce_BubbleComponent.h *********/
  38633. #endif
  38634. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38635. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38636. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38637. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38638. /**
  38639. A speech-bubble component that displays a short message.
  38640. This can be used to show a message with the tail of the speech bubble
  38641. pointing to a particular component or location on the screen.
  38642. @see BubbleComponent
  38643. */
  38644. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38645. private Timer
  38646. {
  38647. public:
  38648. /** Creates a bubble component.
  38649. After creating one a BubbleComponent, do the following:
  38650. - add it to an appropriate parent component, or put it on the
  38651. desktop with Component::addToDesktop (0).
  38652. - use the showAt() method to show a message.
  38653. - it will make itself invisible after it times-out (and can optionally
  38654. also delete itself), or you can reuse it somewhere else by calling
  38655. showAt() again.
  38656. */
  38657. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38658. /** Destructor. */
  38659. ~BubbleMessageComponent();
  38660. /** Shows a message bubble at a particular position.
  38661. This shows the bubble with its stem pointing to the given location
  38662. (co-ordinates being relative to its parent component).
  38663. For details about exactly how it decides where to position itself, see
  38664. BubbleComponent::updatePosition().
  38665. @param x the x co-ordinate of end of the bubble's tail
  38666. @param y the y co-ordinate of end of the bubble's tail
  38667. @param message the text to display
  38668. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38669. from its parent compnent. If this is 0 or less, it
  38670. will stay there until manually removed.
  38671. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38672. mouse button is pressed (anywhere on the screen)
  38673. @param deleteSelfAfterUse if true, then the component will delete itself after
  38674. it becomes invisible
  38675. */
  38676. void showAt (int x, int y,
  38677. const String& message,
  38678. const int numMillisecondsBeforeRemoving,
  38679. const bool removeWhenMouseClicked = true,
  38680. const bool deleteSelfAfterUse = false);
  38681. /** Shows a message bubble next to a particular component.
  38682. This shows the bubble with its stem pointing at the given component.
  38683. For details about exactly how it decides where to position itself, see
  38684. BubbleComponent::updatePosition().
  38685. @param component the component that you want to point at
  38686. @param message the text to display
  38687. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38688. from its parent compnent. If this is 0 or less, it
  38689. will stay there until manually removed.
  38690. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38691. mouse button is pressed (anywhere on the screen)
  38692. @param deleteSelfAfterUse if true, then the component will delete itself after
  38693. it becomes invisible
  38694. */
  38695. void showAt (Component* const component,
  38696. const String& message,
  38697. const int numMillisecondsBeforeRemoving,
  38698. const bool removeWhenMouseClicked = true,
  38699. const bool deleteSelfAfterUse = false);
  38700. /** @internal */
  38701. void getContentSize (int& w, int& h);
  38702. /** @internal */
  38703. void paintContent (Graphics& g, int w, int h);
  38704. /** @internal */
  38705. void timerCallback();
  38706. juce_UseDebuggingNewOperator
  38707. private:
  38708. int fadeOutLength, mouseClickCounter;
  38709. TextLayout textLayout;
  38710. int64 expiryTime;
  38711. bool deleteAfterUse;
  38712. void init (const int numMillisecondsBeforeRemoving,
  38713. const bool removeWhenMouseClicked,
  38714. const bool deleteSelfAfterUse);
  38715. BubbleMessageComponent (const BubbleMessageComponent&);
  38716. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38717. };
  38718. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38719. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38720. #endif
  38721. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38722. /********* Start of inlined file: juce_ColourSelector.h *********/
  38723. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38724. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38725. /**
  38726. A component that lets the user choose a colour.
  38727. This shows RGB sliders and a colourspace that the user can pick colours from.
  38728. This class is also a ChangeBroadcaster, so listeners can register to be told
  38729. when the colour changes.
  38730. */
  38731. class JUCE_API ColourSelector : public Component,
  38732. public ChangeBroadcaster,
  38733. protected SliderListener
  38734. {
  38735. public:
  38736. /** Options for the type of selector to show. These are passed into the constructor. */
  38737. enum ColourSelectorOptions
  38738. {
  38739. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38740. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38741. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38742. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38743. };
  38744. /** Creates a ColourSelector object.
  38745. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38746. which of the selector's features should be visible.
  38747. The edgeGap value specifies the amount of space to leave around the edge.
  38748. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38749. colourspace and hue selector components.
  38750. */
  38751. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38752. const int edgeGap = 4,
  38753. const int gapAroundColourSpaceComponent = 7);
  38754. /** Destructor. */
  38755. ~ColourSelector();
  38756. /** Returns the colour that the user has currently selected.
  38757. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38758. register to be told when the colour changes.
  38759. @see setCurrentColour
  38760. */
  38761. const Colour getCurrentColour() const;
  38762. /** Changes the colour that is currently being shown.
  38763. */
  38764. void setCurrentColour (const Colour& newColour);
  38765. /** Tells the selector how many preset colour swatches you want to have on the component.
  38766. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38767. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38768. their values.
  38769. */
  38770. virtual int getNumSwatches() const;
  38771. /** Called by the selector to find out the colour of one of the swatches.
  38772. Your subclass should return the colour of the swatch with the given index.
  38773. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38774. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38775. their values.
  38776. */
  38777. virtual const Colour getSwatchColour (const int index) const;
  38778. /** Called by the selector when the user puts a new colour into one of the swatches.
  38779. Your subclass should change the colour of the swatch with the given index.
  38780. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38781. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38782. their values.
  38783. */
  38784. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38785. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38786. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38787. methods.
  38788. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38789. */
  38790. enum ColourIds
  38791. {
  38792. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38793. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38794. };
  38795. juce_UseDebuggingNewOperator
  38796. private:
  38797. friend class ColourSpaceView;
  38798. friend class HueSelectorComp;
  38799. Colour colour;
  38800. float h, s, v;
  38801. Slider* sliders[4];
  38802. Component* colourSpace;
  38803. Component* hueSelector;
  38804. VoidArray swatchComponents;
  38805. const int flags;
  38806. int topSpace, edgeGap;
  38807. void setHue (float newH);
  38808. void setSV (float newS, float newV);
  38809. void updateHSV();
  38810. void update();
  38811. void sliderValueChanged (Slider*);
  38812. void paint (Graphics& g);
  38813. void resized();
  38814. ColourSelector (const ColourSelector&);
  38815. const ColourSelector& operator= (const ColourSelector&);
  38816. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38817. // have changed - if you get an error here, update your code to use the new constructor instead..
  38818. // (xxx - note to self: remember to remove this at some point in the future)
  38819. ColourSelector (const bool);
  38820. };
  38821. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38822. /********* End of inlined file: juce_ColourSelector.h *********/
  38823. #endif
  38824. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  38825. #endif
  38826. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38827. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  38828. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38829. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38830. /**
  38831. A component that contains another component, and can magnify or shrink it.
  38832. This component will continually update its size so that it fits the zoomed
  38833. version of the content component that you put inside it, so don't try to
  38834. change the size of this component directly - instead change that of the
  38835. content component.
  38836. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  38837. to remap mouse events correctly. This means that the content component won't
  38838. appear to be a direct child of this component, and instead will think its
  38839. on the desktop.
  38840. */
  38841. class JUCE_API MagnifierComponent : public Component
  38842. {
  38843. public:
  38844. /** Creates a MagnifierComponent.
  38845. This component will continually update its size so that it fits the zoomed
  38846. version of the content component that you put inside it, so don't try to
  38847. change the size of this component directly - instead change that of the
  38848. content component.
  38849. @param contentComponent the component to add as the magnified one
  38850. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  38851. be deleted when this component is deleted. If false,
  38852. it's the caller's responsibility to delete it later.
  38853. */
  38854. MagnifierComponent (Component* const contentComponent,
  38855. const bool deleteContentCompWhenNoLongerNeeded);
  38856. /** Destructor. */
  38857. ~MagnifierComponent();
  38858. /** Returns the current content component. */
  38859. Component* getContentComponent() const throw() { return content; }
  38860. /** Changes the zoom level.
  38861. The scale factor must be greater than zero. Values less than 1 will shrink the
  38862. image; values greater than 1 will multiply its size by this amount.
  38863. When this is called, this component will change its size to fit the full extent
  38864. of the newly zoomed content.
  38865. */
  38866. void setScaleFactor (double newScaleFactor);
  38867. /** Returns the current zoom factor. */
  38868. double getScaleFactor() const throw() { return scaleFactor; }
  38869. juce_UseDebuggingNewOperator
  38870. /** @internal */
  38871. void childBoundsChanged (Component*);
  38872. private:
  38873. Component* content;
  38874. Component* holderComp;
  38875. double scaleFactor;
  38876. ComponentPeer* peer;
  38877. bool deleteContent;
  38878. void paint (Graphics& g);
  38879. void mouseDown (const MouseEvent& e);
  38880. void mouseUp (const MouseEvent& e);
  38881. void mouseDrag (const MouseEvent& e);
  38882. void mouseMove (const MouseEvent& e);
  38883. void mouseEnter (const MouseEvent& e);
  38884. void mouseExit (const MouseEvent& e);
  38885. void mouseWheelMove (const MouseEvent& e, float, float);
  38886. int scaleInt (const int n) const throw();
  38887. MagnifierComponent (const MagnifierComponent&);
  38888. const MagnifierComponent& operator= (const MagnifierComponent&);
  38889. };
  38890. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38891. /********* End of inlined file: juce_MagnifierComponent.h *********/
  38892. #endif
  38893. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38894. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  38895. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38896. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38897. /**
  38898. A component that displays a piano keyboard, whose notes can be clicked on.
  38899. This component will mimic a physical midi keyboard, showing the current state of
  38900. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  38901. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  38902. Another feature is that the computer keyboard can also be used to play notes. By
  38903. default it maps the top two rows of a standard querty keyboard to the notes, but
  38904. these can be remapped if needed. It will only respond to keypresses when it has
  38905. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  38906. The component is also a ChangeBroadcaster, so if you want to be informed when the
  38907. keyboard is scrolled, you can register a ChangeListener for callbacks.
  38908. @see MidiKeyboardState
  38909. */
  38910. class JUCE_API MidiKeyboardComponent : public Component,
  38911. public MidiKeyboardStateListener,
  38912. public ChangeBroadcaster,
  38913. private Timer,
  38914. private AsyncUpdater
  38915. {
  38916. public:
  38917. /** The direction of the keyboard.
  38918. @see setOrientation
  38919. */
  38920. enum Orientation
  38921. {
  38922. horizontalKeyboard,
  38923. verticalKeyboardFacingLeft,
  38924. verticalKeyboardFacingRight,
  38925. };
  38926. /** Creates a MidiKeyboardComponent.
  38927. @param state the midi keyboard model that this component will represent
  38928. @param orientation whether the keyboard is horizonal or vertical
  38929. */
  38930. MidiKeyboardComponent (MidiKeyboardState& state,
  38931. const Orientation orientation);
  38932. /** Destructor. */
  38933. ~MidiKeyboardComponent();
  38934. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  38935. on the component.
  38936. Values are 0 to 1.0, where 1.0 is the heaviest.
  38937. @see setMidiChannel
  38938. */
  38939. void setVelocity (const float velocity);
  38940. /** Changes the midi channel number that will be used for events triggered by clicking
  38941. on the component.
  38942. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  38943. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  38944. Although this is the channel used for outgoing events, the component can display
  38945. incoming events from more than one channel - see setMidiChannelsToDisplay()
  38946. @see setVelocity
  38947. */
  38948. void setMidiChannel (const int midiChannelNumber);
  38949. /** Returns the midi channel that the keyboard is using for midi messages.
  38950. @see setMidiChannel
  38951. */
  38952. int getMidiChannel() const throw() { return midiChannel; }
  38953. /** Sets a mask to indicate which incoming midi channels should be represented by
  38954. key movements.
  38955. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  38956. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  38957. in this mask, the on-screen keys will also go down.
  38958. By default, this mask is set to 0xffff (all channels displayed).
  38959. @see setMidiChannel
  38960. */
  38961. void setMidiChannelsToDisplay (const int midiChannelMask);
  38962. /** Returns the current set of midi channels represented by the component.
  38963. This is the value that was set with setMidiChannelsToDisplay().
  38964. */
  38965. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  38966. /** Changes the width used to draw the white keys. */
  38967. void setKeyWidth (const float widthInPixels);
  38968. /** Returns the width that was set by setKeyWidth(). */
  38969. float getKeyWidth() const throw() { return keyWidth; }
  38970. /** Changes the keyboard's current direction. */
  38971. void setOrientation (const Orientation newOrientation);
  38972. /** Returns the keyboard's current direction. */
  38973. const Orientation getOrientation() const throw() { return orientation; }
  38974. /** Sets the range of midi notes that the keyboard will be limited to.
  38975. By default the range is 0 to 127 (inclusive), but you can limit this if you
  38976. only want a restricted set of the keys to be shown.
  38977. Note that the values here are inclusive and must be between 0 and 127.
  38978. */
  38979. void setAvailableRange (const int lowestNote,
  38980. const int highestNote);
  38981. /** Returns the first note in the available range.
  38982. @see setAvailableRange
  38983. */
  38984. int getRangeStart() const throw() { return rangeStart; }
  38985. /** Returns the last note in the available range.
  38986. @see setAvailableRange
  38987. */
  38988. int getRangeEnd() const throw() { return rangeEnd; }
  38989. /** If the keyboard extends beyond the size of the component, this will scroll
  38990. it to show the given key at the start.
  38991. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  38992. base class to send a callback to any ChangeListeners that have been registered.
  38993. */
  38994. void setLowestVisibleKey (int noteNumber);
  38995. /** Returns the number of the first key shown in the component.
  38996. @see setLowestVisibleKey
  38997. */
  38998. int getLowestVisibleKey() const throw() { return firstKey; }
  38999. /** Returns the length of the black notes.
  39000. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  39001. */
  39002. int getBlackNoteLength() const throw() { return blackNoteLength; }
  39003. /** If set to true, then scroll buttons will appear at either end of the keyboard
  39004. if there are too many notes to fit them all in the component at once.
  39005. */
  39006. void setScrollButtonsVisible (const bool canScroll);
  39007. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39008. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39009. methods.
  39010. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39011. */
  39012. enum ColourIds
  39013. {
  39014. whiteNoteColourId = 0x1005000,
  39015. blackNoteColourId = 0x1005001,
  39016. keySeparatorLineColourId = 0x1005002,
  39017. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  39018. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  39019. textLabelColourId = 0x1005005,
  39020. upDownButtonBackgroundColourId = 0x1005006,
  39021. upDownButtonArrowColourId = 0x1005007
  39022. };
  39023. /** Returns the position within the component of the left-hand edge of a key.
  39024. Depending on the keyboard's orientation, this may be a horizontal or vertical
  39025. distance, in either direction.
  39026. */
  39027. int getKeyStartPosition (const int midiNoteNumber) const;
  39028. /** Deletes all key-mappings.
  39029. @see setKeyPressForNote
  39030. */
  39031. void clearKeyMappings();
  39032. /** Maps a key-press to a given note.
  39033. @param key the key that should trigger the note
  39034. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  39035. be. The actual midi note that gets played will be
  39036. this value + (12 * the current base octave). To change
  39037. the base octave, see setKeyPressBaseOctave()
  39038. */
  39039. void setKeyPressForNote (const KeyPress& key,
  39040. const int midiNoteOffsetFromC);
  39041. /** Removes any key-mappings for a given note.
  39042. For a description of what the note number means, see setKeyPressForNote().
  39043. */
  39044. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  39045. /** Changes the base note above which key-press-triggered notes are played.
  39046. The set of key-mappings that trigger notes can be moved up and down to cover
  39047. the entire scale using this method.
  39048. The value passed in is an octave number between 0 and 10 (inclusive), and
  39049. indicates which C is the base note to which the key-mapped notes are
  39050. relative.
  39051. */
  39052. void setKeyPressBaseOctave (const int newOctaveNumber);
  39053. /** This sets the octave number which is shown as the octave number for middle C.
  39054. This affects only the default implementation of getWhiteNoteText(), which
  39055. passes this octave number to MidiMessage::getMidiNoteName() in order to
  39056. get the note text. See MidiMessage::getMidiNoteName() for more info about
  39057. the parameter.
  39058. By default this value is set to 3.
  39059. @see getOctaveForMiddleC
  39060. */
  39061. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  39062. /** This returns the value set by setOctaveForMiddleC().
  39063. @see setOctaveForMiddleC
  39064. */
  39065. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  39066. /** @internal */
  39067. void paint (Graphics& g);
  39068. /** @internal */
  39069. void resized();
  39070. /** @internal */
  39071. void mouseMove (const MouseEvent& e);
  39072. /** @internal */
  39073. void mouseDrag (const MouseEvent& e);
  39074. /** @internal */
  39075. void mouseDown (const MouseEvent& e);
  39076. /** @internal */
  39077. void mouseUp (const MouseEvent& e);
  39078. /** @internal */
  39079. void mouseEnter (const MouseEvent& e);
  39080. /** @internal */
  39081. void mouseExit (const MouseEvent& e);
  39082. /** @internal */
  39083. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39084. /** @internal */
  39085. void timerCallback();
  39086. /** @internal */
  39087. bool keyStateChanged();
  39088. /** @internal */
  39089. void focusLost (FocusChangeType cause);
  39090. /** @internal */
  39091. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  39092. /** @internal */
  39093. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  39094. /** @internal */
  39095. void handleAsyncUpdate();
  39096. /** @internal */
  39097. void colourChanged();
  39098. juce_UseDebuggingNewOperator
  39099. protected:
  39100. friend class MidiKeyboardUpDownButton;
  39101. /** Draws a white note in the given rectangle.
  39102. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39103. currently pressed down.
  39104. When doing this, be sure to note the keyboard's orientation.
  39105. */
  39106. virtual void drawWhiteNote (int midiNoteNumber,
  39107. Graphics& g,
  39108. int x, int y, int w, int h,
  39109. bool isDown, bool isOver,
  39110. const Colour& lineColour,
  39111. const Colour& textColour);
  39112. /** Draws a black note in the given rectangle.
  39113. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39114. currently pressed down.
  39115. When doing this, be sure to note the keyboard's orientation.
  39116. */
  39117. virtual void drawBlackNote (int midiNoteNumber,
  39118. Graphics& g,
  39119. int x, int y, int w, int h,
  39120. bool isDown, bool isOver,
  39121. const Colour& noteFillColour);
  39122. /** Allows text to be drawn on the white notes.
  39123. By default this is used to label the C in each octave, but could be used for other things.
  39124. @see setOctaveForMiddleC
  39125. */
  39126. virtual const String getWhiteNoteText (const int midiNoteNumber);
  39127. /** Draws the up and down buttons that change the base note. */
  39128. virtual void drawUpDownButton (Graphics& g, int w, int h,
  39129. const bool isMouseOver,
  39130. const bool isButtonPressed,
  39131. const bool movesOctavesUp);
  39132. /** Callback when the mouse is clicked on a key.
  39133. You could use this to do things like handle right-clicks on keys, etc.
  39134. Return true if you want the click to trigger the note, or false if you
  39135. want to handle it yourself and not have the note played.
  39136. @see mouseDraggedToKey
  39137. */
  39138. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  39139. /** Callback when the mouse is dragged from one key onto another.
  39140. @see mouseDownOnKey
  39141. */
  39142. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  39143. /** Calculates the positon of a given midi-note.
  39144. This can be overridden to create layouts with custom key-widths.
  39145. @param midiNoteNumber the note to find
  39146. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  39147. @param x the x position of the left-hand edge of the key (this method
  39148. always works in terms of a horizontal keyboard)
  39149. @param w the width of the key
  39150. */
  39151. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  39152. int& x, int& w) const;
  39153. private:
  39154. MidiKeyboardState& state;
  39155. int xOffset, blackNoteLength;
  39156. float keyWidth;
  39157. Orientation orientation;
  39158. int midiChannel, midiInChannelMask;
  39159. float velocity;
  39160. int noteUnderMouse, mouseDownNote;
  39161. BitArray keysPressed, keysCurrentlyDrawnDown;
  39162. int rangeStart, rangeEnd, firstKey;
  39163. bool canScroll, mouseDragging;
  39164. Button* scrollDown;
  39165. Button* scrollUp;
  39166. Array <KeyPress> keyPresses;
  39167. Array <int> keyPressNotes;
  39168. int keyMappingOctave;
  39169. int octaveNumForMiddleC;
  39170. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  39171. int xyToNote (int x, int y);
  39172. int remappedXYToNote (int x, int y) const;
  39173. void resetAnyKeysInUse();
  39174. void updateNoteUnderMouse (int x, int y);
  39175. void repaintNote (const int midiNoteNumber);
  39176. MidiKeyboardComponent (const MidiKeyboardComponent&);
  39177. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  39178. };
  39179. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39180. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  39181. #endif
  39182. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39183. /********* Start of inlined file: juce_NSViewComponent.h *********/
  39184. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39185. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39186. #if ! DOXYGEN
  39187. class NSViewComponentInternal;
  39188. #endif
  39189. #if JUCE_MAC || DOXYGEN
  39190. /**
  39191. A Mac-specific class that can create and embed an NSView inside itself.
  39192. To use it, create one of these, put it in place and make sure it's visible in a
  39193. window, then use setView() to assign an NSView to it. The view will then be
  39194. moved and resized to follow the movements of this component.
  39195. Of course, since the view is a native object, it'll obliterate any
  39196. juce components that may overlap this component, but that's life.
  39197. */
  39198. class JUCE_API NSViewComponent : public Component
  39199. {
  39200. public:
  39201. /** Create an initially-empty container. */
  39202. NSViewComponent();
  39203. /** Destructor. */
  39204. ~NSViewComponent();
  39205. /** Assigns an NSView to this peer.
  39206. The view will be retained and released by this component for as long as
  39207. it is needed. To remove the current view, just call setView (0).
  39208. Note: a void* is used here to avoid including the cocoa headers as
  39209. part of the juce.h, but the method expects an NSView*.
  39210. */
  39211. void setView (void* nsView);
  39212. /** Returns the current NSView.
  39213. Note: a void* is returned here to avoid including the cocoa headers as
  39214. a requirement of juce.h, so you should just cast the object to an NSView*.
  39215. */
  39216. void* getView() const;
  39217. /** @internal */
  39218. void paint (Graphics& g);
  39219. juce_UseDebuggingNewOperator
  39220. private:
  39221. friend class NSViewComponentInternal;
  39222. NSViewComponentInternal* info;
  39223. NSViewComponent (const NSViewComponent&);
  39224. const NSViewComponent& operator= (const NSViewComponent&);
  39225. };
  39226. #endif
  39227. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39228. /********* End of inlined file: juce_NSViewComponent.h *********/
  39229. #endif
  39230. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39231. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  39232. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39233. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39234. // this is used to disable OpenGL, and is defined in juce_Config.h
  39235. #if JUCE_OPENGL || DOXYGEN
  39236. class OpenGLComponentWatcher;
  39237. /**
  39238. Represents the various properties of an OpenGL bitmap format.
  39239. @see OpenGLComponent::setPixelFormat
  39240. */
  39241. struct OpenGLPixelFormat
  39242. {
  39243. /** Creates an OpenGLPixelFormat.
  39244. The default constructor just initialises the object as a simple 8-bit
  39245. RGBA format.
  39246. */
  39247. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  39248. const int alphaBits = 8,
  39249. const int depthBufferBits = 16,
  39250. const int stencilBufferBits = 0) throw();
  39251. int redBits; /**< The number of bits per pixel to use for the red channel. */
  39252. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  39253. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  39254. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  39255. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  39256. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  39257. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  39258. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  39259. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  39260. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  39261. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  39262. /** Returns a list of all the pixel formats that can be used in this system.
  39263. A reference component is needed in case there are multiple screens with different
  39264. capabilities - in which case, the one that the component is on will be used.
  39265. */
  39266. static void getAvailablePixelFormats (Component* component,
  39267. OwnedArray <OpenGLPixelFormat>& results);
  39268. bool operator== (const OpenGLPixelFormat&) const throw();
  39269. juce_UseDebuggingNewOperator
  39270. };
  39271. /**
  39272. A base class for types of OpenGL context.
  39273. An OpenGLComponent will supply its own context for drawing in its window.
  39274. */
  39275. class OpenGLContext
  39276. {
  39277. public:
  39278. /** Destructor. */
  39279. virtual ~OpenGLContext();
  39280. /** Makes this context the currently active one. */
  39281. virtual bool makeActive() const throw() = 0;
  39282. /** If this context is currently active, it is disactivated. */
  39283. virtual bool makeInactive() const throw() = 0;
  39284. /** Returns true if this context is currently active. */
  39285. virtual bool isActive() const throw() = 0;
  39286. /** Swaps the buffers (if the context can do this). */
  39287. virtual void swapBuffers() = 0;
  39288. /** Sets whether the context checks the vertical sync before swapping.
  39289. The value is the number of frames to allow between buffer-swapping. This is
  39290. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  39291. and greater numbers indicate that it should swap less often.
  39292. Returns true if it sets the value successfully.
  39293. */
  39294. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  39295. /** Returns the current swap-sync interval.
  39296. See setSwapInterval() for info about the value returned.
  39297. */
  39298. virtual int getSwapInterval() const = 0;
  39299. /** Returns the pixel format being used by this context. */
  39300. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  39301. /** For windowed contexts, this moves the context within the bounds of
  39302. its parent window.
  39303. */
  39304. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  39305. /** For windowed contexts, this triggers a repaint of the window.
  39306. (Not relevent on all platforms).
  39307. */
  39308. virtual void repaint() = 0;
  39309. /** Returns an OS-dependent handle to the raw GL context.
  39310. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  39311. a GLXContext.
  39312. */
  39313. virtual void* getRawContext() const throw() = 0;
  39314. /** This tries to create a context that can be used for drawing into the
  39315. area occupied by the specified component.
  39316. Note that you probably shouldn't use this method directly unless you know what
  39317. you're doing - the OpenGLComponent calls this and manages the context for you.
  39318. */
  39319. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  39320. const OpenGLPixelFormat& pixelFormat,
  39321. const OpenGLContext* const contextToShareWith);
  39322. /** Returns the context that's currently in active use by the calling thread.
  39323. Returns 0 if there isn't an active context.
  39324. */
  39325. static OpenGLContext* getCurrentContext();
  39326. juce_UseDebuggingNewOperator
  39327. protected:
  39328. OpenGLContext() throw();
  39329. };
  39330. /**
  39331. A component that contains an OpenGL canvas.
  39332. Override this, add it to whatever component you want to, and use the renderOpenGL()
  39333. method to draw its contents.
  39334. */
  39335. class JUCE_API OpenGLComponent : public Component
  39336. {
  39337. public:
  39338. /** Creates an OpenGLComponent.
  39339. */
  39340. OpenGLComponent();
  39341. /** Destructor. */
  39342. ~OpenGLComponent();
  39343. /** Changes the pixel format used by this component.
  39344. @see OpenGLPixelFormat::getAvailablePixelFormats()
  39345. */
  39346. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  39347. /** Returns the pixel format that this component is currently using. */
  39348. const OpenGLPixelFormat getPixelFormat() const;
  39349. /** Specifies an OpenGL context which should be shared with the one that this
  39350. component is using.
  39351. This is an OpenGL feature that lets two contexts share their texture data.
  39352. Note that this pointer is stored by the component, and when the component
  39353. needs to recreate its internal context for some reason, the same context
  39354. will be used again to share lists. So if you pass a context in here,
  39355. don't delete the context while this component is still using it! You can
  39356. call shareWith (0) to stop this component from sharing with it.
  39357. */
  39358. void shareWith (OpenGLContext* contextToShareListsWith);
  39359. /** Returns the context that this component is sharing with.
  39360. @see shareWith
  39361. */
  39362. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  39363. /** Flips the openGL buffers over. */
  39364. void swapBuffers();
  39365. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  39366. When this is called, makeCurrentContextActive() will already have been called
  39367. for you, so you just need to draw.
  39368. */
  39369. virtual void renderOpenGL() = 0;
  39370. /** This method is called when the component creates a new OpenGL context.
  39371. A new context may be created when the component is first used, or when it
  39372. is moved to a different window, or when the window is hidden and re-shown,
  39373. etc.
  39374. You can use this callback as an opportunity to set up things like textures
  39375. that your context needs.
  39376. New contexts are created on-demand by the makeCurrentContextActive() method - so
  39377. if the context is deleted, e.g. by changing the pixel format or window, no context
  39378. will be created until the next call to makeCurrentContextActive(), which will
  39379. synchronously create one and call this method. This means that if you're using
  39380. a non-GUI thread for rendering, you can make sure this method is be called by
  39381. your renderer thread.
  39382. When this callback happens, the context will already have been made current
  39383. using the makeCurrentContextActive() method, so there's no need to call it
  39384. again in your code.
  39385. */
  39386. virtual void newOpenGLContextCreated() = 0;
  39387. /** Returns the context that will draw into this component.
  39388. This may return 0 if the component is currently invisible or hasn't currently
  39389. got a context. The context object can be deleted and a new one created during
  39390. the lifetime of this component, and there may be times when it doesn't have one.
  39391. @see newOpenGLContextCreated()
  39392. */
  39393. OpenGLContext* getCurrentContext() const throw() { return context; }
  39394. /** Makes this component the current openGL context.
  39395. You might want to use this in things like your resize() method, before calling
  39396. GL commands.
  39397. If this returns false, then the context isn't active, so you should avoid
  39398. making any calls.
  39399. This call may actually create a context if one isn't currently initialised. If
  39400. it does this, it will also synchronously call the newOpenGLContextCreated()
  39401. method to let you initialise it as necessary.
  39402. @see OpenGLContext::makeActive
  39403. */
  39404. bool makeCurrentContextActive();
  39405. /** Stops the current component being the active OpenGL context.
  39406. This is the opposite of makeCurrentContextActive()
  39407. @see OpenGLContext::makeInactive
  39408. */
  39409. void makeCurrentContextInactive();
  39410. /** Returns true if this component is the active openGL context for the
  39411. current thread.
  39412. @see OpenGLContext::isActive
  39413. */
  39414. bool isActiveContext() const throw();
  39415. /** Calls the rendering callback, and swaps the buffers afterwards.
  39416. This is called automatically by paint() when the component needs to be rendered.
  39417. It can be overridden if you need to decouple the rendering from the paint callback
  39418. and render with a custom thread.
  39419. Returns true if the operation succeeded.
  39420. */
  39421. virtual bool renderAndSwapBuffers();
  39422. /** This returns a critical section that can be used to lock the current context.
  39423. Because the context that is used by this component can change, e.g. when the
  39424. component is shown or hidden, then if you're rendering to it on a background
  39425. thread, this allows you to lock the context for the duration of your rendering
  39426. routine.
  39427. */
  39428. CriticalSection& getContextLock() throw() { return contextLock; }
  39429. /** @internal */
  39430. void paint (Graphics& g);
  39431. /** Returns the native handle of an embedded heavyweight window, if there is one.
  39432. E.g. On windows, this will return the HWND of the sub-window containing
  39433. the opengl context, on the mac it'll be the NSOpenGLView.
  39434. */
  39435. void* getNativeWindowHandle() const;
  39436. juce_UseDebuggingNewOperator
  39437. private:
  39438. friend class OpenGLComponentWatcher;
  39439. OpenGLComponentWatcher* componentWatcher;
  39440. OpenGLContext* context;
  39441. OpenGLContext* contextToShareListsWith;
  39442. CriticalSection contextLock;
  39443. OpenGLPixelFormat preferredPixelFormat;
  39444. bool needToUpdateViewport;
  39445. void deleteContext();
  39446. void updateContextPosition();
  39447. void internalRepaint (int x, int y, int w, int h);
  39448. OpenGLComponent (const OpenGLComponent&);
  39449. const OpenGLComponent& operator= (const OpenGLComponent&);
  39450. };
  39451. #endif
  39452. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39453. /********* End of inlined file: juce_OpenGLComponent.h *********/
  39454. #endif
  39455. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39456. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  39457. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39458. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39459. /**
  39460. A component with a set of buttons at the top for changing between pages of
  39461. preferences.
  39462. This is just a handy way of writing a Mac-style preferences panel where you
  39463. have a row of buttons along the top for the different preference categories,
  39464. each button having an icon above its name. Clicking these will show an
  39465. appropriate prefs page below it.
  39466. You can either put one of these inside your own component, or just use the
  39467. showInDialogBox() method to show it in a window and run it modally.
  39468. To use it, just add a set of named pages with the addSettingsPage() method,
  39469. and implement the createComponentForPage() method to create suitable components
  39470. for each of these pages.
  39471. */
  39472. class JUCE_API PreferencesPanel : public Component,
  39473. private ButtonListener
  39474. {
  39475. public:
  39476. /** Creates an empty panel.
  39477. Use addSettingsPage() to add some pages to it in your constructor.
  39478. */
  39479. PreferencesPanel();
  39480. /** Destructor. */
  39481. ~PreferencesPanel();
  39482. /** Creates a page using a set of drawables to define the page's icon.
  39483. Note that the other version of this method is much easier if you're using
  39484. an image instead of a custom drawable.
  39485. @param pageTitle the name of this preferences page - you'll need to
  39486. make sure your createComponentForPage() method creates
  39487. a suitable component when it is passed this name
  39488. @param normalIcon the drawable to display in the page's button normally
  39489. @param overIcon the drawable to display in the page's button when the mouse is over
  39490. @param downIcon the drawable to display in the page's button when the button is down
  39491. @see DrawableButton
  39492. */
  39493. void addSettingsPage (const String& pageTitle,
  39494. const Drawable* normalIcon,
  39495. const Drawable* overIcon,
  39496. const Drawable* downIcon);
  39497. /** Creates a page using a set of drawables to define the page's icon.
  39498. The other version of this method gives you more control over the icon, but this
  39499. one is much easier if you're just loading it from a file.
  39500. @param pageTitle the name of this preferences page - you'll need to
  39501. make sure your createComponentForPage() method creates
  39502. a suitable component when it is passed this name
  39503. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  39504. For this to look good, you'll probably want to use a nice
  39505. transparent png file.
  39506. @param imageDataSize the size of the image data, in bytes
  39507. */
  39508. void addSettingsPage (const String& pageTitle,
  39509. const char* imageData,
  39510. const int imageDataSize);
  39511. /** Utility method to display this panel in a DialogWindow.
  39512. Calling this will create a DialogWindow containing this panel with the
  39513. given size and title, and will run it modally, returning when the user
  39514. closes the dialog box.
  39515. */
  39516. void showInDialogBox (const String& dialogtitle,
  39517. int dialogWidth,
  39518. int dialogHeight,
  39519. const Colour& backgroundColour = Colours::white);
  39520. /** Subclasses must override this to return a component for each preferences page.
  39521. The subclass should return a pointer to a new component representing the named
  39522. page, which the panel will then display.
  39523. The panel will delete the component later when the user goes to another page
  39524. or deletes the panel.
  39525. */
  39526. virtual Component* createComponentForPage (const String& pageName) = 0;
  39527. /** Changes the current page being displayed. */
  39528. void setCurrentPage (const String& pageName);
  39529. /** @internal */
  39530. void resized();
  39531. /** @internal */
  39532. void paint (Graphics& g);
  39533. /** @internal */
  39534. void buttonClicked (Button* button);
  39535. juce_UseDebuggingNewOperator
  39536. private:
  39537. String currentPageName;
  39538. Component* currentPage;
  39539. int buttonSize;
  39540. PreferencesPanel (const PreferencesPanel&);
  39541. const PreferencesPanel& operator= (const PreferencesPanel&);
  39542. };
  39543. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39544. /********* End of inlined file: juce_PreferencesPanel.h *********/
  39545. #endif
  39546. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39547. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  39548. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39549. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39550. // this is used to disable QuickTime, and is defined in juce_Config.h
  39551. #if JUCE_QUICKTIME || DOXYGEN
  39552. #if JUCE_WIN32
  39553. typedef ActiveXControlComponent QTCompBaseClass;
  39554. #else
  39555. typedef NSViewComponent QTCompBaseClass;
  39556. #endif
  39557. /**
  39558. A window that can play back a QuickTime movie.
  39559. */
  39560. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  39561. {
  39562. public:
  39563. /** Creates a QuickTimeMovieComponent, initially blank.
  39564. Use the loadMovie() method to load a movie once you've added the
  39565. component to a window, (or put it on the desktop as a heavyweight window).
  39566. Loading a movie when the component isn't visible can cause problems, as
  39567. QuickTime needs a window handle to initialise properly.
  39568. */
  39569. QuickTimeMovieComponent();
  39570. /** Destructor. */
  39571. ~QuickTimeMovieComponent();
  39572. /** Returns true if QT is installed and working on this machine.
  39573. */
  39574. static bool isQuickTimeAvailable() throw();
  39575. /** Tries to load a QuickTime movie into the player.
  39576. It's best to call this function once you've added the component to a window,
  39577. (or put it on the desktop as a heavyweight window). Loading a movie when the
  39578. component isn't visible can cause problems, because QuickTime needs a window
  39579. handle to do its stuff.
  39580. @param movieFile the .mov file to open
  39581. @param isControllerVisible whether to show a controller bar at the bottom
  39582. @returns true if the movie opens successfully
  39583. */
  39584. bool loadMovie (const File& movieFile,
  39585. const bool isControllerVisible);
  39586. bool loadMovie (InputStream* movieStream,
  39587. const bool isControllerVisible);
  39588. /** Closes the movie, if one is open. */
  39589. void closeMovie();
  39590. /** Returns the movie file that is currently open.
  39591. If there isn't one, this returns File::nonexistent
  39592. */
  39593. const File getCurrentMovieFile() const;
  39594. /** Returns true if there's currently a movie open. */
  39595. bool isMovieOpen() const;
  39596. /** Returns the length of the movie, in seconds. */
  39597. double getMovieDuration() const;
  39598. /** Returns the movie's natural size, in pixels.
  39599. You can use this to resize the component to show the movie at its preferred
  39600. scale.
  39601. If no movie is loaded, the size returned will be 0 x 0.
  39602. */
  39603. void getMovieNormalSize (int& width, int& height) const;
  39604. /** This will position the component within a given area, keeping its aspect
  39605. ratio correct according to the movie's normal size.
  39606. The component will be made as large as it can go within the space, and will
  39607. be aligned according to the justification value if this means there are gaps at
  39608. the top or sides.
  39609. */
  39610. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  39611. const RectanglePlacement& placement);
  39612. /** Starts the movie playing. */
  39613. void play();
  39614. /** Stops the movie playing. */
  39615. void stop();
  39616. /** Returns true if the movie is currently playing. */
  39617. bool isPlaying() const;
  39618. /** Moves the movie's position back to the start. */
  39619. void goToStart();
  39620. /** Sets the movie's position to a given time. */
  39621. void setPosition (const double seconds);
  39622. /** Returns the current play position of the movie. */
  39623. double getPosition() const;
  39624. /** Changes the movie playback rate.
  39625. A value of 1 is normal speed, greater values play it proportionately faster,
  39626. smaller values play it slower.
  39627. */
  39628. void setSpeed (const float newSpeed);
  39629. /** Changes the movie's playback volume.
  39630. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39631. */
  39632. void setMovieVolume (const float newVolume);
  39633. /** Returns the movie's playback volume.
  39634. @returns the volume in the range 0 (silent) to 1.0 (full)
  39635. */
  39636. float getMovieVolume() const;
  39637. /** Tells the movie whether it should loop. */
  39638. void setLooping (const bool shouldLoop);
  39639. /** Returns true if the movie is currently looping.
  39640. @see setLooping
  39641. */
  39642. bool isLooping() const;
  39643. /** True if the native QuickTime controller bar is shown in the window.
  39644. @see loadMovie
  39645. */
  39646. bool isControllerVisible() const;
  39647. /** @internal */
  39648. void paint (Graphics& g);
  39649. juce_UseDebuggingNewOperator
  39650. private:
  39651. File movieFile;
  39652. bool movieLoaded, controllerVisible, looping;
  39653. #if JUCE_WIN32
  39654. /** @internal */
  39655. void parentHierarchyChanged();
  39656. /** @internal */
  39657. void visibilityChanged();
  39658. void createControlIfNeeded();
  39659. bool isControlCreated() const;
  39660. void* internal;
  39661. #else
  39662. void* movie;
  39663. #endif
  39664. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39665. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39666. };
  39667. #endif
  39668. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39669. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39670. #endif
  39671. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39672. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  39673. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39674. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39675. #if JUCE_WIN32 || JUCE_LINUX
  39676. /**
  39677. On Windows only, this component sits in the taskbar tray as a small icon.
  39678. To use it, just create one of these components, but don't attempt to make it
  39679. visible, add it to a parent, or put it on the desktop.
  39680. You can then call setIconImage() to create an icon for it in the taskbar.
  39681. To change the icon's tooltip, you can use setIconTooltip().
  39682. To respond to mouse-events, you can override the normal mouseDown(),
  39683. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  39684. position will not be valid, you can use this to respond to clicks. Traditionally
  39685. you'd use a left-click to show your application's window, and a right-click
  39686. to show a pop-up menu.
  39687. */
  39688. class JUCE_API SystemTrayIconComponent : public Component
  39689. {
  39690. public:
  39691. SystemTrayIconComponent();
  39692. /** Destructor. */
  39693. ~SystemTrayIconComponent();
  39694. /** Changes the image shown in the taskbar.
  39695. */
  39696. void setIconImage (const Image& newImage);
  39697. /** Changes the tooltip that Windows shows above the icon. */
  39698. void setIconTooltip (const String& tooltip);
  39699. #if JUCE_LINUX
  39700. /** @internal */
  39701. void paint (Graphics& g);
  39702. #endif
  39703. juce_UseDebuggingNewOperator
  39704. private:
  39705. SystemTrayIconComponent (const SystemTrayIconComponent&);
  39706. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  39707. };
  39708. #endif
  39709. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39710. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  39711. #endif
  39712. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39713. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  39714. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39715. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39716. #if JUCE_WEB_BROWSER
  39717. class WebBrowserComponentInternal;
  39718. /**
  39719. A component that displays an embedded web browser.
  39720. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  39721. Windows, probably IE.
  39722. */
  39723. class WebBrowserComponent : public Component
  39724. {
  39725. public:
  39726. /** Creates a WebBrowserComponent.
  39727. Once it's created and visible, send the browser to a URL using goToURL().
  39728. */
  39729. WebBrowserComponent();
  39730. /** Destructor. */
  39731. ~WebBrowserComponent();
  39732. /** Sends the browser to a particular URL.
  39733. @param url the URL to go to.
  39734. @param headers an optional set of parameters to put in the HTTP header. If
  39735. you supply this, it should be a set of string in the form
  39736. "HeaderKey: HeaderValue"
  39737. @param postData an optional block of data that will be attached to the HTTP
  39738. POST request
  39739. */
  39740. void goToURL (const String& url,
  39741. const StringArray* headers = 0,
  39742. const MemoryBlock* postData = 0);
  39743. /** Stops the current page loading.
  39744. */
  39745. void stop();
  39746. /** Sends the browser back one page.
  39747. */
  39748. void goBack();
  39749. /** Sends the browser forward one page.
  39750. */
  39751. void goForward();
  39752. /** Refreshes the browser.
  39753. */
  39754. void refresh();
  39755. /** This callback is called when the browser is about to navigate
  39756. to a new location.
  39757. You can override this method to perform some action when the user
  39758. tries to go to a particular URL. To allow the operation to carry on,
  39759. return true, or return false to stop the navigation happening.
  39760. */
  39761. virtual bool pageAboutToLoad (const String& newURL);
  39762. /** @internal */
  39763. void paint (Graphics& g);
  39764. /** @internal */
  39765. void resized();
  39766. /** @internal */
  39767. void parentHierarchyChanged();
  39768. /** @internal */
  39769. void visibilityChanged();
  39770. juce_UseDebuggingNewOperator
  39771. private:
  39772. WebBrowserComponentInternal* browser;
  39773. bool blankPageShown;
  39774. String lastURL;
  39775. StringArray lastHeaders;
  39776. MemoryBlock lastPostData;
  39777. void reloadLastURL();
  39778. void checkWindowAssociation();
  39779. WebBrowserComponent (const WebBrowserComponent&);
  39780. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  39781. };
  39782. #endif
  39783. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39784. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  39785. #endif
  39786. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39787. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39788. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39789. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39790. class ToggleButton;
  39791. class TextButton;
  39792. class AlertWindow;
  39793. class TextLayout;
  39794. class ScrollBar;
  39795. class BubbleComponent;
  39796. class ComboBox;
  39797. class Button;
  39798. class FilenameComponent;
  39799. class DocumentWindow;
  39800. class ResizableWindow;
  39801. class GroupComponent;
  39802. class MenuBarComponent;
  39803. class DropShadower;
  39804. class GlyphArrangement;
  39805. class PropertyComponent;
  39806. class TableHeaderComponent;
  39807. class Toolbar;
  39808. class ToolbarItemComponent;
  39809. class PopupMenu;
  39810. class ProgressBar;
  39811. class FileBrowserComponent;
  39812. class DirectoryContentsDisplayComponent;
  39813. class FilePreviewComponent;
  39814. class ImageButton;
  39815. /**
  39816. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39817. can be used to apply different 'skins' to the application.
  39818. */
  39819. class JUCE_API LookAndFeel
  39820. {
  39821. public:
  39822. /** Creates the default JUCE look and feel. */
  39823. LookAndFeel();
  39824. /** Destructor. */
  39825. virtual ~LookAndFeel();
  39826. /** Returns the current default look-and-feel for a component to use when it
  39827. hasn't got one explicitly set.
  39828. @see setDefaultLookAndFeel
  39829. */
  39830. static LookAndFeel& getDefaultLookAndFeel() throw();
  39831. /** Changes the default look-and-feel.
  39832. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39833. set to 0, it will revert to using the default one. The
  39834. object passed-in must be deleted by the caller when
  39835. it's no longer needed.
  39836. @see getDefaultLookAndFeel
  39837. */
  39838. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39839. /** Looks for a colour that has been registered with the given colour ID number.
  39840. If a colour has been set for this ID number using setColour(), then it is
  39841. returned. If none has been set, it will just return Colours::black.
  39842. The colour IDs for various purposes are stored as enums in the components that
  39843. they are relevent to - for an example, see Slider::ColourIds,
  39844. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39845. If you're looking up a colour for use in drawing a component, it's usually
  39846. best not to call this directly, but to use the Component::findColour() method
  39847. instead. That will first check whether a suitable colour has been registered
  39848. directly with the component, and will fall-back on calling the component's
  39849. LookAndFeel's findColour() method if none is found.
  39850. @see setColour, Component::findColour, Component::setColour
  39851. */
  39852. const Colour findColour (const int colourId) const throw();
  39853. /** Registers a colour to be used for a particular purpose.
  39854. For more details, see the comments for findColour().
  39855. @see findColour, Component::findColour, Component::setColour
  39856. */
  39857. void setColour (const int colourId, const Colour& colour) throw();
  39858. /** Returns true if the specified colour ID has been explicitly set using the
  39859. setColour() method.
  39860. */
  39861. bool isColourSpecified (const int colourId) const throw();
  39862. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  39863. /** Allows you to change the default sans-serif font.
  39864. If you need to supply your own Typeface object for any of the default fonts, rather
  39865. than just supplying the name (e.g. if you want to use an embedded font), then
  39866. you should instead override getTypefaceForFont() to create and return the typeface.
  39867. */
  39868. void setDefaultSansSerifTypefaceName (const String& newName);
  39869. /** Draws the lozenge-shaped background for a standard button. */
  39870. virtual void drawButtonBackground (Graphics& g,
  39871. Button& button,
  39872. const Colour& backgroundColour,
  39873. bool isMouseOverButton,
  39874. bool isButtonDown);
  39875. /** Draws the text for a TextButton. */
  39876. virtual void drawButtonText (Graphics& g,
  39877. TextButton& button,
  39878. bool isMouseOverButton,
  39879. bool isButtonDown);
  39880. /** Draws the contents of a standard ToggleButton. */
  39881. virtual void drawToggleButton (Graphics& g,
  39882. ToggleButton& button,
  39883. bool isMouseOverButton,
  39884. bool isButtonDown);
  39885. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39886. virtual void drawTickBox (Graphics& g,
  39887. Component& component,
  39888. int x, int y, int w, int h,
  39889. const bool ticked,
  39890. const bool isEnabled,
  39891. const bool isMouseOverButton,
  39892. const bool isButtonDown);
  39893. /** AlertWindow handling..
  39894. */
  39895. virtual AlertWindow* createAlertWindow (const String& title,
  39896. const String& message,
  39897. const String& button1,
  39898. const String& button2,
  39899. const String& button3,
  39900. AlertWindow::AlertIconType iconType,
  39901. int numButtons,
  39902. Component* associatedComponent);
  39903. virtual void drawAlertBox (Graphics& g,
  39904. AlertWindow& alert,
  39905. const Rectangle& textArea,
  39906. TextLayout& textLayout);
  39907. virtual int getAlertBoxWindowFlags();
  39908. virtual int getAlertWindowButtonHeight();
  39909. virtual const Font getAlertWindowFont();
  39910. /** Draws a progress bar.
  39911. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39912. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39913. isn't known). It can use the current time as a basis for playing an animation.
  39914. (Used by progress bars in AlertWindow).
  39915. */
  39916. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39917. int width, int height,
  39918. double progress, const String& textToShow);
  39919. /** Draws one of the buttons on a scrollbar.
  39920. @param g the context to draw into
  39921. @param scrollbar the bar itself
  39922. @param width the width of the button
  39923. @param height the height of the button
  39924. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39925. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39926. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39927. @param isButtonDown whether the mouse button's held down
  39928. */
  39929. virtual void drawScrollbarButton (Graphics& g,
  39930. ScrollBar& scrollbar,
  39931. int width, int height,
  39932. int buttonDirection,
  39933. bool isScrollbarVertical,
  39934. bool isMouseOverButton,
  39935. bool isButtonDown);
  39936. /** Draws the thumb area of a scrollbar.
  39937. @param g the context to draw into
  39938. @param scrollbar the bar itself
  39939. @param x the x position of the left edge of the thumb area to draw in
  39940. @param y the y position of the top edge of the thumb area to draw in
  39941. @param width the width of the thumb area to draw in
  39942. @param height the height of the thumb area to draw in
  39943. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39944. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39945. thumb, or its x position for horizontal bars
  39946. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39947. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39948. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39949. currently dragging the thumb
  39950. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39951. */
  39952. virtual void drawScrollbar (Graphics& g,
  39953. ScrollBar& scrollbar,
  39954. int x, int y,
  39955. int width, int height,
  39956. bool isScrollbarVertical,
  39957. int thumbStartPosition,
  39958. int thumbSize,
  39959. bool isMouseOver,
  39960. bool isMouseDown);
  39961. /** Returns the component effect to use for a scrollbar */
  39962. virtual ImageEffectFilter* getScrollbarEffect();
  39963. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39964. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39965. /** Returns the default thickness to use for a scrollbar. */
  39966. virtual int getDefaultScrollbarWidth();
  39967. /** Returns the length in pixels to use for a scrollbar button. */
  39968. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39969. /** Returns a tick shape for use in yes/no boxes, etc. */
  39970. virtual const Path getTickShape (const float height);
  39971. /** Returns a cross shape for use in yes/no boxes, etc. */
  39972. virtual const Path getCrossShape (const float height);
  39973. /** Draws the + or - box in a treeview. */
  39974. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  39975. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39976. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39977. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39978. virtual Image* getDefaultFolderImage();
  39979. virtual Image* getDefaultDocumentFileImage();
  39980. virtual void createFileChooserHeaderText (const String& title,
  39981. const String& instructions,
  39982. GlyphArrangement& destArrangement,
  39983. int width);
  39984. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39985. const String& filename, Image* icon,
  39986. const String& fileSizeDescription,
  39987. const String& fileTimeDescription,
  39988. const bool isDirectory,
  39989. const bool isItemSelected,
  39990. const int itemIndex);
  39991. virtual Button* createFileBrowserGoUpButton();
  39992. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39993. DirectoryContentsDisplayComponent* fileListComponent,
  39994. FilePreviewComponent* previewComp,
  39995. ComboBox* currentPathBox,
  39996. TextEditor* filenameBox,
  39997. Button* goUpButton);
  39998. virtual void drawBubble (Graphics& g,
  39999. float tipX, float tipY,
  40000. float boxX, float boxY, float boxW, float boxH);
  40001. /** Fills the background of a popup menu component. */
  40002. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40003. /** Draws one of the items in a popup menu. */
  40004. virtual void drawPopupMenuItem (Graphics& g,
  40005. int width, int height,
  40006. const bool isSeparator,
  40007. const bool isActive,
  40008. const bool isHighlighted,
  40009. const bool isTicked,
  40010. const bool hasSubMenu,
  40011. const String& text,
  40012. const String& shortcutKeyText,
  40013. Image* image,
  40014. const Colour* const textColour);
  40015. /** Returns the size and style of font to use in popup menus. */
  40016. virtual const Font getPopupMenuFont();
  40017. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40018. int width, int height,
  40019. bool isScrollUpArrow);
  40020. /** Finds the best size for an item in a popup menu. */
  40021. virtual void getIdealPopupMenuItemSize (const String& text,
  40022. const bool isSeparator,
  40023. int standardMenuItemHeight,
  40024. int& idealWidth,
  40025. int& idealHeight);
  40026. virtual int getMenuWindowFlags();
  40027. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40028. bool isMouseOverBar,
  40029. MenuBarComponent& menuBar);
  40030. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40031. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40032. virtual void drawMenuBarItem (Graphics& g,
  40033. int width, int height,
  40034. int itemIndex,
  40035. const String& itemText,
  40036. bool isMouseOverItem,
  40037. bool isMenuOpen,
  40038. bool isMouseOverBar,
  40039. MenuBarComponent& menuBar);
  40040. virtual void drawComboBox (Graphics& g, int width, int height,
  40041. const bool isButtonDown,
  40042. int buttonX, int buttonY,
  40043. int buttonW, int buttonH,
  40044. ComboBox& box);
  40045. virtual const Font getComboBoxFont (ComboBox& box);
  40046. virtual Label* createComboBoxTextBox (ComboBox& box);
  40047. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40048. virtual void drawLabel (Graphics& g, Label& label);
  40049. virtual void drawLinearSlider (Graphics& g,
  40050. int x, int y,
  40051. int width, int height,
  40052. float sliderPos,
  40053. float minSliderPos,
  40054. float maxSliderPos,
  40055. const Slider::SliderStyle style,
  40056. Slider& slider);
  40057. virtual void drawLinearSliderBackground (Graphics& g,
  40058. int x, int y,
  40059. int width, int height,
  40060. float sliderPos,
  40061. float minSliderPos,
  40062. float maxSliderPos,
  40063. const Slider::SliderStyle style,
  40064. Slider& slider);
  40065. virtual void drawLinearSliderThumb (Graphics& g,
  40066. int x, int y,
  40067. int width, int height,
  40068. float sliderPos,
  40069. float minSliderPos,
  40070. float maxSliderPos,
  40071. const Slider::SliderStyle style,
  40072. Slider& slider);
  40073. virtual int getSliderThumbRadius (Slider& slider);
  40074. virtual void drawRotarySlider (Graphics& g,
  40075. int x, int y,
  40076. int width, int height,
  40077. float sliderPosProportional,
  40078. const float rotaryStartAngle,
  40079. const float rotaryEndAngle,
  40080. Slider& slider);
  40081. virtual Button* createSliderButton (const bool isIncrement);
  40082. virtual Label* createSliderTextBox (Slider& slider);
  40083. virtual ImageEffectFilter* getSliderEffect();
  40084. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40085. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40086. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40087. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40088. ComboBox* filenameBox, Button* browseButton);
  40089. virtual void drawCornerResizer (Graphics& g,
  40090. int w, int h,
  40091. bool isMouseOver,
  40092. bool isMouseDragging);
  40093. virtual void drawResizableFrame (Graphics& g,
  40094. int w, int h,
  40095. const BorderSize& borders);
  40096. virtual void drawResizableWindowBorder (Graphics& g,
  40097. int w, int h,
  40098. const BorderSize& border,
  40099. ResizableWindow& window);
  40100. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40101. Graphics& g, int w, int h,
  40102. int titleSpaceX, int titleSpaceW,
  40103. const Image* icon,
  40104. bool drawTitleTextOnLeft);
  40105. virtual Button* createDocumentWindowButton (int buttonType);
  40106. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40107. int titleBarX, int titleBarY,
  40108. int titleBarW, int titleBarH,
  40109. Button* minimiseButton,
  40110. Button* maximiseButton,
  40111. Button* closeButton,
  40112. bool positionTitleBarButtonsOnLeft);
  40113. virtual int getDefaultMenuBarHeight();
  40114. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40115. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40116. int w, int h,
  40117. bool isVerticalBar,
  40118. bool isMouseOver,
  40119. bool isMouseDragging);
  40120. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40121. const String& text,
  40122. const Justification& position,
  40123. GroupComponent& group);
  40124. virtual void createTabButtonShape (Path& p,
  40125. int width, int height,
  40126. int tabIndex,
  40127. const String& text,
  40128. Button& button,
  40129. TabbedButtonBar::Orientation orientation,
  40130. const bool isMouseOver,
  40131. const bool isMouseDown,
  40132. const bool isFrontTab);
  40133. virtual void fillTabButtonShape (Graphics& g,
  40134. const Path& path,
  40135. const Colour& preferredBackgroundColour,
  40136. int tabIndex,
  40137. const String& text,
  40138. Button& button,
  40139. TabbedButtonBar::Orientation orientation,
  40140. const bool isMouseOver,
  40141. const bool isMouseDown,
  40142. const bool isFrontTab);
  40143. virtual void drawTabButtonText (Graphics& g,
  40144. int x, int y, int w, int h,
  40145. const Colour& preferredBackgroundColour,
  40146. int tabIndex,
  40147. const String& text,
  40148. Button& button,
  40149. TabbedButtonBar::Orientation orientation,
  40150. const bool isMouseOver,
  40151. const bool isMouseDown,
  40152. const bool isFrontTab);
  40153. virtual int getTabButtonOverlap (int tabDepth);
  40154. virtual int getTabButtonSpaceAroundImage();
  40155. virtual int getTabButtonBestWidth (int tabIndex,
  40156. const String& text,
  40157. int tabDepth,
  40158. Button& button);
  40159. virtual void drawTabButton (Graphics& g,
  40160. int w, int h,
  40161. const Colour& preferredColour,
  40162. int tabIndex,
  40163. const String& text,
  40164. Button& button,
  40165. TabbedButtonBar::Orientation orientation,
  40166. const bool isMouseOver,
  40167. const bool isMouseDown,
  40168. const bool isFrontTab);
  40169. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40170. int w, int h,
  40171. TabbedButtonBar& tabBar,
  40172. TabbedButtonBar::Orientation orientation);
  40173. virtual Button* createTabBarExtrasButton();
  40174. virtual void drawImageButton (Graphics& g, Image* image,
  40175. int imageX, int imageY, int imageW, int imageH,
  40176. const Colour& overlayColour,
  40177. float imageOpacity,
  40178. ImageButton& button);
  40179. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40180. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40181. int width, int height,
  40182. bool isMouseOver, bool isMouseDown,
  40183. int columnFlags);
  40184. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40185. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40186. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40187. bool isMouseOver, bool isMouseDown,
  40188. ToolbarItemComponent& component);
  40189. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40190. const String& text, ToolbarItemComponent& component);
  40191. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40192. bool isOpen, int width, int height);
  40193. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40194. PropertyComponent& component);
  40195. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40196. PropertyComponent& component);
  40197. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  40198. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40199. /**
  40200. */
  40201. virtual void playAlertSound();
  40202. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40203. static void drawGlassSphere (Graphics& g,
  40204. const float x, const float y,
  40205. const float diameter,
  40206. const Colour& colour,
  40207. const float outlineThickness) throw();
  40208. static void drawGlassPointer (Graphics& g,
  40209. const float x, const float y,
  40210. const float diameter,
  40211. const Colour& colour, const float outlineThickness,
  40212. const int direction) throw();
  40213. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40214. static void drawGlassLozenge (Graphics& g,
  40215. const float x, const float y,
  40216. const float width, const float height,
  40217. const Colour& colour,
  40218. const float outlineThickness,
  40219. const float cornerSize,
  40220. const bool flatOnLeft, const bool flatOnRight,
  40221. const bool flatOnTop, const bool flatOnBottom) throw();
  40222. juce_UseDebuggingNewOperator
  40223. protected:
  40224. // xxx the following methods are only here to cause a compiler error, because they've been
  40225. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  40226. // error if you try to build a subclass with the old versions.
  40227. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  40228. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  40229. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  40230. virtual void getTabButtonBestWidth (int, const String&, int) {}
  40231. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  40232. private:
  40233. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40234. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40235. Array <int> colourIds;
  40236. Array <Colour> colours;
  40237. // default typeface names
  40238. String defaultSans, defaultSerif, defaultFixed;
  40239. void drawShinyButtonShape (Graphics& g,
  40240. float x, float y, float w, float h, float maxCornerSize,
  40241. const Colour& baseColour,
  40242. const float strokeWidth,
  40243. const bool flatOnLeft,
  40244. const bool flatOnRight,
  40245. const bool flatOnTop,
  40246. const bool flatOnBottom) throw();
  40247. LookAndFeel (const LookAndFeel&);
  40248. const LookAndFeel& operator= (const LookAndFeel&);
  40249. };
  40250. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40251. /********* End of inlined file: juce_LookAndFeel.h *********/
  40252. #endif
  40253. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40254. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40255. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40256. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40257. /**
  40258. The original Juce look-and-feel.
  40259. */
  40260. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40261. {
  40262. public:
  40263. /** Creates the default JUCE look and feel. */
  40264. OldSchoolLookAndFeel();
  40265. /** Destructor. */
  40266. virtual ~OldSchoolLookAndFeel();
  40267. /** Draws the lozenge-shaped background for a standard button. */
  40268. virtual void drawButtonBackground (Graphics& g,
  40269. Button& button,
  40270. const Colour& backgroundColour,
  40271. bool isMouseOverButton,
  40272. bool isButtonDown);
  40273. /** Draws the contents of a standard ToggleButton. */
  40274. virtual void drawToggleButton (Graphics& g,
  40275. ToggleButton& button,
  40276. bool isMouseOverButton,
  40277. bool isButtonDown);
  40278. virtual void drawTickBox (Graphics& g,
  40279. Component& component,
  40280. int x, int y, int w, int h,
  40281. const bool ticked,
  40282. const bool isEnabled,
  40283. const bool isMouseOverButton,
  40284. const bool isButtonDown);
  40285. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40286. int width, int height,
  40287. double progress, const String& textToShow);
  40288. virtual void drawScrollbarButton (Graphics& g,
  40289. ScrollBar& scrollbar,
  40290. int width, int height,
  40291. int buttonDirection,
  40292. bool isScrollbarVertical,
  40293. bool isMouseOverButton,
  40294. bool isButtonDown);
  40295. virtual void drawScrollbar (Graphics& g,
  40296. ScrollBar& scrollbar,
  40297. int x, int y,
  40298. int width, int height,
  40299. bool isScrollbarVertical,
  40300. int thumbStartPosition,
  40301. int thumbSize,
  40302. bool isMouseOver,
  40303. bool isMouseDown);
  40304. virtual ImageEffectFilter* getScrollbarEffect();
  40305. virtual void drawTextEditorOutline (Graphics& g,
  40306. int width, int height,
  40307. TextEditor& textEditor);
  40308. /** Fills the background of a popup menu component. */
  40309. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40310. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40311. bool isMouseOverBar,
  40312. MenuBarComponent& menuBar);
  40313. virtual void drawComboBox (Graphics& g, int width, int height,
  40314. const bool isButtonDown,
  40315. int buttonX, int buttonY,
  40316. int buttonW, int buttonH,
  40317. ComboBox& box);
  40318. virtual const Font getComboBoxFont (ComboBox& box);
  40319. virtual void drawLinearSlider (Graphics& g,
  40320. int x, int y,
  40321. int width, int height,
  40322. float sliderPos,
  40323. float minSliderPos,
  40324. float maxSliderPos,
  40325. const Slider::SliderStyle style,
  40326. Slider& slider);
  40327. virtual int getSliderThumbRadius (Slider& slider);
  40328. virtual Button* createSliderButton (const bool isIncrement);
  40329. virtual ImageEffectFilter* getSliderEffect();
  40330. virtual void drawCornerResizer (Graphics& g,
  40331. int w, int h,
  40332. bool isMouseOver,
  40333. bool isMouseDragging);
  40334. virtual Button* createDocumentWindowButton (int buttonType);
  40335. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40336. int titleBarX, int titleBarY,
  40337. int titleBarW, int titleBarH,
  40338. Button* minimiseButton,
  40339. Button* maximiseButton,
  40340. Button* closeButton,
  40341. bool positionTitleBarButtonsOnLeft);
  40342. juce_UseDebuggingNewOperator
  40343. private:
  40344. DropShadowEffect scrollbarShadow;
  40345. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40346. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40347. };
  40348. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40349. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40350. #endif
  40351. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40352. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  40353. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40354. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40355. /**
  40356. A class to take care of the logic involved with the loading/saving of some kind
  40357. of document.
  40358. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  40359. functions you need for documents that get saved to a file, so this class attempts
  40360. to abstract most of the boring stuff.
  40361. Your subclass should just implement all the pure virtual methods, and you can
  40362. then use the higher-level public methods to do the load/save dialogs, to warn the user
  40363. about overwriting files, etc.
  40364. The document object keeps track of whether it has changed since it was last saved or
  40365. loaded, so when you change something, call its changed() method. This will set a
  40366. flag so it knows it needs saving, and will also broadcast a change message using the
  40367. ChangeBroadcaster base class.
  40368. @see ChangeBroadcaster
  40369. */
  40370. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  40371. {
  40372. public:
  40373. /** Creates a FileBasedDocument.
  40374. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  40375. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  40376. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  40377. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  40378. */
  40379. FileBasedDocument (const String& fileExtension,
  40380. const String& fileWildCard,
  40381. const String& openFileDialogTitle,
  40382. const String& saveFileDialogTitle);
  40383. /** Destructor. */
  40384. virtual ~FileBasedDocument();
  40385. /** Returns true if the changed() method has been called since the file was
  40386. last saved or loaded.
  40387. @see resetChangedFlag, changed
  40388. */
  40389. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  40390. /** Called to indicate that the document has changed and needs saving.
  40391. This method will also trigger a change message to be sent out using the
  40392. ChangeBroadcaster base class.
  40393. After calling the method, the hasChangedSinceSaved() method will return true, until
  40394. it is reset either by saving to a file or using the resetChangedFlag() method.
  40395. @see hasChangedSinceSaved, resetChangedFlag
  40396. */
  40397. virtual void changed();
  40398. /** Sets the state of the 'changed' flag.
  40399. The 'changed' flag is set to true when the changed() method is called - use this method
  40400. to reset it or to set it without also broadcasting a change message.
  40401. @see changed, hasChangedSinceSaved
  40402. */
  40403. void setChangedFlag (const bool hasChanged);
  40404. /** Tries to open a file.
  40405. If the file opens correctly, the document's file (see the getFile() method) is set
  40406. to this new one; if it fails, the document's file is left unchanged, and optionally
  40407. a message box is shown telling the user there was an error.
  40408. @returns true if the new file loaded successfully
  40409. @see loadDocument, loadFromUserSpecifiedFile
  40410. */
  40411. bool loadFrom (const File& fileToLoadFrom,
  40412. const bool showMessageOnFailure);
  40413. /** Asks the user for a file and tries to load it.
  40414. This will pop up a dialog box using the title, file extension and
  40415. wildcard specified in the document's constructor, and asks the user
  40416. for a file. If they pick one, the loadFrom() method is used to
  40417. try to load it, optionally showing a message if it fails.
  40418. @returns true if a file was loaded; false if the user cancelled or if they
  40419. picked a file which failed to load correctly
  40420. @see loadFrom
  40421. */
  40422. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  40423. /** A set of possible outcomes of one of the save() methods
  40424. */
  40425. enum SaveResult
  40426. {
  40427. savedOk = 0, /**< indicates that a file was saved successfully. */
  40428. userCancelledSave, /**< indicates that the user aborted the save operation. */
  40429. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  40430. };
  40431. /** Tries to save the document to the last file it was saved or loaded from.
  40432. This will always try to write to the file, even if the document isn't flagged as
  40433. having changed.
  40434. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  40435. true, it will prompt the user to pick a file, as if
  40436. saveAsInteractive() was called.
  40437. @param showMessageOnFailure if true it will show a warning message when if the
  40438. save operation fails
  40439. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  40440. */
  40441. SaveResult save (const bool askUserForFileIfNotSpecified,
  40442. const bool showMessageOnFailure);
  40443. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  40444. it if they say yes.
  40445. If you've got a document open and want to close it (e.g. to quit the app), this is the
  40446. method to call.
  40447. If the document doesn't need saving it'll return the value savedOk so
  40448. you can go ahead and delete the document.
  40449. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  40450. return savedOk, so again, you can safely delete the document.
  40451. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  40452. close-document operation.
  40453. And if they click "save changes", it'll try to save and either return savedOk, or
  40454. failedToWriteToFile if there was a problem.
  40455. @see save, saveAs, saveAsInteractive
  40456. */
  40457. SaveResult saveIfNeededAndUserAgrees();
  40458. /** Tries to save the document to a specified file.
  40459. If this succeeds, it'll also change the document's internal file (as returned by
  40460. the getFile() method). If it fails, the file will be left unchanged.
  40461. @param newFile the file to try to write to
  40462. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  40463. the user first if they want to overwrite it
  40464. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  40465. use the saveAsInteractive() method to ask the user for a
  40466. filename
  40467. @param showMessageOnFailure if true and the write operation fails, it'll show
  40468. a message box to warn the user
  40469. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  40470. */
  40471. SaveResult saveAs (const File& newFile,
  40472. const bool warnAboutOverwritingExistingFiles,
  40473. const bool askUserForFileIfNotSpecified,
  40474. const bool showMessageOnFailure);
  40475. /** Prompts the user for a filename and tries to save to it.
  40476. This will pop up a dialog box using the title, file extension and
  40477. wildcard specified in the document's constructor, and asks the user
  40478. for a file. If they pick one, the saveAs() method is used to try to save
  40479. to this file.
  40480. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  40481. the user first if they want to overwrite it
  40482. @see saveIfNeededAndUserAgrees, save, saveAs
  40483. */
  40484. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  40485. /** Returns the file that this document was last successfully saved or loaded from.
  40486. When the document object is created, this will be set to File::nonexistent.
  40487. It is changed when one of the load or save methods is used, or when setFile()
  40488. is used to explicitly set it.
  40489. */
  40490. const File getFile() const throw() { return documentFile; }
  40491. /** Sets the file that this document thinks it was loaded from.
  40492. This won't actually load anything - it just changes the file stored internally.
  40493. @see getFile
  40494. */
  40495. void setFile (const File& newFile);
  40496. protected:
  40497. /** Overload this to return the title of the document.
  40498. This is used in message boxes, filenames and file choosers, so it should be
  40499. something sensible.
  40500. */
  40501. virtual const String getDocumentTitle() = 0;
  40502. /** This method should try to load your document from the given file.
  40503. If it fails, it should return an error message. If it succeeds, it should return
  40504. an empty string.
  40505. */
  40506. virtual const String loadDocument (const File& file) = 0;
  40507. /** This method should try to write your document to the given file.
  40508. If it fails, it should return an error message. If it succeeds, it should return
  40509. an empty string.
  40510. */
  40511. virtual const String saveDocument (const File& file) = 0;
  40512. /** This is used for dialog boxes to make them open at the last folder you
  40513. were using.
  40514. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  40515. the last document that was used - you might want to store this value
  40516. in a static variable, or even in your application's properties. It should
  40517. be a global setting rather than a property of this object.
  40518. This method works very well in conjunction with a RecentlyOpenedFilesList
  40519. object to manage your recent-files list.
  40520. As a default value, it's ok to return File::nonexistent, and the document
  40521. object will use a sensible one instead.
  40522. @see RecentlyOpenedFilesList
  40523. */
  40524. virtual const File getLastDocumentOpened() = 0;
  40525. /** This is used for dialog boxes to make them open at the last folder you
  40526. were using.
  40527. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  40528. the last document that was used - you might want to store this value
  40529. in a static variable, or even in your application's properties. It should
  40530. be a global setting rather than a property of this object.
  40531. This method works very well in conjunction with a RecentlyOpenedFilesList
  40532. object to manage your recent-files list.
  40533. @see RecentlyOpenedFilesList
  40534. */
  40535. virtual void setLastDocumentOpened (const File& file) = 0;
  40536. public:
  40537. juce_UseDebuggingNewOperator
  40538. private:
  40539. File documentFile;
  40540. bool changedSinceSave;
  40541. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  40542. FileBasedDocument (const FileBasedDocument&);
  40543. const FileBasedDocument& operator= (const FileBasedDocument&);
  40544. };
  40545. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40546. /********* End of inlined file: juce_FileBasedDocument.h *********/
  40547. #endif
  40548. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40549. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40550. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40551. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40552. /**
  40553. Manages a set of files for use as a list of recently-opened documents.
  40554. This is a handy class for holding your list of recently-opened documents, with
  40555. helpful methods for things like purging any non-existent files, automatically
  40556. adding them to a menu, and making persistence easy.
  40557. @see File, FileBasedDocument
  40558. */
  40559. class JUCE_API RecentlyOpenedFilesList
  40560. {
  40561. public:
  40562. /** Creates an empty list.
  40563. */
  40564. RecentlyOpenedFilesList();
  40565. /** Destructor. */
  40566. ~RecentlyOpenedFilesList();
  40567. /** Sets a limit for the number of files that will be stored in the list.
  40568. When addFile() is called, then if there is no more space in the list, the
  40569. least-recently added file will be dropped.
  40570. @see getMaxNumberOfItems
  40571. */
  40572. void setMaxNumberOfItems (const int newMaxNumber);
  40573. /** Returns the number of items that this list will store.
  40574. @see setMaxNumberOfItems
  40575. */
  40576. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  40577. /** Returns the number of files in the list.
  40578. The most recently added file is always at index 0.
  40579. */
  40580. int getNumFiles() const;
  40581. /** Returns one of the files in the list.
  40582. The most recently added file is always at index 0.
  40583. */
  40584. const File getFile (const int index) const;
  40585. /** Returns an array of all the absolute pathnames in the list.
  40586. */
  40587. const StringArray& getAllFilenames() const throw() { return files; }
  40588. /** Clears all the files from the list. */
  40589. void clear();
  40590. /** Adds a file to the list.
  40591. The file will be added at index 0. If this file is already in the list, it will
  40592. be moved up to index 0, but a file can only appear once in the list.
  40593. If the list already contains the maximum number of items that is permitted, the
  40594. least-recently added file will be dropped from the end.
  40595. */
  40596. void addFile (const File& file);
  40597. /** Checks each of the files in the list, removing any that don't exist.
  40598. You might want to call this after reloading a list of files, or before putting them
  40599. on a menu.
  40600. */
  40601. void removeNonExistentFiles();
  40602. /** Adds entries to a menu, representing each of the files in the list.
  40603. This is handy for creating an "open recent file..." menu in your app. The
  40604. menu items are numbered consecutively starting with the baseItemId value,
  40605. and can either be added as complete pathnames, or just the last part of the
  40606. filename.
  40607. If dontAddNonExistentFiles is true, then each file will be checked and only those
  40608. that exist will be added.
  40609. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  40610. pointers to file objects. Any files that appear in this list will not be added to the
  40611. menu - the reason for this is that you might have a number of files already open, so
  40612. might not want these to be shown in the menu.
  40613. It returns the number of items that were added.
  40614. */
  40615. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  40616. const int baseItemId,
  40617. const bool showFullPaths,
  40618. const bool dontAddNonExistentFiles,
  40619. const File** filesToAvoid = 0);
  40620. /** Returns a string that encapsulates all the files in the list.
  40621. The string that is returned can later be passed into restoreFromString() in
  40622. order to recreate the list. This is handy for persisting your list, e.g. in
  40623. a PropertiesFile object.
  40624. @see restoreFromString
  40625. */
  40626. const String toString() const;
  40627. /** Restores the list from a previously stringified version of the list.
  40628. Pass in a stringified version created with toString() in order to persist/restore
  40629. your list.
  40630. @see toString
  40631. */
  40632. void restoreFromString (const String& stringifiedVersion);
  40633. juce_UseDebuggingNewOperator
  40634. private:
  40635. StringArray files;
  40636. int maxNumberOfItems;
  40637. };
  40638. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40639. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40640. #endif
  40641. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40642. #endif
  40643. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  40644. #endif
  40645. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40646. #endif
  40647. #endif // __JUCE_APP_INCLUDES_JUCEHEADER__
  40648. /********* End of inlined file: juce_app_includes.h *********/
  40649. #endif
  40650. #if JUCE_MSVC
  40651. #pragma warning (pop)
  40652. #pragma pack (pop)
  40653. #endif
  40654. #if JUCE_MAC
  40655. #pragma align=reset
  40656. #endif
  40657. END_JUCE_NAMESPACE
  40658. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40659. #ifdef JUCE_NAMESPACE
  40660. // this will obviously save a lot of typing, but can be disabled by
  40661. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40662. using namespace JUCE_NAMESPACE;
  40663. /* On the Mac, these symbols are defined in the Mac libraries, so
  40664. these macros make it easier to reference them without writing out
  40665. the namespace every time.
  40666. If you run into difficulties where these macros interfere with the contents
  40667. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40668. the comments in that file for more information.
  40669. */
  40670. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40671. #define Component JUCE_NAMESPACE::Component
  40672. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40673. #define Point JUCE_NAMESPACE::Point
  40674. #define Button JUCE_NAMESPACE::Button
  40675. #endif
  40676. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40677. it easier to use the juce version explicitly.
  40678. If you run into difficulties where this macro interferes with other 3rd party header
  40679. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40680. file for more information.
  40681. */
  40682. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40683. #define Rectangle JUCE_NAMESPACE::Rectangle
  40684. #endif
  40685. #endif
  40686. #endif
  40687. /* Easy autolinking to the right JUCE libraries under win32.
  40688. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40689. including this header file.
  40690. */
  40691. #if JUCE_MSVC
  40692. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40693. /** If you want your application to link to Juce as a DLL instead of
  40694. a static library (on win32), just define the JUCE_DLL macro before
  40695. including juce.h
  40696. */
  40697. #ifdef JUCE_DLL
  40698. #ifdef JUCE_DEBUG
  40699. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40700. #else
  40701. #define AUTOLINKEDLIB "JUCE.lib"
  40702. #endif
  40703. #else
  40704. #ifdef JUCE_DEBUG
  40705. #ifdef _WIN64
  40706. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40707. #else
  40708. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40709. #endif
  40710. #else
  40711. #ifdef _WIN64
  40712. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40713. #else
  40714. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40715. #endif
  40716. #endif
  40717. #endif
  40718. #pragma comment(lib, AUTOLINKEDLIB)
  40719. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40720. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40721. #endif
  40722. // Auto-link the other win32 libs that are needed by library calls..
  40723. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40724. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40725. // Auto-links to various win32 libs that are needed by library calls..
  40726. #pragma comment(lib, "kernel32.lib")
  40727. #pragma comment(lib, "user32.lib")
  40728. #pragma comment(lib, "shell32.lib")
  40729. #pragma comment(lib, "gdi32.lib")
  40730. #pragma comment(lib, "vfw32.lib")
  40731. #pragma comment(lib, "comdlg32.lib")
  40732. #pragma comment(lib, "winmm.lib")
  40733. #pragma comment(lib, "wininet.lib")
  40734. #pragma comment(lib, "ole32.lib")
  40735. #pragma comment(lib, "advapi32.lib")
  40736. #pragma comment(lib, "ws2_32.lib")
  40737. #pragma comment(lib, "comsupp.lib")
  40738. #pragma comment(lib, "version.lib")
  40739. #if JUCE_OPENGL
  40740. #pragma comment(lib, "OpenGL32.Lib")
  40741. #pragma comment(lib, "GlU32.Lib")
  40742. #endif
  40743. #if JUCE_QUICKTIME
  40744. #pragma comment (lib, "QTMLClient.lib")
  40745. #endif
  40746. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40747. #endif
  40748. #endif
  40749. #endif
  40750. /*
  40751. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40752. AppSubClass is the name of a class derived from JUCEApplication.
  40753. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40754. */
  40755. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40756. #define START_JUCE_APPLICATION(AppClass) \
  40757. int main (int argc, char* argv[]) \
  40758. { \
  40759. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40760. }
  40761. #elif JUCE_WIN32
  40762. #ifdef _CONSOLE
  40763. #define START_JUCE_APPLICATION(AppClass) \
  40764. int main (int, char* argv[]) \
  40765. { \
  40766. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40767. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40768. }
  40769. #elif ! defined (_AFXDLL)
  40770. #ifdef _WINDOWS_
  40771. #define START_JUCE_APPLICATION(AppClass) \
  40772. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40773. { \
  40774. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40775. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40776. }
  40777. #else
  40778. #define START_JUCE_APPLICATION(AppClass) \
  40779. int __stdcall WinMain (int, int, const char*, int) \
  40780. { \
  40781. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40782. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40783. }
  40784. #endif
  40785. #endif
  40786. #endif
  40787. #endif // __JUCE_JUCEHEADER__
  40788. /********* End of inlined file: juce.h *********/
  40789. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__